This project implements a self-correcting AI agent using Python, LangChain, and the Groq API.
The agent takes a given task, asks the language model to generate executable Python code, runs the generated code using a Python execution tool, and uses the execution result as feedback. If an error occurs, the agent sends the error back to the language model and allows it to generate corrected code.
The objective of this assignment is to demonstrate how an AI agent can:
- Understand a user-defined goal
- Generate Python code using an LLM
- Execute the generated code
- Observe the execution result
- Detect errors
- Correct the generated code
- Retry the task
- Provide a final response after successful execution
For this assignment, the agent was given the following goal:
Create a Python program that computes the square root of 144.
The expected result is:
12
- Python
- LangChain
- Groq API
- Large Language Model (LLM)
- Kaggle Notebook
- Python
exec()for code execution
The agent follows this process:
User Goal
↓
LLM Generates Python Code
↓
Python Tool Executes Code
↓
Execution Result / Error
↓
LLM Observes the Result
↓
If Error → Correct Code → Retry
↓
Successful Execution
↓
Final Response
The agent is allowed a maximum of three attempts to successfully complete the task.
For the given task, the agent may generate code similar to:
import math
print(math.sqrt(144))The execution produces:
12.0
The agent then provides the final result based on the successful execution.
The Groq API key is not stored directly in this repository.
The notebook uses Kaggle Secrets to securely access the API key:
from kaggle_secrets import UserSecretsClient
client = UserSecretsClient()
groq_api_key = client.get_secret("GROQ_API_KEY")This prevents the API key from being exposed in the source code.
AI-Agent-Assignment-5/
│
├── Assignment_5_Self_Correcting_AI_Agent.ipynb
└── README.md
This assignment demonstrates the basic structure of a self-correcting AI agent. Instead of simply producing an answer, the agent generates code, uses a tool to execute it, observes the result, and can correct errors before trying again.
For the assigned task, the agent successfully calculates:
√144 = 12