Human-in-the-Loop через middleware: README.md

This commit is contained in:
2026-05-28 05:40:27 +00:00
parent ec3b52184b
commit e92f36d093
@@ -1,109 +1,139 @@
# HumanintheLoop через Middleware
# HumanintheLoop Agent via Middleware
Пример реализации агента на LangGraph с встроенным `HumanInTheLoopMiddleware`.
При каждом вызове инструмента агент останавливается и выводит в терминал запрос
на подтверждение (`approve` / `reject`). После ответа пользователь может
продолжить выполнение, а агент продолжит работу.
This repository contains a minimal example of an LLM agent that pauses whenever it wants to call a tool and asks the user for approval before proceeding.
The core idea is to use **`HumanInTheLoopMiddleware`** from LangChain, which intercepts every tool invocation, prints a prompt with the action details, and waits for the user to respond (`approve`, `reject`, or optionally edit the request).
> **Why this matters** In many realworld scenarios you want an LLM to ask for human confirmation before performing potentially sensitive actions (e.g., sending emails, accessing databases, calling external APIs).
---
## 📦 Установка зависимостей
## Table of Contents
- [Project Structure](#project-structure)
- [Installation](#installation)
- [Running the Agent](#running-the-agent)
- [Interactive Mode](#interactive-mode)
- [Scripted Example](#scripted-example)
- [Example Usage](#example-usage)
- [Extending the Agent](#extending-the-agent)
---
## Project Structure
```
├── solution.py # Main script with the agent implementation
└── README.md # This file
```
`solution.py` contains:
1. **LLM configuration** uses `ChatOpenAI`.
2. **A simple tool** (`get_weather`) that returns a fake weather string.
3. **Memory checkpoint** via `MemorySaver`.
4. **Agent creation** with `create_react_agent` and the middleware.
5. **Execution loop** that keeps asking for user input until the conversation ends.
---
## Installation
1. **Clone the repo**
```bash
git clone https://github.com/your-username/human-in-the-loop-agent.git
cd human-in-the-loop-agent
```
2. **Create a virtual environment (optional but recommended)**
```bash
# Создайте виртуальное окружение (рекомендуется)
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Установите необходимые пакеты
pip install langgraph langchain-core langchain-openai openai tqdm
source .venv/bin/activate # On Windows: .venv\Scripts\activate
```
> **Важно**
> Для работы с OpenAI API понадобится переменная окружения `OPENAI_API_KEY`.
> ```bash
> export OPENAI_API_KEY="sk-..."
> ```
3. **Install dependencies**
---
```bash
pip install --upgrade pip
pip install langchain langgraph openai
```
## 📁 Структура проекта
4. **Set your OpenAI API key**
```text
.
├── solution.py # Основной скрипт, реализующий агент
└── README.md # Текущий файл
```bash
export OPENAI_API_KEY="sk-..."
# Windows: setx OPENAI_API_KEY "sk-..."
```
---
## ▶️ Запуск
## Running the Agent
### 1. Запустите скрипт из командной строки
### Interactive Mode
Simply run the script:
```bash
python solution.py
```
> Скрипт автоматически создаст агента, подключит middleware и начнет диалог с пользователем.
### 2. Взаимодействие в терминале
После каждого вызова инструмента вы увидите сообщение вида:
You will see a prompt like:
```
⚠️ Инструмент: get_weather
Запрос: "Какая погода в Москве на 2024‑06‑01?"
Нужно подтвердить действие (approve/reject):
Agent wants to call tool `get_weather` with arguments:
city = "Moscow"
date = "2025-10-01"
Please type one of: approve / reject (or edit <new_args>)
>
```
- Введите `approve` – инструмент будет выполнен и результат вернётся агенту.
- Введите `reject` – вызов инструмента отменяется, агент продолжит работу без него.
Type **`approve`** to let the agent proceed, or **`reject`** to stop it.
If you want to modify the arguments before approval, use `edit city=London date=2025-12-25`.
The conversation continues until the user types `stop` or the agent finishes its plan.
### Scripted Example
You can also run a quick demo that automatically approves all calls:
```bash
python - <<'PY'
from solution import agent, llm, memory
# Override middleware to autoapprove for demonstration
agent.middleware[0].interrupt_on = {"get_weather": False}
print(agent.run("What's the weather in New York tomorrow?"))
PY
```
---
## 📄 Пример использования
## Example Usage
```python
from langgraph.prebuilt import create_react_agent
from langchain.tools import tool
from langgraph.checkpoint.memory import MemorySaver
from langgraph.types import Command
from langgraph.moderation import HumanInTheLoopMiddleware
```bash
$ python solution.py
User: What's the weather in Paris next Friday?
Agent wants to call tool `get_weather` with arguments:
city = "Paris"
date = "2025-10-06"
# 1. Определяем инструмент
@tool
def get_weather(city: str, date: str) -> str:
"""Возвращает погоду в городе на указанную дату."""
return f"Погода в {city} на {date}: солнечно 25°C."
Please type one of: approve / reject (or edit <new_args>)
> approve
# 2. Создаём агент с middleware
memory = MemorySaver()
agent = create_react_agent(
tools=[get_weather],
memory=memory,
middleware=[HumanInTheLoopMiddleware()],
)
# 3. Запускаем диалог
config = {"thread_id": "session-1"}
state = agent.invoke({"messages": [{"role": "user", "content": "Какая погода в Москве на 2024‑06‑01?"}]}, config=config)
print(state["messages"][-1]["content"])
Assistant: Погода в Париже на 2025‑10‑06: солнечно 25°C.
User: Thank you!
```
> После запуска вы увидите запрос подтверждения и сможете взаимодействовать с агентом, как описано выше.
---
## Extending the Agent
1. **Add more tools** decorate any function with `@tool` and add it to the `tools` list in `create_react_agent`.
2. **Change the interrupt policy** modify `interrupt_on` dict (e.g., `{ "get_weather": True, "send_email": False }`).
3. **Persist conversation state** replace `MemorySaver()` with a database checkpoint if you need longterm memory.
4. **Custom prompts** tweak `system_prompt` or add a custom `description_prefix`.
---
## 📚 Полезные ссылки
- [Документация LangChain HumanintheLoop](https://docs.langchain.com/oss/python/langchain/human-in-the-loop)
- [LangGraph GitHub репозиторий](https://github.com/run-llama/langgraph)
---
## 🤝 Вклад
Если вы нашли ошибки или хотите добавить новые инструменты, создайте pull request.
Пожалуйста, придерживайтесь стиля кода из `solution.py` и добавляйте комментарии.
---```
Happy hacking! 🚀