add main.py

This commit is contained in:
2026-05-25 22:36:15 +00:00
parent 4c509acbc8
commit 78240601d0
+20 -15
View File
@@ -1,5 +1,4 @@
import os
import json
from langchain_openai import ChatOpenAI
from langchain.agents import create_agent
from langchain.agents.middleware import HumanInTheLoopMiddleware
@@ -20,33 +19,36 @@ from langchain.tools import tool
@tool
def get_weather(city: str, date: str = "сегодня") -> str:
"""Return a mock weather description for the given city and date."""
# In a real scenario, call an API. Here we return a deterministic string.
# In a real scenario, call an API. Here we return a placeholder.
return f"Погода в {city} на {date}: солнечно, 25°C."
# Agent with HumanInTheLoopMiddleware
# Memory for middleware
memory = MemorySaver()
# Agent with HumanInTheLoopMiddleware
agent = create_agent(
model=llm,
tools=[get_weather],
system_prompt="Ты полезный ассистент.",
middleware=[
HumanInTheLoopMiddleware(
interrupt_on={"get_weather": True},
interrupt_on={
"get_weather": True, # allow approve, edit, reject
},
description_prefix="Подтвердите вызов инструмента",
),
],
checkpointer=memory,
)
# Helper to process interrupt and collect decisions
# Helper to process interrupt and get decisions
def handle_interrupt(interrupt_value):
action_requests = interrupt_value["action_requests"]
decisions = []
for idx, action in enumerate(action_requests, 1):
name = action.get("name")
args = action.get("args", {})
args = action.get("args")
description = action.get("description", "")
print(f"\n--- Подтверждение {idx} ---")
print(f"Инструмент: {name}")
@@ -59,7 +61,7 @@ def handle_interrupt(interrupt_value):
decisions.append({"type": "approve"})
break
elif choice == "r":
msg = input("Сообщение для агента (причина отказа): ")
msg = input("Причина отказа: ")
decisions.append({"type": "reject", "message": msg})
break
else:
@@ -70,12 +72,14 @@ def handle_interrupt(interrupt_value):
if __name__ == "__main__":
config = {"configurable": {"thread_id": "сессия-1"}}
while True:
user_input = input("\nВы: ")
if user_input.lower() in {"exit", "quit"}:
print("Завершение.")
break
user_input = input("Вы: ")
if not user_input:
continue
# Initial invoke
result = agent.invoke({"messages": [{"role": "human", "content": user_input}]}, config=config)
result = agent.invoke(
{"messages": [{"role": "human", "content": user_input}]},
config=config,
)
# Process interrupts
while "__interrupt__" in result:
interrupt = result["__interrupt__"][0].value
@@ -83,7 +87,8 @@ if __name__ == "__main__":
result = agent.invoke(Command(resume={"decisions": decisions}), config=config)
# Final answer
if result.get("messages"):
final_msg = result["messages"][-1].content
print(f"\nАгент: {final_msg}")
answer = result["messages"][-1].content
print(f"\nАгент: {answer}\n")
else:
print("\nАгент не вернул ответа.")
print("\nАгент не ответил.\n")
# Continue loop for next user query