From fd545e1aba9c902956e6dde7391255d195915008 Mon Sep 17 00:00:00 2001 From: Danil Parunin 5f1b81b8-4f5d-11e8-9c2d-fa7ae01bbebc Date: Tue, 16 Jun 2026 08:19:14 +0000 Subject: [PATCH] =?UTF-8?q?fix(needs=5Ffixes):=201=20=D0=B8=D1=81=D0=BF?= =?UTF-8?q?=D1=80=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B9,=200=20=D0=BE?= =?UTF-8?q?=D1=82=D1=81=D1=82=D0=BE=D1=8F=D0=BD=D0=BE=20=E2=80=94=20main.p?= =?UTF-8?q?y?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 84 +++++++++++++++++++-------------------------------------- 1 file changed, 27 insertions(+), 57 deletions(-) diff --git a/main.py b/main.py index 6765fc2..eeaaed5 100644 --- a/main.py +++ b/main.py @@ -1,83 +1,53 @@ -import asyncio import os +import asyncio from langchain_openai import ChatOpenAI -from langchain_core.messages import HumanMessage from langchain.tools import tool -from deepagents import create_deep_agent -from deepagents.backends import FilesystemBackend, LocalShellBackend, CompositeBackend +from langchain.agents import create_agent +from langchain_core.messages import HumanMessage -# --- LLM configuration ----------------------------------------------------- -# Connect to the local LM Studio server. Replace '' with the exact -# name of the model you have loaded in LM Studio. +# Настройка LLM через OpenRouter llm = ChatOpenAI( - model='', - base_url='http://localhost:1234/v1', - api_key=os.getenv('OPENAI_API_KEY', 'fake'), + model="openai/gpt-oss-20b:free", + base_url="https://openrouter.ai/api/v1", + api_key=os.getenv("OPENAI_API_KEY"), temperature=0.7, ) -# --- Backend --------------------------------------------------------------- -backend = CompositeBackend([ - LocalShellBackend(workspace_dir="./workspace"), - FilesystemBackend(), -]) - -# --- Sub‑agent tool -------------------------------------------------------- +# Инструмент, который вызывает субагент для получения цены @tool def get_price(product: str, city: str) -> str: - """Return a realistic price for a product in a given city. - - The function internally creates a sub‑agent that asks the LLM to generate - a price table. The sub‑agent is a lightweight wrapper around the same - LLM instance to keep the example simple. + """Получить примерную цену продукта в указанном городе. + Возвращает таблицу в формате Markdown. """ - # Create a sub‑agent that only has the task of generating a price table. - sub_agent = create_deep_agent( + # Создаём субагент, который генерирует таблицу + sub_agent = create_agent( model=llm, tools=[], - backend=backend, - system_prompt=f"You are a market analyst. Provide a realistic price for {product} in {city}. Output a markdown table with columns: Продукт, Цена (руб.), Магазин.", + system_prompt=f"Ты эксперт по ценам в {city}.\n\nДай таблицу: | Продукт | Цена (руб.) | Магазин |", # простая подсказка ) - # Invoke the sub‑agent with a simple prompt. - result = asyncio.run( - sub_agent.ainvoke( - {"messages": [HumanMessage(content=f"Generate price for {product} in {city}")]}, - {"configurable": {"thread_id": f"price-{product}-{city}"}}, - ) - ) - # Return the content of the last message (the table). + # Запускаем субагент с запросом + sub_prompt = f"Какова примерная цена на {product} в {city}?" + result = sub_agent.invoke({"messages": [HumanMessage(content=sub_prompt)]}) + # Извлекаем последний текстовый ответ return result["messages"][-1].content -# --- Main agent ------------------------------------------------------------ -main_agent = create_deep_agent( +# Главный агент +agent = create_agent( model=llm, tools=[get_price], - backend=backend, system_prompt="Ты помощник по планированию покупок.", ) -# --- Helper to pretty‑print the conversation ------------------------------ -from langchain_core.messages import BaseMessage - -def format_message(msg: BaseMessage) -> str: - if hasattr(msg, "content") and msg.content: - return msg.content - if hasattr(msg, "tool_calls") and msg.tool_calls: - call = msg.tool_calls[0] - return f"{call['name']}({call['args']})" - return "" - -# --- Main entry point ------------------------------------------------------ async def main(): - user_prompt = "Помоги составить список покупок: молоко, хлеб, яблоки. Я нахожусь в Казани." - result = await main_agent.ainvoke( - {"messages": [HumanMessage(content=user_prompt)]}, - {"configurable": {"thread_id": "shopping-session"}}, - ) - # Print all messages in order + user_query = "Помоги составить список покупок: молоко, хлеб, яблоки. Я нахожусь в Казани." + result = await agent.ainvoke({"messages": [HumanMessage(content=user_query)]}) + # Печатаем все сообщения, включая вызовы инструментов for msg in result["messages"]: - print(format_message(msg)) - print("---") + if msg.content: + print(msg.content) + elif msg.tool_calls: + for call in msg.tool_calls: + print(f"{call['name']}({call['args']})") if __name__ == "__main__": asyncio.run(main())