Обновить solutions/69a86305c46fd26feae6bcaa_Human-in-the-Loop_через_middleware/solution.py
This commit is contained in:
@@ -1,21 +1,22 @@
|
|||||||
# solution.py
|
# solution.py
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""
|
"""
|
||||||
Пример агента с Human‑in‑the‑loop, реализованный в LangGraph.
|
Пример агента с Human-in-the-Loop через HumanInTheLoopMiddleware.
|
||||||
|
При каждом вызове инструмента агент останавливается,
|
||||||
|
выводит информацию и ожидает решения пользователя: approve / reject.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from langchain_openai import ChatOpenAI
|
from langchain_openai import ChatOpenAI
|
||||||
|
from langchain.tools import tool
|
||||||
|
from langchain.agents.middleware import HumanInTheLoopMiddleware
|
||||||
from langgraph.prebuilt import create_react_agent
|
from langgraph.prebuilt import create_react_agent
|
||||||
from langgraph.checkpoint.memory import MemorySaver
|
from langgraph.checkpoint.memory import MemorySaver
|
||||||
from langgraph.types import Command
|
from langgraph.types import Command
|
||||||
from langchain.tools import tool
|
|
||||||
from langchain_core.messages import ToolMessage
|
|
||||||
|
|
||||||
|
# 1. Модель LLM
|
||||||
# 1. Модель LLM (пример с OpenAI‑совместимым API)
|
|
||||||
llm = ChatOpenAI(
|
llm = ChatOpenAI(
|
||||||
model="gpt-4o-mini", # замените на нужную модель
|
model="gpt-4o-mini",
|
||||||
temperature=0.7,
|
temperature=0,
|
||||||
)
|
)
|
||||||
|
|
||||||
# 2. Простой инструмент
|
# 2. Простой инструмент
|
||||||
@@ -24,53 +25,90 @@ def get_weather(city: str, date: str) -> str:
|
|||||||
"""Возвращает погоду в городе на указанную дату."""
|
"""Возвращает погоду в городе на указанную дату."""
|
||||||
return f"Погода в {city} на {date}: солнечно 25°C."
|
return f"Погода в {city} на {date}: солнечно 25°C."
|
||||||
|
|
||||||
# 3. Хранилище памяти для чекпоинтера
|
# 3. Хранилище памяти
|
||||||
memory = MemorySaver()
|
memory = MemorySaver()
|
||||||
|
|
||||||
# 4. Создание агента с interrupt_before=["tools"]
|
# 4. Создание агента с HumanInTheLoopMiddleware
|
||||||
agent = create_react_agent(
|
agent = create_react_agent(
|
||||||
tools=[get_weather],
|
|
||||||
model=llm,
|
model=llm,
|
||||||
|
tools=[get_weather],
|
||||||
system_prompt="Ты полезный ассистент, отвечай точно.",
|
system_prompt="Ты полезный ассистент, отвечай точно.",
|
||||||
checkpointer=memory,
|
checkpointer=memory,
|
||||||
interrupt_before=["tools"], # включаем human‑in‑the‑loop
|
middleware=[
|
||||||
|
HumanInTheLoopMiddleware(
|
||||||
|
interrupt_on={
|
||||||
|
"get_weather": True, # прерывать на каждом вызове get_weather
|
||||||
|
},
|
||||||
|
description_prefix="Подтвердите вызов инструмента",
|
||||||
|
),
|
||||||
|
],
|
||||||
)
|
)
|
||||||
|
|
||||||
# 5. Основная логика взаимодействия
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
|
"""
|
||||||
|
Запускает чат-цикл с human-in-the-loop:
|
||||||
|
пользователь вводит запрос, агент останавливается перед вызовом
|
||||||
|
инструмента и ждёт подтверждения (approve / reject).
|
||||||
|
"""
|
||||||
config = {"configurable": {"thread_id": "session-1"}}
|
config = {"configurable": {"thread_id": "session-1"}}
|
||||||
|
|
||||||
|
print("Привет! Введите запрос или 'выход' для завершения.")
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
user_input = input("Вы: ")
|
user_input = input("\nВы: ").strip()
|
||||||
if user_input.lower() in {"выход", "exit", "quit"}:
|
if user_input.lower() in {"выход", "exit", "quit"}:
|
||||||
print("Завершение работы.")
|
print("Завершение работы.")
|
||||||
break
|
break
|
||||||
# первый вызов агента
|
|
||||||
|
# Первый вызов агента
|
||||||
result = agent.invoke(
|
result = agent.invoke(
|
||||||
{"messages": [{"role": "human", "content": user_input}]},
|
{"messages": [{"role": "human", "content": user_input}]},
|
||||||
config=config,
|
config=config,
|
||||||
)
|
)
|
||||||
# цикл обработки прерываний
|
|
||||||
|
# Цикл обработки прерываний
|
||||||
while "__interrupt__" in result:
|
while "__interrupt__" in result:
|
||||||
last_msg = result["messages"][-1]
|
interrupt_payload = result["__interrupt__"][0].value
|
||||||
tool_call = last_msg.tool_calls[0] # один вызов инструмента
|
action_requests = interrupt_payload.get("action_requests", [])
|
||||||
name = tool_call["name"]
|
review_configs = interrupt_payload.get("review_configs", {})
|
||||||
args = tool_call["args"]
|
|
||||||
print(f"\nИнструмент: {name}")
|
decisions = []
|
||||||
|
|
||||||
|
for req in action_requests:
|
||||||
|
name = req.get("name", "неизвестный инструмент")
|
||||||
|
args = req.get("args", {})
|
||||||
|
description = req.get("description", "")
|
||||||
|
|
||||||
|
print("\n--- Подтверждение ---")
|
||||||
|
print(f"Инструмент: {name}")
|
||||||
|
if description:
|
||||||
|
print(f"Описание: {description}")
|
||||||
print(f"Аргументы: {args}")
|
print(f"Аргументы: {args}")
|
||||||
|
|
||||||
|
# Показываем разрешённые решения из review_configs
|
||||||
|
allowed = review_configs.get(name, {}).get(
|
||||||
|
"allowed_decisions", ["approve", "reject"]
|
||||||
|
)
|
||||||
|
print(f"Разрешённые решения: {allowed}")
|
||||||
|
|
||||||
choice = input("a=approve, r=reject: ").strip().lower()
|
choice = input("a=approve, r=reject: ").strip().lower()
|
||||||
if choice == "r":
|
if choice == "r":
|
||||||
reason = input("Причина отказа: ")
|
reason = input("Причина отказа: ").strip()
|
||||||
# передаем ToolMessage как результат вызова инструмента
|
decisions.append({"type": "reject", "message": reason})
|
||||||
|
else:
|
||||||
|
decisions.append({"type": "approve"})
|
||||||
|
|
||||||
|
# Возобновляем выполнение агента с решениями
|
||||||
result = agent.invoke(
|
result = agent.invoke(
|
||||||
{"messages": [ToolMessage(content=reason, tool_call_id=tool_call["id"])]},
|
Command(resume={"decisions": decisions}),
|
||||||
config=config,
|
config=config,
|
||||||
)
|
)
|
||||||
else:
|
|
||||||
# approve – просто возобновляем без сообщения
|
# Финальный ответ агента
|
||||||
result = agent.invoke(Command(resume=None), config=config)
|
|
||||||
# вывод финального ответа агента
|
|
||||||
final_answer = result["messages"][-1].content
|
final_answer = result["messages"][-1].content
|
||||||
print("\nОтвет агента:\n", final_answer)
|
print(f"\nАгент: {final_answer}")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
Reference in New Issue
Block a user