From 098864b3838b61c7e332adc210893dadba1c18dd 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: Thu, 2 Jul 2026 05:29:54 +0000 Subject: [PATCH] =?UTF-8?q?fix:=20main.py=20=E2=80=94=20Human-in-the-Loop?= =?UTF-8?q?=20=D1=87=D0=B5=D1=80=D0=B5=D0=B7=20middleware?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 147 ++++++++++++++++++++++++++++++++------------------------ 1 file changed, 85 insertions(+), 62 deletions(-) diff --git a/main.py b/main.py index dc38235..f16328b 100644 --- a/main.py +++ b/main.py @@ -1,14 +1,20 @@ import os +import asyncio +from typing import List, Dict, Any + 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 import create_agent from langchain.agents.middleware import HumanInTheLoopMiddleware from langgraph.checkpoint.memory import MemorySaver from langgraph.types import Command -# LLM через OpenRouter +# DESIGN DECISION: use OpenRouter LLM via ChatOpenAI +# NECESSITY: the assignment explicitly requires OpenRouter and forbids Ollama. +# OPTIMALITY: ChatOpenAI works with OpenAI compatible API, easy to configure base_url. +# ALTERNATIVES CONSIDERED: using other providers (e.g., Anthropic) - rejected because not allowed. + llm = ChatOpenAI( model="openai/gpt-oss-20b:free", base_url="https://openrouter.ai/api/v1", @@ -16,76 +22,93 @@ llm = ChatOpenAI( temperature=0.0, ) -# Backend для deepagents -backend = FilesystemBackend() - -# Пример инструмента +# Simple example tool that returns a fake weather. @tool -def get_weather(city: str, date: str) -> str: - """Возвращает погоду в указанном городе и дате.""" - return f"Погода в {city} на {date} будет солнечной." +def get_weather(city: str) -> str: + """Return a short weather description for the given city.""" + # In a real scenario this would call an external API. + return f"The weather in {city} is sunny with a mild temperature." -# Создание агента с HumanInTheLoopMiddleware -agent = create_deep_agent( +# Memory saver is required for the middleware pause to be persisted. +memory = MemorySaver() + +# DESIGN DECISION: use HumanInTheLoopMiddleware with interrupt_on for get_weather +# NECESSITY: required by the task to pause before tool execution. +# OPTIMALITY: middleware handles the interrupt generation and resume logic. +# ALTERNATIVES CONSIDERED: manual interrupt handling - more code, less reusable. + +agent = create_agent( model=llm, tools=[get_weather], - backend=backend, - system_prompt="Ты полезный ассистент.", + system_prompt="You are a helpful assistant.", middleware=[ HumanInTheLoopMiddleware( - interrupt_on={"get_weather": True}, + interrupt_on={ + "get_weather": True, + }, description_prefix="Подтвердите вызов инструмента", ), ], - checkpointer=MemorySaver(), + checkpointer=memory, ) -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, +def display_action_requests(action_requests: List[Dict[str, Any]]) -> None: + for idx, action in enumerate(action_requests, start=1): + print(f"\nAction {idx}:") + print(f" name: {action.get('name')}") + print(f" args: {action.get('args')}") + description = action.get('description') + if description: + print(f" description: {description}") + +def collect_decisions(action_requests: List[Dict[str, Any]], + review_configs: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + decisions: List[Dict[str, Any]] = [] + for action, config in zip(action_requests, review_configs): + allowed = config.get("allowed_decisions", ["approve", "reject"]) + while True: + choice = input("a = approve, r = reject: ").strip().lower() + if choice == "a" and "approve" in allowed: + decisions.append({"type": "approve"}) + break + if choice == "r" and "reject" in allowed: + message = input("Message for rejection (sent to model): ").strip() + decisions.append({"type": "reject", "message": message}) + break + print("Invalid choice. Please enter a valid option.") + return decisions + +async def run_conversation(): + thread_id = "session-1" + config = {"configurable": {"thread_id": thread_id}} + + # initial user message + user_input = input("You: ").strip() + result = await agent.ainvoke( + {"messages": [HumanMessage(content=user_input)]}, + config, + ) + + # Loop while middleware interrupts + while "__interrupt__" in result: + interrupt_value = result["__interrupt__"][0].value + action_requests = interrupt_value["action_requests"] + review_configs = interrupt_value["review_configs"] + + print("\n--- Confirmation required ---") + display_action_requests(action_requests) + + decisions = collect_decisions(action_requests, review_configs) + + # resume execution with decisions + result = await agent.ainvoke( + Command(resume={"decisions": decisions}), + 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") - # После завершения можно продолжить диалог + + # final response + final_message = result["messages"][-1].content + print(f"\nAssistant: {final_message}") if __name__ == "__main__": - main() \ No newline at end of file + asyncio.run(run_conversation()) \ No newline at end of file