add main.py
This commit is contained in:
@@ -4,8 +4,9 @@ from langchain.agents import create_agent
|
|||||||
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
|
||||||
|
from langchain.tools import tool
|
||||||
|
|
||||||
# LLM setup
|
# LLM configuration
|
||||||
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",
|
||||||
@@ -13,19 +14,15 @@ llm = ChatOpenAI(
|
|||||||
temperature=0.0,
|
temperature=0.0,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Simple tool: get_weather
|
# Simple weather tool
|
||||||
from langchain.tools import tool
|
|
||||||
|
|
||||||
@tool
|
@tool
|
||||||
def get_weather(city: str, date: str = "сегодня") -> str:
|
def get_weather(city: str, date: str = "сегодня") -> str:
|
||||||
"""Return a mock weather description for the given city and date."""
|
"""Return a mock weather description for a city and date."""
|
||||||
# In a real scenario, call an API. Here we return a placeholder.
|
|
||||||
return f"Погода в {city} на {date}: солнечно, 25°C."
|
return f"Погода в {city} на {date}: солнечно, 25°C."
|
||||||
|
|
||||||
# Memory for middleware
|
# Agent with HumanInTheLoopMiddleware
|
||||||
memory = MemorySaver()
|
memory = MemorySaver()
|
||||||
|
|
||||||
# Agent with HumanInTheLoopMiddleware
|
|
||||||
agent = create_agent(
|
agent = create_agent(
|
||||||
model=llm,
|
model=llm,
|
||||||
tools=[get_weather],
|
tools=[get_weather],
|
||||||
@@ -33,7 +30,7 @@ agent = create_agent(
|
|||||||
middleware=[
|
middleware=[
|
||||||
HumanInTheLoopMiddleware(
|
HumanInTheLoopMiddleware(
|
||||||
interrupt_on={
|
interrupt_on={
|
||||||
"get_weather": True, # allow approve, edit, reject
|
"get_weather": True,
|
||||||
},
|
},
|
||||||
description_prefix="Подтвердите вызов инструмента",
|
description_prefix="Подтвердите вызов инструмента",
|
||||||
),
|
),
|
||||||
@@ -42,13 +39,12 @@ agent = create_agent(
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Helper to process interrupt and get decisions
|
# Helper to process interrupt and get decisions
|
||||||
|
|
||||||
def handle_interrupt(interrupt_value):
|
def handle_interrupt(interrupt_value):
|
||||||
action_requests = interrupt_value["action_requests"]
|
action_requests = interrupt_value["action_requests"]
|
||||||
decisions = []
|
decisions = []
|
||||||
for idx, action in enumerate(action_requests, 1):
|
for idx, action in enumerate(action_requests, 1):
|
||||||
name = action.get("name")
|
name = action.get("name")
|
||||||
args = action.get("args")
|
args = action.get("args", {})
|
||||||
description = action.get("description", "")
|
description = action.get("description", "")
|
||||||
print(f"\n--- Подтверждение {idx} ---")
|
print(f"\n--- Подтверждение {idx} ---")
|
||||||
print(f"Инструмент: {name}")
|
print(f"Инструмент: {name}")
|
||||||
@@ -61,7 +57,7 @@ def handle_interrupt(interrupt_value):
|
|||||||
decisions.append({"type": "approve"})
|
decisions.append({"type": "approve"})
|
||||||
break
|
break
|
||||||
elif choice == "r":
|
elif choice == "r":
|
||||||
msg = input("Причина отказа: ")
|
msg = input("Сообщение для агента (причина отказа): ")
|
||||||
decisions.append({"type": "reject", "message": msg})
|
decisions.append({"type": "reject", "message": msg})
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
@@ -72,10 +68,10 @@ def handle_interrupt(interrupt_value):
|
|||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
config = {"configurable": {"thread_id": "сессия-1"}}
|
config = {"configurable": {"thread_id": "сессия-1"}}
|
||||||
while True:
|
while True:
|
||||||
user_input = input("Вы: ")
|
user_input = input("\nВы: ")
|
||||||
if not user_input:
|
if not user_input:
|
||||||
continue
|
continue
|
||||||
# Initial invoke
|
# First invoke
|
||||||
result = agent.invoke(
|
result = agent.invoke(
|
||||||
{"messages": [{"role": "human", "content": user_input}]},
|
{"messages": [{"role": "human", "content": user_input}]},
|
||||||
config=config,
|
config=config,
|
||||||
@@ -85,10 +81,9 @@ if __name__ == "__main__":
|
|||||||
interrupt = result["__interrupt__"][0].value
|
interrupt = result["__interrupt__"][0].value
|
||||||
decisions = handle_interrupt(interrupt)
|
decisions = handle_interrupt(interrupt)
|
||||||
result = agent.invoke(Command(resume={"decisions": decisions}), config=config)
|
result = agent.invoke(Command(resume={"decisions": decisions}), config=config)
|
||||||
# Final answer
|
# Output final answer
|
||||||
if result.get("messages"):
|
if result.get("messages"):
|
||||||
answer = result["messages"][-1].content
|
print("\nАгент:", result["messages"][-1].content)
|
||||||
print(f"\nАгент: {answer}\n")
|
|
||||||
else:
|
else:
|
||||||
print("\nАгент не ответил.\n")
|
print("\nАгент не ответил.")
|
||||||
# Continue loop for next user query
|
# Continue loop for next user query
|
||||||
|
|||||||
Reference in New Issue
Block a user