create a ai agent in python that understands the question and generates tasks and execustes them
https://chatgpt.com/share/6996bc34-3a9c-8006-b68d-585cf7b60d17
To build an AI agent in Python that understands a question, generates tasks, and executes them, you need three main components:
- Reasoning / Planning → break question into tasks
- Tools / Functions → things the agent can execute
- Execution Loop → plan → execute → observe → respond
Below is a clean, production-style example using modern OpenAI Agents SDK concepts but implemented in plain Python so you fully control it.
Architecture Overview
User Question
↓
LLM → Task Planner
↓
Task List
↓
Executor → Tools (search, code, files, APIs)
↓
Results
↓
Final Answer
Step 1: Install dependencies
pip install openai python-dotenv
Step 2: Create .env
OPENAI_API_KEY=your_api_key_here
Step 3: Full AI Agent Implementation
import os
import json
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
client = OpenAI()
# -----------------------------
# TOOLS (functions agent can use)
# -----------------------------
def calculator(expression):
try:
return str(eval(expression))
except Exception as e:
return f"Error: {e}"
def read_file(filename):
try:
with open(filename, "r") as f:
return f.read()
except Exception as e:
return str(e)
def write_file(filename, content):
try:
with open(filename, "w") as f:
f.write(content)
return "File written successfully"
except Exception as e:
return str(e)
TOOLS = {
"calculator": calculator,
"read_file": read_file,
"write_file": write_file,
}
# -----------------------------
# STEP 1: PLAN TASKS
# -----------------------------
def plan_tasks(user_question):
prompt = f"""
You are an AI task planner.
Break the user question into steps.
Question:
{user_question}
Return JSON list like:
[
{{
"task": "description",
"tool": "calculator/read_file/write_file/none",
"input": "input"
}}
]
"""
response = client.chat.completions.create(
model="gpt-5-mini",
messages=[{"role": "user", "content": prompt}],
temperature=0
)
text = response.choices[0].message.content
try:
tasks = json.loads(text)
except:
print("Planner output:", text)
raise Exception("Planner failed")
return tasks
# -----------------------------
# STEP 2: EXECUTE TASKS
# -----------------------------
def execute_tasks(tasks):
results = []
for task in tasks:
tool = task["tool"]
input_data = task["input"]
print(f"Executing: {task['task']}")
if tool == "none":
result = input_data
elif tool in TOOLS:
result = TOOLS[tool](input_data)
else:
result = f"Unknown tool: {tool}"
results.append({
"task": task["task"],
"result": result
})
return results
# -----------------------------
# STEP 3: GENERATE FINAL ANSWER
# -----------------------------
def generate_answer(question, execution_results):
prompt = f"""
User Question:
{question}
Task Results:
{execution_results}
Generate final helpful answer.
"""
response = client.chat.completions.create(
model="gpt-5-mini",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
# -----------------------------
# MAIN AGENT LOOP
# -----------------------------
def run_agent(question):
print("\nPlanning tasks...")
tasks = plan_tasks(question)
print("\nTasks:", tasks)
print("\nExecuting tasks...")
results = execute_tasks(tasks)
print("\nResults:", results)
print("\nGenerating final answer...")
answer = generate_answer(question, results)
return answer
# -----------------------------
# TEST
# -----------------------------
if __name__ == "__main__":
question = "Calculate 25*4 and save result in file result.txt"
answer = run_agent(question)
print("\nFINAL ANSWER:\n", answer)
Example Output
Planning tasks...
Tasks:
[
{task: calculate 25*4, tool: calculator, input: "25*4"},
{task: write result to file, tool: write_file, input: "result.txt,100"}
]
Executing tasks...
Executing: calculate 25*4
Executing: write result to file
FINAL ANSWER:
The result 100 has been calculated and saved in result.txt
This agent can already:
• Understand natural language
• Break into tasks
• Select tools
• Execute tools
• Generate final answer
Advanced Capabilities You Can Add
Add tools like:
Web search tool
def web_search(query):
# call search API
Run shell commands
import subprocess
def run_command(cmd):
return subprocess.getoutput(cmd)
Database tool
def query_db(sql):
Production-Level Architecture
agent/
├── planner.py
├── executor.py
├── tools/
│ ├── file.py
│ ├── web.py
│ ├── db.py
└── main.py
Even Better: Autonomous Agent Loop
while not goal_complete:
think()
plan()
execute()
observe()
This is how AutoGPT works.
If you want, I can build a full autonomous agent that can:
• browse internet
• write code
• execute code
• fix errors
• use tools automatically
• like Devin / AutoGPT
Just tell me.