From 4859872a88f4929efb4f21479641a5112fa80bba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=B0=D0=BD=D0=B8=D0=B8=D0=BB=20=D0=92=D0=B8=D0=BA?= =?UTF-8?q?=D1=82=D0=BE=D1=80=D0=BE=D0=B2?= Date: Tue, 30 Jun 2026 07:44:48 +0000 Subject: [PATCH] add: main.py --- main.py | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 main.py diff --git a/main.py b/main.py new file mode 100644 index 0000000..dc38235 --- /dev/null +++ b/main.py @@ -0,0 +1,91 @@ +import os +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 +from langchain.agents.middleware import HumanInTheLoopMiddleware +from langgraph.checkpoint.memory import MemorySaver +from langgraph.types import Command + +# LLM через OpenRouter +llm = ChatOpenAI( + model="openai/gpt-oss-20b:free", + base_url="https://openrouter.ai/api/v1", + api_key=os.getenv("OPENAI_API_KEY"), + temperature=0.0, +) + +# Backend для deepagents +backend = FilesystemBackend() + +# Пример инструмента +@tool +def get_weather(city: str, date: str) -> str: + """Возвращает погоду в указанном городе и дате.""" + return f"Погода в {city} на {date} будет солнечной." + +# Создание агента с HumanInTheLoopMiddleware +agent = create_deep_agent( + model=llm, + tools=[get_weather], + backend=backend, + system_prompt="Ты полезный ассистент.", + middleware=[ + HumanInTheLoopMiddleware( + interrupt_on={"get_weather": True}, + description_prefix="Подтвердите вызов инструмента", + ), + ], + checkpointer=MemorySaver(), +) + +def main(): + config = {"configurable": {"thread_id": "session-1"}} + while True: + user_input = input("Вы: ") + if not user_input.strip(): + continue + # Первый вызов агента + result = agent.invoke( + {"messages": [HumanMessage(content=user_input)]}, + config=config, + ) + # Цикл обработки пауз + while "__interrupt__" in result: + interrupt = result["__interrupt__"][0].value + action_requests = interrupt.get("action_requests", []) + decisions = [] + print("\n--- Подтверждение ---") + for idx, action in enumerate(action_requests, start=1): + name = action.get("name") + args = action.get("args", {}) + description = action.get("description", "") + print(f"{idx}. Инструмент: {name}") + print(f" Аргументы: {args}") + if description: + print(f" Описание: {description}") + # Запрос решения + while True: + choice = input(" a = approve, r = reject: ").strip().lower() + if choice == "a": + decisions.append({"type": "approve"}) + break + elif choice == "r": + msg = input(" Сообщение для агента (причина отказа): ").strip() + decisions.append({"type": "reject", "message": msg}) + break + else: + print(" Неверный ввод. Попробуйте снова.") + # Возобновляем выполнение + result = agent.invoke( + Command(resume={"decisions": decisions}), + config=config, + ) + # Вывод финального ответа + final_message = result["messages"][-1].content + print(f"\nАгент: {final_message}\n") + # После завершения можно продолжить диалог + +if __name__ == "__main__": + main() \ No newline at end of file