Human-in-the-Loop через middleware: solution.py
This commit is contained in:
@@ -1,3 +1,4 @@
|
|||||||
|
# solution.py
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""
|
"""
|
||||||
Пример агента с Human‑in‑the‑loop, реализованный в LangGraph.
|
Пример агента с Human‑in‑the‑loop, реализованный в LangGraph.
|
||||||
@@ -8,6 +9,8 @@ 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.tools import tool
|
||||||
|
from langchain_core.messages import ToolMessage
|
||||||
|
|
||||||
|
|
||||||
# 1. Модель LLM (пример с OpenAI‑совместимым API)
|
# 1. Модель LLM (пример с OpenAI‑совместимым API)
|
||||||
llm = ChatOpenAI(
|
llm = ChatOpenAI(
|
||||||
@@ -33,32 +36,41 @@ agent = create_react_agent(
|
|||||||
interrupt_before=["tools"], # включаем human‑in‑the‑loop
|
interrupt_before=["tools"], # включаем human‑in‑the‑loop
|
||||||
)
|
)
|
||||||
|
|
||||||
# 5. Запуск и цикл обработки прерываний
|
# 5. Основная логика взаимодействия
|
||||||
config = {"configurable": {"thread_id": "session-1"}}
|
def main() -> None:
|
||||||
result = agent.invoke(
|
config = {"configurable": {"thread_id": "session-1"}}
|
||||||
{"messages": [{"role": "human", "content": "Какая погода в Казани сегодня?"}]},
|
while True:
|
||||||
|
user_input = input("Вы: ")
|
||||||
|
if user_input.lower() in {"выход", "exit", "quit"}:
|
||||||
|
print("Завершение работы.")
|
||||||
|
break
|
||||||
|
# первый вызов агента
|
||||||
|
result = agent.invoke(
|
||||||
|
{"messages": [{"role": "human", "content": user_input}]},
|
||||||
config=config,
|
config=config,
|
||||||
)
|
)
|
||||||
|
# цикл обработки прерываний
|
||||||
while "__interrupt__" in result:
|
while "__interrupt__" in result:
|
||||||
# Последнее сообщение содержит вызов инструмента
|
|
||||||
last_msg = result["messages"][-1]
|
last_msg = result["messages"][-1]
|
||||||
tool_call = last_msg.tool_calls[0] # предполагаем один вызов
|
tool_call = last_msg.tool_calls[0] # один вызов инструмента
|
||||||
name = tool_call["name"]
|
name = tool_call["name"]
|
||||||
args = tool_call.get("args", {})
|
args = tool_call["args"]
|
||||||
print(f"\nИнструмент: {name}")
|
print(f"\nИнструмент: {name}")
|
||||||
print(f"Аргументы: {args}")
|
print(f"Аргументы: {args}")
|
||||||
|
|
||||||
choice = input("a=approve, r=reject: ").strip().lower()
|
choice = input("a=approve, r=reject: ").strip().lower()
|
||||||
if choice == "r":
|
if choice == "r":
|
||||||
msg = input("Причина отказа: ")
|
reason = input("Причина отказа: ")
|
||||||
decisions = [{"type": "reject", "message": msg}]
|
# передаем ToolMessage как результат вызова инструмента
|
||||||
|
result = agent.invoke(
|
||||||
|
{"messages": [ToolMessage(content=reason, tool_call_id=tool_call["id"])]},
|
||||||
|
config=config,
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
decisions = [{"type": "approve"}]
|
# approve – просто возобновляем без сообщения
|
||||||
|
result = agent.invoke(Command(resume=None), config=config)
|
||||||
|
# вывод финального ответа агента
|
||||||
|
final_answer = result["messages"][-1].content
|
||||||
|
print("\nОтвет агента:\n", final_answer)
|
||||||
|
|
||||||
# Возобновляем выполнение
|
if __name__ == "__main__":
|
||||||
result = agent.invoke(Command(resume=decisions), config=config)
|
main()
|
||||||
|
|
||||||
# 6. Финальный ответ
|
|
||||||
final_answer = result["messages"][-1].content
|
|
||||||
print("\nОтвет агента:\n", final_answer)
|
|
||||||
Reference in New Issue
Block a user