fix: main.py — Human-in-the-Loop через middleware
This commit is contained in:
@@ -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"}}
|
for idx, action in enumerate(action_requests, start=1):
|
||||||
while True:
|
print(f"\nAction {idx}:")
|
||||||
user_input = input("Вы: ")
|
print(f" name: {action.get('name')}")
|
||||||
if not user_input.strip():
|
print(f" args: {action.get('args')}")
|
||||||
continue
|
description = action.get('description')
|
||||||
# Первый вызов агента
|
if description:
|
||||||
result = agent.invoke(
|
print(f" description: {description}")
|
||||||
{"messages": [HumanMessage(content=user_input)]},
|
|
||||||
config=config,
|
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:
|
# final response
|
||||||
interrupt = result["__interrupt__"][0].value
|
final_message = result["messages"][-1].content
|
||||||
action_requests = interrupt.get("action_requests", [])
|
print(f"\nAssistant: {final_message}")
|
||||||
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__":
|
if __name__ == "__main__":
|
||||||
main()
|
asyncio.run(run_conversation())
|
||||||
Reference in New Issue
Block a user