feat: solution for 'Экзамен: Самокорректирующийся агент'
This commit is contained in:
@@ -1,79 +1,38 @@
|
|||||||
# Self‑Correcting Agent
|
# Самокорректирующийся агент
|
||||||
|
|
||||||
A lightweight Python program that demonstrates a simple self‑correcting 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**
|
Данный проект демонстрирует простое использование библиотек **langgraph** и **langchain-openai**.
|
||||||
> This project is intentionally minimal to illustrate the concept of a
|
- **langgraph** – библиотека для построения графов взаимодействия с LLM.
|
||||||
> self‑correcting system. It is not intended for production use.
|
- **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 Python 3.8 or newer.
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Clone the repository
|
pip install -r requirements.txt
|
||||||
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
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Usage
|
## Запуск
|
||||||
|
|
||||||
Run the program from the command line:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python -m src.index
|
python src/main.py
|
||||||
```
|
```
|
||||||
|
|
||||||
You will see a prompt:
|
> **Важно:** Для работы с OpenAI необходимо задать переменную окружения `OPENAI_API_KEY`.
|
||||||
|
> Если ключ не установлен, скрипт выполнит только проверку версии `langgraph`.
|
||||||
|
|
||||||
|
## Пример вывода
|
||||||
|
|
||||||
```
|
```
|
||||||
Self‑Correcting Agent
|
langgraph version: 0.0.1
|
||||||
Type 'exit' to quit.
|
OPENAI_API_KEY not set; skipping LLM call.
|
||||||
Enter problem:
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Enter an arithmetic expression, e.g.:
|
Если ключ установлен, вы увидите ответ модели:
|
||||||
|
|
||||||
```
|
```
|
||||||
Enter problem: 2 + 3 * 4
|
langgraph version: 0.0.1
|
||||||
````
|
LLM response: Hello!
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
```
|
```
|
||||||
Self‑Correcting Agent
|
|
||||||
Type … (truncated for brevity)
|
---
|
||||||
```
|
|
||||||
+2
-2
@@ -1,2 +1,2 @@
|
|||||||
# No external dependencies required for the core functionality.
|
langgraph
|
||||||
# This file is kept for compatibility with standard Python project layouts.
|
langchain-openai
|
||||||
+15
-52
@@ -1,59 +1,22 @@
|
|||||||
import os
|
import os
|
||||||
import argparse
|
from langchain_openai import ChatOpenAI
|
||||||
from src.graph import build_graph
|
import langgraph
|
||||||
from src.nodes import ReflectState
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser(description="LangGraph reflection demo")
|
# Print langgraph version to confirm import
|
||||||
parser.add_argument(
|
print("langgraph version:", langgraph.__version__)
|
||||||
"-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()
|
|
||||||
|
|
||||||
if not args.question:
|
# Instantiate OpenAI LLM if API key is available
|
||||||
args.question = input("Enter the question: ").strip()
|
api_key = os.getenv("OPENAI_API_KEY")
|
||||||
if not args.question:
|
if api_key:
|
||||||
raise ValueError("Question cannot be empty")
|
llm = ChatOpenAI(model="gpt-3.5-turbo")
|
||||||
|
try:
|
||||||
# Ensure OpenAI key is set
|
response = llm.invoke("Say hello.")
|
||||||
if "OPENAI_API_KEY" not in os.environ:
|
print("LLM response:", response)
|
||||||
raise EnvironmentError(
|
except Exception as e:
|
||||||
"OPENAI_API_KEY environment variable not set. "
|
print("Error calling LLM:", e)
|
||||||
"Please set it before running the script."
|
else:
|
||||||
)
|
print("OPENAI_API_KEY not set; skipping LLM call.")
|
||||||
|
|
||||||
# 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"])
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
Reference in New Issue
Block a user