Files
task-6a1864fa8a94f887e50d46f0/README.md
T
2026-06-03 12:44:40 +00:00

61 lines
2.0 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# SelfCorrecting LangGraph Agent
## Overview
This project implements a **selfcorrecting agent** using LangGraph. The agent
performs a task, asks an LLM to judge the result, and retries automatically until
the result is judged **success** or the maximum number of attempts is reached.
The key components are:
| Component | Purpose |
|-----------|---------|
| `AgentState` | Typed state that tracks the task, result, attempts, status, error and max_attempts |
| `unreliable_tool` | Simulates a tool that fails 30% of the time (used to demonstrate retry logic) |
| `verify_result` | LLM judge that must reply with the single word `success` or `failed` |
| `handle_error` | Resets the error and sets the status back to `pending` for a retry |
| `execute_task` | Runs the unreliable tool and updates the state |
| `create_agent` | Builds the LangGraph with the above nodes and a retry loop |
| `create_agent_executor` | Compiles the graph into a runnable executor |
| CLI | Run the agent from the command line: `python agent.py "2+2" --max 5` |
## How It Works
1. **Start** The graph begins at `execute_task`.
2. **Execute** The tool runs. If it throws an exception, the state status becomes `failed`.
3. **Check attempts** If the number of attempts is >= `max_attempts`, the graph ends with status `max_attempts`.
4. **Verify** The LLM judges the result. If the verdict is `success`, the graph ends. If `failed`, it goes to `handle_error`.
5. **Retry** `handle_error` clears the error and sets status to `pending`, then the graph loops back to `execute_task`.
## Usage
```bash
# Install dependencies
pip install -r requirements.txt
# Run the agent
python agent.py "2+2" --max 5
```
The console will show the final state, e.g.:
```
--- Final State ---
result: 4
attempts: 2
status: success
error: None
max_attempts: 5
```
## Requirements
```text
langchain>=1.0.0
langgraph>=1.0.0
langchain-openai>=1.0.0
```
## Note
The agent uses the OpenAI API. Make sure the environment variable `OPENAI_API_KEY` is set.