Initial implementation of Human-in-the-Loop agent
This commit is contained in:
@@ -1,105 +1,84 @@
|
|||||||
import os
|
import json
|
||||||
import asyncio
|
from langchain.agents import create_agent
|
||||||
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, LocalShellBackend, CompositeBackend
|
|
||||||
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 langchain_openai import ChatOpenAI
|
||||||
|
from langchain.tools import tool
|
||||||
|
|
||||||
# --- LLM initialization (OpenRouter) -------------------------------------------------
|
# Define a simple get_weather tool
|
||||||
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 setup -------------------------------------------------
|
|
||||||
backend = CompositeBackend([
|
|
||||||
LocalShellBackend(workspace_dir="./workspace"),
|
|
||||||
FilesystemBackend(),
|
|
||||||
])
|
|
||||||
|
|
||||||
# --- Tool definition -------------------------------------------------
|
|
||||||
@tool
|
@tool
|
||||||
def get_weather(city: str, date: str) -> str:
|
def get_weather(city: str, date: str = "today") -> str:
|
||||||
"""Return a mock weather report for the given city and date."""
|
"""Return a mock weather for the given city and date."""
|
||||||
# In a real scenario this would call an external API.
|
|
||||||
return f"The weather in {city} on {date} is sunny with a high of 25°C."
|
return f"The weather in {city} on {date} is sunny with a high of 25°C."
|
||||||
|
|
||||||
# --- Agent creation -------------------------------------------------
|
# Initialize LLM (replace with your OpenRouter key if needed)
|
||||||
agent = create_deep_agent(
|
llm = ChatOpenAI(model="gpt-4o", temperature=0)
|
||||||
|
|
||||||
|
memory = MemorySaver()
|
||||||
|
|
||||||
|
agent = create_agent(
|
||||||
model=llm,
|
model=llm,
|
||||||
tools=[get_weather],
|
tools=[get_weather],
|
||||||
backend=backend,
|
system_prompt="Ты полезный ассистент",
|
||||||
system_prompt="You are a helpful assistant.",
|
|
||||||
middleware=[
|
middleware=[
|
||||||
HumanInTheLoopMiddleware(
|
HumanInTheLoopMiddleware(
|
||||||
interrupt_on={"get_weather": True},
|
interrupt_on={
|
||||||
|
"get_weather": True,
|
||||||
|
},
|
||||||
description_prefix="Подтвердите вызов инструмента",
|
description_prefix="Подтвердите вызов инструмента",
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
checkpointer=MemorySaver(),
|
checkpointer=memory,
|
||||||
)
|
)
|
||||||
|
|
||||||
# --- Helper functions -------------------------------------------------
|
if __name__ == "__main__":
|
||||||
async def prompt_user_for_decisions(action_requests, review_configs):
|
import sys
|
||||||
|
from langgraph.types import Command
|
||||||
|
|
||||||
|
# Simple CLI loop
|
||||||
|
thread_id = "session-1"
|
||||||
|
config = {"configurable": {"thread_id": thread_id}}
|
||||||
|
|
||||||
|
# Initial user message
|
||||||
|
user_msg = " ".join(sys.argv[1:]) or "Какая погода в Казани сегодня?"
|
||||||
|
result = agent.invoke({"messages": [{"role": "human", "content": user_msg}]}, config=config)
|
||||||
|
|
||||||
|
while "__interrupt__" in result:
|
||||||
|
interrupt = result["__interrupt__"][0].value
|
||||||
|
action_requests = interrupt["action_requests"]
|
||||||
|
review_configs = interrupt["review_configs"]
|
||||||
decisions = []
|
decisions = []
|
||||||
for idx, action in enumerate(action_requests):
|
for idx, action in enumerate(action_requests):
|
||||||
print(f"\n--- Подтверждение ---")
|
print(f"\n--- Подтверждение ---")
|
||||||
print(f"Инструмент: {action.get('name')}\n")
|
print(f"Инструмент: {action['name']}")
|
||||||
print(f"Аргументы: {action.get('args')}\n")
|
print(f"Аргументы: {action['args']}")
|
||||||
if "description" in action:
|
if "description" in action:
|
||||||
print(f"Описание: {action['description']}\n")
|
print(f"Описание: {action['description']}")
|
||||||
allowed = review_configs[idx].get("allowed_decisions", ["approve", "reject", "edit"])
|
# Determine allowed decisions
|
||||||
prompt = f"a = approve, r = reject{', e = edit' if 'edit' in allowed else ''}: "
|
allowed = review_configs.get(action['name'], {}).get("allowed_decisions", ["approve", "reject", "edit"]) if isinstance(review_configs.get(action['name']), dict) else ["approve", "reject", "edit"]
|
||||||
|
# Simple input handling
|
||||||
while True:
|
while True:
|
||||||
choice = input(prompt).strip().lower()
|
inp = input("a = approve, r = reject, e = edit: ").strip().lower()
|
||||||
if choice == "a" and "approve" in allowed:
|
if inp == "a" and "approve" in allowed:
|
||||||
decisions.append({"type": "approve"})
|
decisions.append({"type": "approve"})
|
||||||
break
|
break
|
||||||
elif choice == "r" and "reject" in allowed:
|
if inp == "r" and "reject" in allowed:
|
||||||
msg = input("Сообщение для агента (причина отказа): ")
|
msg = input("Введите причину отказа: ")
|
||||||
decisions.append({"type": "reject", "message": msg})
|
decisions.append({"type": "reject", "message": msg})
|
||||||
break
|
break
|
||||||
elif choice == "e" and "edit" in allowed:
|
if inp == "e" and "edit" in allowed:
|
||||||
# Simple edit: ask for new JSON args
|
# For simplicity, ask for new args as JSON
|
||||||
new_args = input("Введите отредактированные аргументы в формате JSON: ")
|
new_args = input("Введите новые аргументы в формате JSON: ")
|
||||||
try:
|
try:
|
||||||
import json
|
new_args_dict = json.loads(new_args)
|
||||||
edited = json.loads(new_args)
|
decisions.append({"type": "edit", "edited_action": {"name": action['name'], "args": new_args_dict}})
|
||||||
decisions.append({"type": "edit", "edited_action": {"name": action['name'], "args": edited}})
|
|
||||||
break
|
break
|
||||||
except json.JSONDecodeError:
|
except Exception as exc:
|
||||||
print("Неверный JSON. Попробуйте снова.")
|
print("Неверный JSON, попробуйте снова.")
|
||||||
else:
|
print("Недопустимый ввод. Попробуйте снова.")
|
||||||
print("Неверный выбор. Попробуйте снова.")
|
# Resume
|
||||||
return decisions
|
result = agent.invoke(Command(resume={"decisions": decisions}), config=config)
|
||||||
|
|
||||||
# --- Main interaction loop -------------------------------------------------
|
|
||||||
async def main():
|
|
||||||
config = {"configurable": {"thread_id": "session-1"}}
|
|
||||||
# Initial user message
|
|
||||||
user_input = input("Вы: ")
|
|
||||||
result = await agent.ainvoke(
|
|
||||||
{"messages": [HumanMessage(content=user_input)]},
|
|
||||||
config,
|
|
||||||
)
|
|
||||||
|
|
||||||
# Process possible interrupts
|
|
||||||
while "__interrupt__" in result:
|
|
||||||
interrupt = result["__interrupt__"][0].value
|
|
||||||
action_requests = interrupt.get("action_requests", [])
|
|
||||||
review_configs = interrupt.get("review_configs", [])
|
|
||||||
decisions = await prompt_user_for_decisions(action_requests, review_configs)
|
|
||||||
result = await agent.ainvoke(Command(resume={"decisions": decisions}), config)
|
|
||||||
|
|
||||||
# Final answer
|
# Final answer
|
||||||
final_message = result["messages"][-1].content
|
final_msg = result["messages"][-1]["content"]
|
||||||
print(f"\nАгент: {final_message}")
|
print("\nАгент: " + final_msg)
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
asyncio.run(main())
|
|
||||||
|
|||||||
Reference in New Issue
Block a user