Stream-режим AI-агента: README.md

This commit is contained in:
2026-05-27 14:33:54 +00:00
parent 49426e7e2a
commit 3a23cdcab4
@@ -1,110 +1,106 @@
# StreamMode AI Agent
# Streamрежим AI‑агента
A lightweight Python project that demonstrates how to run a LangChain agent in **streaming mode** using the `langchain-ollama` and `langgraph` libraries.
The agent is defined in `agent.py`. Instead of waiting for the entire response, it streams tokens back to the console as they are generated.
## Описание проекта
Этот проект реализует **AI‑агент**, построенный на основе LangGraph и LangChain, который использует модели из Ollama (по умолчанию `llama3`) и векторную базу Qdrant для хранения эмбеддингов.
Главная особенность – **потоковый вывод** (`stream()`), благодаря которому ответы генерируются токен за токеном и сразу отображаются в консоли, а не после завершения работы.
---
## Предварительные требования
## Table of Contents
| Пакет | Версия | Зачем нужен |
|-------|--------|-------------|
| `ollama` | любой актуальный | Запускает локальную модель LLM (llama3) |
| `qdrant` | 1.x+ | Хранит векторные эмбеддинги для быстрых запросов |
| `python>=3.10` | – | Язык выполнения |
- [What It Does](#what-it-does)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Running the Agent](#running-the-agent)
- [Example Usage](#example-usage)
---
## What It Does
* Implements a simple LangChain agent that can call external tools (e.g., web search, calculator).
* Uses `ChatOllama` as the LLM backend.
* Streams the generated answer tokenbytoken to the console with `agent.stream()`.
* Works out of the box on any machine that has Ollama installed locally.
---
## Prerequisites
| Component | Minimum Version | Notes |
|-----------|-----------------|-------|
| **Python** | 3.10+ | Tested on 3.11 |
| **Ollama** | Latest stable | Must have a model (default: `llama3`) downloaded. |
| **Nomic Embed Text** | Latest | For embeddings used by the agent. |
| **Qdrant** | Optional | If you want to persist embeddings locally. |
> **Installing Ollama**
> ```bash
> curl -fsSL https://ollama.com/install.sh | sh
> ollama pull llama3 # or any other model you prefer
> ```
---
## Installation
> **Важно**: Установите и запустите Ollama и Qdrant перед запуском агента.
```bash
# Clone the repo (or copy agent.py into your project)
git clone https://github.com/yourusername/stream-ai-agent.git
# Пример установки Ollama (Linux)
curl -fsSL https://ollama.ai/install.sh | sh
# Запуск модели llama3
ollama run llama3
# Установка Qdrant (Docker)
docker pull qdrant/qdrant
docker run -p 6333:6333 qdrant/qdrant
```
## Установка проекта
```bash
git clone https://github.com/yourname/stream-ai-agent.git
cd stream-ai-agent
# Create a virtual environment (optional but recommended)
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
```
`requirements.txt` contains:
`requirements.txt` содержит:
```text
langchain>=0.2.0
langchain-ollama>=0.1.0
langgraph>=0.1.0
nomic-embed-text>=0.1.0
python-dotenv>=1.0.0
```
langchain==0.2.*
langgraph==0.1.*
langchain-ollama==0.1.*
langchain-qdrant==0.1.*
nomic-embed-text==0.3.*
python-dotenv
```
---
## Running the Agent
The main entry point is `agent.py`.
Run it with:
## Запуск
```bash
# Basic usage prompts the agent to answer a question
python agent.py "What is the capital of France?"
# 1. Убедитесь, что Ollama и Qdrant запущены.
# 2. Запустите агента:
python agent.py
```
If you want to see the streaming output in real time, simply execute the script as shown above. The console will display each token as soon as it is produced by the LLM.
---
## Example Usage
### Пример команды с аргументами (если добавлены CLI‑параметры)
```bash
$ python agent.py "Explain quantum computing in simple terms."
🤖 Quantum computing is a type of computation that uses quantum bits (qubits) instead of classical bits...
🤖 ...to perform certain calculations much faster than traditional computers.
python agent.py --prompt "Расскажи о последних новостях в области AI"
```
The `🤖` emoji indicates the streaming output from the LLM.
You can also pass multiple arguments or use environment variables to change the model:
## Пример использования
После запуска вы увидите интерактивный ввод:
```bash
OLLAMA_MODEL=llama2 python agent.py "How many moons does Mars have?"
```
> Какую роль играет Qdrant в работе агента?
```
Ответ будет выводиться токен за токеном:
```
Qdrant используется как быстрый
векторный хранилище для эмбеддингов,
что позволяет быстро находить релевантные
тексты и ускорять генерацию ответов.
```
### Пример кода, который можно вставить в `agent.py` (потоковый вывод)
```python
from langchain_ollama import ChatOllama
# Инициализация LLM
llm = ChatOllama(model="llama3")
# Потоковый вызов
for chunk in llm.stream(prompt):
print(chunk.content, end="", flush=True)
print() # Перевод строки после завершения
```
> **Совет**: При работе с LangGraph используйте `AgentExecutor` в режиме `stream=True`, чтобы получать токен за токеном из всех инструментов.
## Вклад
1. Форкните репозиторий.
2. Создайте ветку (`git checkout -b feature/stream-mode`).
3. Сделайте коммит и отправьте PR.
Убедитесь, что тесты проходят: `pytest`.
---
### Customizing the Agent
* **Change the LLM** edit `LLM_MODEL` in `agent.py`.
* **Add tools** extend the `tools` list with any `BaseTool` subclass.
* **Persist embeddings** configure Qdrant by setting `QDRANT_URL` and `QDRANT_API_KEY`.
---
Happy streaming! 🚀
**Автор:** Ваше имя
**Дата создания:** 20260527