feat: solution for '8. Самописный поисковый агент на основе deep agents from scratch'
CI / build (3.1) (push) Has been cancelled
CI / build (3.11) (push) Has been cancelled
CI / build (3.8) (push) Has been cancelled
CI / build (3.9) (push) Has been cancelled

This commit is contained in:
2026-06-30 16:35:09 +03:00
parent 54499668c4
commit b186e2f395
2 changed files with 170 additions and 122 deletions
+73 -43
View File
@@ -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 GPT4omini** as the language model.
- Performs web searches via **SerpAPI** (Google/SerpAPI).
- Maintains conversation context with a memory buffer.
- Implements the **ZeroShot React** agent pattern.
- Simple commandline 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