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

This commit is contained in:
2026-05-27 14:30:04 +00:00
parent ef7c3df7a0
commit 8cf8ba633e
@@ -1,107 +1,110 @@
# Streamрежим AI‑агента # StreamMode AI Agent
## Описание проекта 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, который взаимодействует с LLM `llama3` через Ollama и использует эмбеддинги от Nomic. ---
Главная особенность – **потоковый вывод** (`stream`) вместо обычного `.invoke()`. Это позволяет видеть ответ токен за токеном в реальном времени, что особенно полезно при работе с длинными запросами или многократным вызовом инструментов.
## Предварительные требования ## Table of Contents
| Компонент | Версия / Минимальные требования | Как установить | - [What It Does](#what-it-does)
|-----------|---------------------------------|----------------| - [Prerequisites](#prerequisites)
| **Python** | 3.10+ (рекомендуется 3.11) | `python -m venv .venv && source .venv/bin/activate` | - [Installation](#installation)
| **Ollama** | Любая версия, поддерживающая `llama3` | [Официальная инструкция](https://ollama.com/download) | - [Running the Agent](#running-the-agent)
| **LLM‑модель** (`llama3`) | Доступна в Ollama | `ollama pull llama3` | - [Example Usage](#example-usage)
| **Qdrant** (необязательно, если используете внешнее хранилище) | Любая версия | `docker run -p 6333:6333 qdrant/qdrant` |
> ⚠️ Если вы не планируете хранить состояние в Qdrant, можно использовать встроенный `MemorySaver`. ---
## Установка ## 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
```bash ```bash
# Клонируйте репозиторий (или скачайте файлы) # Clone the repo (or copy agent.py into your project)
git clone https://github.com/your-username/stream-ai-agent.git git clone https://github.com/yourusername/stream-ai-agent.git
cd stream-ai-agent cd stream-ai-agent
# Создайте и активируйте виртуальное окружение # 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` содержит: `requirements.txt` contains:
```text ```text
langgraph==0.1.* langchain>=0.2.0
langchain==0.2.* langchain-ollama>=0.1.0
langchain-ollama==0.0.* langgraph>=0.1.0
nomic-embed-text==0.3.* nomic-embed-text>=0.1.0
python-dotenv==1.0.* python-dotenv>=1.0.0
``` ```
## Запуск ---
### 1. Инициализация агента (файл `agent.py`) ## Running the Agent
The main entry point is `agent.py`.
Run it with:
```bash ```bash
# Убедитесь, что переменная окружения OLLAMA_MODEL установлена (по умолчанию "llama3") # Basic usage prompts the agent to answer a question
export OLLAMA_MODEL=llama3 # Linux/macOS python agent.py "What is the capital of France?"
set OLLAMA_MODEL=llama3 # Windows
python agent.py
``` ```
> Внутри `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.
> ```python
> for chunk in graph.stream(state):
> print(chunk, end="", flush=True)
> ```
### 2. Тестирование с примером запроса ---
## Example Usage
```bash ```bash
# Запускаем скрипт и вводим запрос вручную $ python agent.py "Explain quantum computing in simple terms."
python agent.py 🤖 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.
``` ```
Пример ввода: The `🤖` emoji indicates the streaming output from the LLM.
You can also pass multiple arguments or use environment variables to change the model:
``` ```bash
User: Расскажи мне о последних достижениях в области квантовых вычислений. OLLAMA_MODEL=llama2 python agent.py "How many moons does Mars have?"
``` ```
Вывод будет появляться токен за токеном, пока модель генерирует ответ. ---
## Пример использования ### Customizing the Agent
```python * **Change the LLM** edit `LLM_MODEL` in `agent.py`.
from langgraph.graph import StateGraph, START * **Add tools** extend the `tools` list with any `BaseTool` subclass.
from langchain_ollama import ChatOllama * **Persist embeddings** configure Qdrant by setting `QDRANT_URL` and `QDRANT_API_KEY`.
from nomic_embed_text import NomicEmbedText
from langgraph.prebuilt.tool_executor import ToolExecutorNode
from langgraph.checkpoint.memory import MemorySaver
# Инициализация LLM и эмбеддингов ---
llm = ChatOllama(model=os.getenv("OLLAMA_MODEL", "llama3"))
embedder = NomicEmbedText()
# Создание графа с потоковым выводом Happy streaming! 🚀
graph = StateGraph()
graph.add_node("agent_executor", ToolExecutorNode(llm=llm, tools=[]))
graph.set_entry_point(START)
graph.set_finish_point("agent_executor")
state = {"messages": [HumanMessage(content="Привет!")]}
# Потоковый вывод
for chunk in graph.stream(state):
print(chunk, end="", flush=True)
```
> В реальном проекте вы можете подключить собственные инструменты (API‑вызыватели, базы знаний и т.д.) через `ToolExecutorNode`.
## Лицензия
MIT © 2026.