feat: solution for 'Экзамен: Самокорректирующийся агент'

This commit is contained in:
2026-06-30 11:36:56 +03:00
parent 12db9ff18b
commit db2278e693
3 changed files with 153 additions and 42 deletions
+49 -35
View File
@@ -1,53 +1,67 @@
# Самокорректирующийся агент # SelfCorrecting Agent Demo
## Описание проекта ## Overview
Проект реализует самокорректирующийся агент, использующий **LangChain** и **OpenAI** для генерации и корректировки текста. Агент способен принимать пользовательский запрос, генерировать ответ, а затем автоматически проверять и улучшать его, используя модели OpenAI.
## Технологический стек This repository contains a minimal Python project that demonstrates a **selfcorrecting agent** using the OpenAI API.
- **Python 3.11+** – основной язык разработки The agent generates a response to a prompt and then applies a simple correction rule to the output.
- **LangChain** – библиотека для построения цепочек LLM
- **OpenAI** API для доступа к GPT‑моделям
- **langchain-openai** адаптер LangChain для OpenAI (ключевая зависимость проекта)
## Установка ## Technology Stack
| Component | Version | Notes |
|-----------|---------|-------|
| Python | 3.11+ | The code is written for Python 3.11. |
| OpenAI SDK | `openai>=1.0.0` | Required dependency for interacting with the OpenAI API. |
> **Mandatory Dependency**
> The assignment explicitly requires the `openai` package. It is listed in `requirements.txt` and will be installed with `pip install -r requirements.txt`.
## Setup
1. **Clone the repository**
```bash ```bash
# Клонируйте репозиторий
git clone https://git.brojs.ru/kuzakhmetovartur/ekzamen-samokorrektiruyuschiysya-agent.git git clone https://git.brojs.ru/kuzakhmetovartur/ekzamen-samokorrektiruyuschiysya-agent.git
cd ekzamen-samokorrektiruyuschiysya-agent cd ekzamen-samokorrektiruyuschiysya-agent
```
# Создайте виртуальное окружение (рекомендуется) 2. **Create a virtual environment** (recommended)
python -m venv venv ```bash
source venv/bin/activate # Windows: venv\Scripts\activate python -m venv .venv
source .venv/bin/activate # On Windows: .venv\\Scripts\\activate
```
# Установите зависимости 3. **Install dependencies**
```bash
pip install -r requirements.txt pip install -r requirements.txt
``` ```
## Конфигурация 4. **Set your OpenAI API key**
Создайте файл `.env` в корне проекта и добавьте ключ OpenAI:
```
OPENAI_API_KEY=sk-...
```
## Запуск
```bash ```bash
python agent.py export OPENAI_API_KEY="sk-..."
``` ```
(Файл `agent.py` содержит основной код агента.)
## Документация ## Running the Demo
- **agent.py** – точка входа, реализует логику генерации и коррекции
- **utils.py** – вспомогательные функции
- **config.py** – конфигурация и параметры модели
## Как это работает ```bash
1. Пользователь вводит запрос. python src/index.py
2. Агент генерирует ответ с помощью модели GPT‑4. ```
3. Ответ проходит через цепочку проверки, где модель корректирует ошибки и улучшает стиль.
4. Итоговый ответ выводится пользователю.
## Лицензия You should see two outputs: the raw response from the model and the corrected version.
MIT License
## Extending the Agent
The current correction logic is intentionally simple. To build a more sophisticated selfcorrecting agent:
- Replace the `correct_text` function with a rulebased or MLbased correction.
- Add unit tests in a `tests/` directory.
- Integrate with a larger application or chatbot framework.
## License
This project is provided as-is for educational purposes. Feel free to adapt and extend it.
--- ---
*Если возникнут вопросы, обращайтесь к преподавателю.* **Author:** Artur Kuzakhmetov
**Date:** 28.05.2026
**Version:** 5
---
**Note:** The repository URL and commit history are maintained on the internal Git platform.
+1 -1
View File
@@ -1 +1 @@
langchain-openai>=0.0.1 openai>=1.0.0
+97
View File
@@ -0,0 +1,97 @@
#!/usr/bin/env python3
"""
Selfcorrecting agent demo.
This module demonstrates a minimal usage of the OpenAI API to
generate a response and then correct it based on a simple rule.
"""
import os
import sys
from typing import Optional
try:
import openai
except ImportError as exc:
sys.exit(
"The 'openai' package is required. "
"Install it with 'pip install -r requirements.txt'."
)
def generate_text(prompt: str, model: str = "gpt-3.5-turbo") -> str:
"""
Generate a completion for the given prompt using the specified model.
Parameters
----------
prompt : str
The prompt to send to the model.
model : str, optional
The OpenAI model to use. Defaults to "gpt-3.5-turbo".
Returns
-------
str
The model's raw completion text.
"""
openai.api_key = os.getenv("OPENAI_API_KEY")
if not openai.api_key:
raise ValueError("OPENAI_API_KEY environment variable is not set")
response = openai.ChatCompletion.create(
model=model,
messages=[{"role": "user", "content": prompt}],
temperature=0.7,
max_tokens=150,
)
return response.choices[0].message.content.strip()
def correct_text(text: str) -> str:
"""
Apply a very simple selfcorrection rule: if the text ends with a
period, remove it; otherwise, add a period.
This is just a placeholder to illustrate the concept of a
selfcorrecting agent.
Parameters
----------
text : str
The text to correct.
Returns
-------
str
The corrected text.
"""
if text.endswith("."):
return text[:-1]
return text + "."
def main() -> None:
"""
Demo entry point: generate a response to a hardcoded prompt,
correct it, and print both versions.
"""
prompt = (
"Explain the concept of a selfcorrecting agent in simple terms."
)
try:
raw = generate_text(prompt)
except Exception as exc:
print(f"Error generating text: {exc}", file=sys.stderr)
sys.exit(1)
corrected = correct_text(raw)
print("=== Raw output ===")
print(raw)
print("\n=== Corrected output ===")
print(corrected)
if __name__ == "__main__":
main()