fix: main.py — Human-in-the-Loop через middleware

This commit is contained in:
2026-07-02 05:29:54 +00:00
parent 9186393d06
commit 098864b383
+77 -54
View File
@@ -1,14 +1,20 @@
import os import os
import asyncio
from typing import List, Dict, Any
from langchain_openai import ChatOpenAI from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage from langchain_core.messages import HumanMessage
from langchain.tools import tool from langchain.tools import tool
from deepagents import create_deep_agent from langchain.agents import create_agent
from deepagents.backends import FilesystemBackend
from langchain.agents.middleware import HumanInTheLoopMiddleware from langchain.agents.middleware import HumanInTheLoopMiddleware
from langgraph.checkpoint.memory import MemorySaver from langgraph.checkpoint.memory import MemorySaver
from langgraph.types import Command 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( llm = ChatOpenAI(
model="openai/gpt-oss-20b:free", model="openai/gpt-oss-20b:free",
base_url="https://openrouter.ai/api/v1", base_url="https://openrouter.ai/api/v1",
@@ -16,76 +22,93 @@ llm = ChatOpenAI(
temperature=0.0, temperature=0.0,
) )
# Backend для deepagents # Simple example tool that returns a fake weather.
backend = FilesystemBackend()
# Пример инструмента
@tool @tool
def get_weather(city: str, date: str) -> str: def get_weather(city: str) -> str:
"""Возвращает погоду в указанном городе и дате.""" """Return a short weather description for the given city."""
return f"Погода в {city} на {date} будет солнечной." # In a real scenario this would call an external API.
return f"The weather in {city} is sunny with a mild temperature."
# Создание агента с HumanInTheLoopMiddleware # Memory saver is required for the middleware pause to be persisted.
agent = create_deep_agent( 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, model=llm,
tools=[get_weather], tools=[get_weather],
backend=backend, system_prompt="You are a helpful assistant.",
system_prompt="Ты полезный ассистент.",
middleware=[ middleware=[
HumanInTheLoopMiddleware( HumanInTheLoopMiddleware(
interrupt_on={"get_weather": True}, interrupt_on={
"get_weather": True,
},
description_prefix="Подтвердите вызов инструмента", description_prefix="Подтвердите вызов инструмента",
), ),
], ],
checkpointer=MemorySaver(), checkpointer=memory,
) )
def main(): def display_action_requests(action_requests: List[Dict[str, Any]]) -> None:
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): for idx, action in enumerate(action_requests, start=1):
name = action.get("name") print(f"\nAction {idx}:")
args = action.get("args", {}) print(f" name: {action.get('name')}")
description = action.get("description", "") print(f" args: {action.get('args')}")
print(f"{idx}. Инструмент: {name}") description = action.get('description')
print(f" Аргументы: {args}")
if description: if description:
print(f" Описание: {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: while True:
choice = input("a = approve, r = reject: ").strip().lower() choice = input("a = approve, r = reject: ").strip().lower()
if choice == "a": if choice == "a" and "approve" in allowed:
decisions.append({"type": "approve"}) decisions.append({"type": "approve"})
break break
elif choice == "r": if choice == "r" and "reject" in allowed:
msg = input(" Сообщение для агента (причина отказа): ").strip() message = input("Message for rejection (sent to model): ").strip()
decisions.append({"type": "reject", "message": msg}) decisions.append({"type": "reject", "message": message})
break break
else: print("Invalid choice. Please enter a valid option.")
print(" Неверный ввод. Попробуйте снова.") return decisions
# Возобновляем выполнение
result = agent.invoke( async def run_conversation():
Command(resume={"decisions": decisions}), thread_id = "session-1"
config=config, 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,
)
# final response
final_message = result["messages"][-1].content final_message = result["messages"][-1].content
print(f"\nАгент: {final_message}\n") print(f"\nAssistant: {final_message}")
# После завершения можно продолжить диалог
if __name__ == "__main__": if __name__ == "__main__":
main() asyncio.run(run_conversation())