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

This commit is contained in:
2026-05-27 10:49:58 +00:00
parent 9901f6c958
commit 03ec9595ce
@@ -1,78 +1,169 @@
# HumanintheLoop (HIL) через middleware на FastMCP # HumanintheLoop Middleware
## Описание проекта HumanintheLoop (HITL) middleware is a lightweight Python framework that lets you build conversational agents on top of **Qdrant** vector store and **Ollama** LLMs.
Проект демонстрирует принцип **HumanintheLoop** (человек в потоке выполнения) при помощи простого HTTP‑сервера, реализованного на **FastMCP**. The project demonstrates how to:
Сервер имеет один эндпоинт `/process`. Перед выполнением запроса к этому эндпоинту пользователь должен подтвердить действие через консольный ввод (`yes`/`no`). Это позволяет показать, как можно вставлять ручное вмешательство в автоматический процесс без изменения бизнес‑логики.
## Предварительные требования * Store and retrieve documents with Qdrant.
- Python 3.10+ * Embed text using the `nomic-embed-text` model from Ollama.
- `pip` (или `pipx`) для установки зависимостей * Generate responses with the `llama3` chat model via LangChain.
* Wrap everything in a simple HTTP client that can be used by external services or UI frontends.
> **Важно**: В данном примере не требуется внешних сервисов, таких как Ollama или Qdrant. Всё работает локально. The core logic lives in two files:
| File | Purpose |
|------|---------|
| **agent.py** | Implements the LangChain pipeline: embedding → vector search → LLM generation. |
| **client.py** | Exposes a minimal FastAPI server that accepts user queries and returns responses from `agent.py`. |
---
## 📦 Prerequisites
| Component | Minimum Version | Notes |
|-----------|-----------------|-------|
| Python | 3.10+ | Tested on 3.12 |
| pip | | Use the system package manager or `pipx` |
| **Ollama** | Latest | Install from https://ollama.ai/ |
| **Qdrant** | 1.7+ | Run locally (`docker run -p 6333:6333 qdrant/qdrant`) or use a managed instance |
> **Important:**
> * The Ollama image must expose the `llama3` and `nomic-embed-text` models.
> ```bash
> ollama pull llama3
> ollama pull nomic-embed-text
> ```
> * Qdrant should be reachable at `http://localhost:6333` (or set via the `QDRANT_URL` env var).
---
## ⚙️ Installation
## Установка
```bash ```bash
# Клонируйте репозиторий # Clone the repo
git clone https://github.com/your-username/hil-fastmcp.git git clone https://github.com/your-org/hitl-middleware.git
cd hil-fastmcp cd hitl-middleware
# Создайте виртуальное окружение (необязательно, но рекомендуется) # Create a virtual environment (optional but recommended)
python -m venv .venv python -m venv .venv
source .venv/bin/activate # Windows: .\.venv\Scripts\activate source .venv/bin/activate # Windows: .venv\Scripts\activate
# Установите зависимости # Install dependencies
pip install -r requirements.txt pip install -r requirements.txt
``` ```
## Запуск сервера `requirements.txt` contains:
```text
langchain==0.2.*
langchain-ollama==0.1.*
langchain-qdrant==0.1.*
fastapi==0.* # for client.py
uvicorn==0.* # ASGI server
python-dotenv==1.*
```
---
## 🚀 Running the Project
### 1️⃣ Start Qdrant (if not already running)
```bash ```bash
# Запускаем сервер из файла solution.py docker run -d --name qdrant \
python solution.py -p 6333:6333 \
``` qdrant/qdrant
После запуска вы увидите сообщение:
```
FastMCP server is running on http://127.0.0.1:8000
``` ```
## Пример использования > Make sure the container is healthy before proceeding.
### 2️⃣ Run the Agent
The agent can be executed as a script or imported into other code.
It will automatically load embeddings, connect to Qdrant, and expose a `process_query` function.
### 1. Отправка запроса к `/process`
```bash ```bash
curl -X POST http://127.0.0.1:8000/process \ python agent.py
-H "Content-Type: application/json" \
-d '{"task":"example"}'
``` ```
После отправки запроса сервер выведет в консоль: > The script prints a simple “Agent ready” message and waits for input if run directly.
```
Do you want to proceed with the request? (yes/no): ### 3️⃣ Run the Client (FastAPI)
The client exposes an HTTP endpoint `/query`.
It forwards incoming requests to the agent and returns the LLM response.
```bash
uvicorn client:app --host 0.0.0.0 --port 8000
``` ```
### 2. Подтверждение действия You should see:
- Введите `yes` и нажмите **Enter** → запрос выполнится, и клиент получит ответ:
```
INFO: Started server process [12345]
...
INFO: Application startup complete.
```
Now you can send requests to `http://localhost:8000/query`.
---
## 📄 Example Usage
### Using the HTTP API
```bash
curl -X POST http://localhost:8000/query \
-H "Content-Type: application/json" \
-d '{"question": "What is the capital of France?"}'
```
**Response**
```json ```json
{"message":"Task processed successfully","task":"example"} {
``` "answer": "The capital of France is Paris."
- Введите `no` → сервер вернёт ошибку 403: }
```json
{"detail":"Action was not confirmed by the user."}
``` ```
## Структура проекта ### Using the Agent Directly (Python)
```
├── solution.py # Основной код сервера с HIL‑middleware ```python
└── requirements.txt # Список зависимостей (FastMCP) from agent import process_query
response = process_query("Explain quantum computing in simple terms.")
print(response)
# Output: "Quantum computing uses qubits..."
``` ```
## Как это работает ---
1. **Middleware** intercepts every request to `/process`.
2. Он выводит запрос в консоль и ждёт ввода пользователя.
3. Если пользователь вводит `yes`, middleware пропускает запрос дальше к обработчику.
4. В противном случае возвращается HTTP‑ошибка 403.
Таким образом, человек имеет контроль над каждым выполнением запроса без необходимости менять логику самого эндпоинта. ## 🔧 Configuration
## Лицензия All configuration values can be overridden via environment variables or a `.env` file placed at the project root.
MIT © 2026
--- | Variable | Default | Description |
|----------|---------|-------------|
| `QDRANT_URL` | `http://localhost:6333` | Qdrant endpoint |
| `OLLAMA_HOST` | `http://localhost:11434` | Ollama API host |
| `LLM_MODEL` | `llama3` | Chat model name |
| `EMBEDDING_MODEL` | `nomic-embed-text` | Embedding model name |
Example `.env`:
```dotenv
QDRANT_URL=http://qdrant:6333
OLLAMA_HOST=http://ollama:11434
LLM_MODEL=llama3
EMBEDDING_MODEL=nomic-embed-text
```
---
## 📚 Further Reading
* [LangChain Docs](https://langchain.com/)
* [Ollama Quickstart](https://github.com/ollama/ollama)
* [Qdrant Documentation](https://qdrant.tech/documentation/)
Feel free to extend the middleware with custom prompts, retrieval strategies, or additional LLMs. Happy hacking!