Skip to content

Instantly share code, notes, and snippets.

@stgmt
Created October 1, 2025 11:03
Show Gist options
  • Select an option

  • Save stgmt/6876872d9993f775d5f5f503d564a05f to your computer and use it in GitHub Desktop.

Select an option

Save stgmt/6876872d9993f775d5f5f503d564a05f to your computer and use it in GitHub Desktop.
from langchain.agents import create_agent
from langchain.agents.middleware import HumanInTheLoopMiddleware
from langchain_core.messages import HumanMessage
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command
# Настройка middleware с указанием инструментов, требующих одобрения
hitl_middleware = HumanInTheLoopMiddleware(
tool_configs=[
{
"tool_name": "delete_file",
"mode": "require_approval" # Требуется одобрение
},
{
"tool_name": "write_file",
"mode": "allow_edit" # Можно редактировать аргументы
}
]
)
# Создание агента
agent = create_agent(
model="claude-sonnet-4-20250514",
tools=[delete_file_tool, write_file_tool],
middleware=[hitl_middleware],
checkpointer=InMemorySaver()
)
config = {"configurable": {"thread_id": "conversation-123"}}
# Первый вызов - агент приостановится
result = agent.invoke(
{"messages": [HumanMessage("Delete old records from database")]},
config
)
# Проверка состояния
state = agent.get_state(config)
if state.next:
request = state["__interrupt__"].value[0]["action_request"]
print("Tool:", request["action"])
print("Arguments:", request["args"])
# Варианты ответа:
# 1. Одобрить
agent.invoke(Command(resume=[{"type": "accept"}]), config=config)
# 2. Отредактировать аргументы
agent.invoke(
Command(resume=[{
"type": "edit",
"args": {
"action": "delete_file",
"args": {"filename": "safe_file.txt"}
}
}]),
config=config
)
# 3. Отклонить
agent.invoke(Command(resume=[{"type": "reject"}]), config=config)
# 4. Дать собственный ответ
agent.invoke(
Command(resume=[{
"type": "response",
"response": "Operation cancelled by user"
}]),
config=config
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment