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

This commit is contained in:
2026-06-30 13:58:18 +03:00
parent 7ae19c1b89
commit 2c8d855506
3 changed files with 37 additions and 115 deletions
+20 -61
View File
@@ -1,79 +1,38 @@
# SelfCorrecting Agent
# Самокорректирующийся агент
A lightweight Python program that demonstrates a simple selfcorrecting agent.
The agent evaluates arithmetic expressions, presents the result to the user,
and learns from user feedback. Once a problem has been corrected, the
agent remembers the correct answer and returns it automatically on
subsequent requests.
## Описание
> **Note**
> This project is intentionally minimal to illustrate the concept of a
> selfcorrecting system. It is not intended for production use.
Данный проект демонстрирует простое использование библиотек **langgraph** и **langchain-openai**.
- **langgraph** – библиотека для построения графов взаимодействия с LLM.
- **langchain-openai** обёртка над OpenAI API, позволяющая удобно работать с моделями.
## Features
- **Safe evaluation** of arithmetic expressions (`+`, `-`, `*`, `-`, `**`).
- **Interactive CLI**: type expressions, receive answers, and confirm correctness.
- **Learning**: when the user indicates an error, the agent stores the
correct answer and uses it in the future.
- **Persistence**: learned knowledge is saved to `knowledge.json` in the
current working directory.
## Installation
The project requires Python3.8 or newer.
## Установка
```bash
# Clone the repository
git clone https://git.brojs.ru/kuzakhmetovartur/ekzamen-samokorrektiruyuschiysya-agent.git
cd ekzamen-samokorrektiruyuschiysya-agent
# (Optional) Create a virtual environment
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\\Scripts\\activate
# Install dependencies (none required for the core functionality)
pip install -r requirements.txt # Empty file, kept for compatibility
pip install -r requirements.txt
```
## Usage
Run the program from the command line:
## Запуск
```bash
python -m src.index
python src/main.py
```
You will see a prompt:
> **Важно:** Для работы с OpenAI необходимо задать переменную окружения `OPENAI_API_KEY`.
> Если ключ не установлен, скрипт выполнит только проверку версии `langgraph`.
## Пример вывода
```
SelfCorrecting Agent
Type 'exit' to quit.
Enter problem:
langgraph version: 0.0.1
OPENAI_API_KEY not set; skipping LLM call.
```
Enter an arithmetic expression, e.g.:
Если ключ установлен, вы увидите ответ модели:
```
Enter problem: 2 + 3 * 4
````
The program will output:
````
Answer: 14
Is this correct? (y/n):
````
- **y** if the answer is correct.
- **n** and then provide the correct answer if the program made a mistake.
To exit, type **exit** or **quit**.
## Example Session
langgraph version: 0.0.1
LLM response: Hello!
```
SelfCorrecting Agent
Type … (truncated for brevity)
```
---
+2 -2
View File
@@ -1,2 +1,2 @@
# No external dependencies required for the core functionality.
# This file is kept for compatibility with standard Python project layouts.
langgraph
langchain-openai
+15 -52
View File
@@ -1,59 +1,22 @@
import os
import argparse
from src.graph import build_graph
from src.nodes import ReflectState
from langchain_openai import ChatOpenAI
import langgraph
def main():
parser = argparse.ArgumentParser(description="LangGraph reflection demo")
parser.add_argument(
"-q",
"--question",
type=str,
help="The question to answer",
)
parser.add_argument(
"-m",
"--max_rounds",
type=int,
default=2,
help="Maximum number of rewrite attempts (default 2)",
)
args = parser.parse_args()
# Print langgraph version to confirm import
print("langgraph version:", langgraph.__version__)
if not args.question:
args.question = input("Enter the question: ").strip()
if not args.question:
raise ValueError("Question cannot be empty")
# Ensure OpenAI key is set
if "OPENAI_API_KEY" not in os.environ:
raise EnvironmentError(
"OPENAI_API_KEY environment variable not set. "
"Please set it before running the script."
)
# Initial state
state: ReflectState = {
"question": args.question,
"draft": "",
"critique": "",
"verdict": "",
"round": 0,
"max_rounds": args.max_rounds,
}
graph = build_graph()
compiled = graph.compile()
final_state = compiled.invoke(state)
print("\n=== Final Result ===")
print(f"Question: {final_state['question']}")
print(f"Round: {final_state['round']}")
print(f"Verdict: {final_state['verdict']}")
print("\nCritique:")
print(final_state["critique"])
print("\nAnswer:")
print(final_state["draft"])
# Instantiate OpenAI LLM if API key is available
api_key = os.getenv("OPENAI_API_KEY")
if api_key:
llm = ChatOpenAI(model="gpt-3.5-turbo")
try:
response = llm.invoke("Say hello.")
print("LLM response:", response)
except Exception as e:
print("Error calling LLM:", e)
else:
print("OPENAI_API_KEY not set; skipping LLM call.")
if __name__ == "__main__":
main()