Files
task-69a86305c46fd26feae6bcaa/main.py
T
2026-06-30 07:44:48 +00:00

91 lines
3.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import os
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.middleware import HumanInTheLoopMiddleware
from langgraph.checkpoint.memory import MemorySaver
from langgraph.types import Command
# LLM через OpenRouter
llm = ChatOpenAI(
model="openai/gpt-oss-20b:free",
base_url="https://openrouter.ai/api/v1",
api_key=os.getenv("OPENAI_API_KEY"),
temperature=0.0,
)
# Backend для deepagents
backend = FilesystemBackend()
# Пример инструмента
@tool
def get_weather(city: str, date: str) -> str:
"""Возвращает погоду в указанном городе и дате."""
return f"Погода в {city} на {date} будет солнечной."
# Создание агента с HumanInTheLoopMiddleware
agent = create_deep_agent(
model=llm,
tools=[get_weather],
backend=backend,
system_prompt="Ты полезный ассистент.",
middleware=[
HumanInTheLoopMiddleware(
interrupt_on={"get_weather": True},
description_prefix="Подтвердите вызов инструмента",
),
],
checkpointer=MemorySaver(),
)
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,
)
# Цикл обработки пауз
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")
# После завершения можно продолжить диалог
if __name__ == "__main__":
main()