feat: solution for '8. Самописный поисковый агент на основе deep agents from scratch'
This commit is contained in:
@@ -1,68 +1,98 @@
|
||||
# Deep Search Agent – LangChain Implementation
|
||||
# Самописный поисковый агент на основе deep agents from scratch
|
||||
|
||||
This repository contains a minimal implementation of a **search agent** built with LangChain, following the “Deep Agents from Scratch” template.
|
||||
The agent can answer arbitrary questions by performing a web search and reasoning over the results.
|
||||
## Описание
|
||||
|
||||
## Features
|
||||
Это простая реализация поискового агента, использующего трансформерный энкодер для векторизации документов и запросов. Поиск осуществляется по косинусному сходству между векторами.
|
||||
|
||||
- Uses **OpenAI GPT‑4o‑mini** as the language model.
|
||||
- Performs web searches via **SerpAPI** (Google/SerpAPI).
|
||||
- Maintains conversation context with a memory buffer.
|
||||
- Implements the **Zero‑Shot React** agent pattern.
|
||||
- Simple command‑line interface for interactive use.
|
||||
## Структура проекта
|
||||
|
||||
## Prerequisites
|
||||
```
|
||||
src/
|
||||
├── index.py # Основной код агента и API
|
||||
data/
|
||||
└── documents.txt # Текстовый файл с документами (один документ на строку)
|
||||
README.md
|
||||
```
|
||||
|
||||
- Python 3.10+
|
||||
- An OpenAI API key.
|
||||
- A SerpAPI key (free tier available).
|
||||
> **Важно**: файл `data/documents.txt` должен существовать и содержать хотя бы несколько строк текста. Если его нет, агент не запустится.
|
||||
|
||||
## Setup
|
||||
## Установка
|
||||
|
||||
```bash
|
||||
# Clone the repository
|
||||
git clone https://git.brojs.ru/kuzakhmetovartur/8.-samopisnyy-poiskovyy-agent-na-osnove-<repo>.git
|
||||
cd <repo>
|
||||
# Создайте виртуальное окружение (рекомендуется)
|
||||
python -m venv venv
|
||||
source venv/bin/activate # Windows: venv\Scripts\activate
|
||||
|
||||
# Create a virtual environment (optional but recommended)
|
||||
python -m venv .venv
|
||||
source .venv/bin/activate # On Windows: .venv\\Scripts\\activate
|
||||
|
||||
# Install dependencies
|
||||
pip install -r requirements.txt
|
||||
# Установите зависимости
|
||||
pip install -U pip
|
||||
pip install torch transformers fastapi uvicorn pydantic numpy
|
||||
```
|
||||
|
||||
Create a `.env` file in the project root with your credentials:
|
||||
> Если у вас есть GPU, убедитесь, что установлена версия `torch` с поддержкой CUDA.
|
||||
|
||||
```
|
||||
OPENAI_API_KEY=sk-...
|
||||
SERPAPI_KEY=your-serpapi-key
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
Run the agent interactively:
|
||||
## Запуск
|
||||
|
||||
```bash
|
||||
python -m src.agent
|
||||
python src/index.py
|
||||
```
|
||||
|
||||
You will be prompted to enter a question. The agent will search the web and return a concise answer.
|
||||
Сервер будет доступен по адресу `http://0.0.0.0:8000`.
|
||||
|
||||
## Example
|
||||
## API
|
||||
|
||||
```
|
||||
Enter your question: What is the capital of France?
|
||||
Processing...
|
||||
### POST `/search`
|
||||
|
||||
=== Answer ===
|
||||
The capital of France is Paris.
|
||||
**Запрос**
|
||||
|
||||
```json
|
||||
{
|
||||
"query": "пример запроса",
|
||||
"top_k": 5
|
||||
}
|
||||
```
|
||||
|
||||
## Testing
|
||||
- `query` – строка запроса.
|
||||
- `top_k` – количество возвращаемых документов (по умолчанию 5).
|
||||
|
||||
The agent can be tested programmatically by importing `create_search_agent` from `src.agent` and calling `agent.run("your question")`.
|
||||
**Ответ**
|
||||
|
||||
## License
|
||||
```json
|
||||
{
|
||||
"results": [
|
||||
{
|
||||
"document": "текст найденного документа",
|
||||
"score": 0.8723
|
||||
},
|
||||
...
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Пример использования
|
||||
|
||||
```bash
|
||||
curl -X POST "http://0.0.0.0:8000/search" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"query":"машинное обучение", "top_k":3}'
|
||||
```
|
||||
|
||||
## Как добавить документы
|
||||
|
||||
1. Откройте файл `data/documents.txt`.
|
||||
2. Добавьте новые строки – каждая строка будет рассматриваться как отдельный документ.
|
||||
3. Перезапустите сервер, чтобы обновления вступили в силу.
|
||||
|
||||
## Тесты
|
||||
|
||||
Тестов в проекте нет, но вы можете быстро проверить работу:
|
||||
|
||||
```python
|
||||
from src.index import SearchAgent
|
||||
|
||||
agent = SearchAgent()
|
||||
print(agent.search("пример", top_k=3))
|
||||
```
|
||||
|
||||
## Лицензия
|
||||
|
||||
MIT License
|
||||
Reference in New Issue
Block a user