How to Build Your First AI Agent Using Python (A Practical, AdSense-Friendly Guide)

How to Build Your First AI Agent Using Python
What Is an AI Agent?
- Understand tasks (the user’s request and constraints)
- Plan steps to reach the goal
- Use tools (like web search, calculators, code execution, or APIs)
- Iterate based on results from those tools
- Maintain memory (optional, but helpful for multi-step tasks)
Why Build an AI Agent in Python?
- Beginner-friendly and readable
- Rich in libraries for AI, HTTP requests, and data handling
- Great for rapid iteration when experimenting with prompts and tools
- Well-supported by agent frameworks and LLM integrations
Overview: What We’ll Build
- Accept a user request (for example: “Find today’s weather and give me a plan for a short walk.”)
- Use a small set of tools (we’ll implement a mock weather tool and a calculator tool)
- Follow a structured workflow: plan → use tools → produce final answer
- Optionally store “memory” (like previous requests) to improve continuity
Prerequisites
- Python 3.10+ installed
- pip (usually comes with Python)
- An API key for your chosen LLM provider (OpenAI, Anthropic, etc.)
- A code editor (VS Code recommended)
Choose an Agent Approach: Minimal vs. Framework
- Minimal (roll-your-own): You write the agent loop yourself using Python and LLM calls. Great for learning.
- Framework-based: Use libraries like LangChain, LlamaIndex, or a similar agent framework. Faster to build and easier to scale.
Install Dependencies
pip install requests python-dotenv
pip install openai
OPENAI_API_KEY=your_key_here
Step 1: Create Your Basic Agent Skeleton
import os
from dotenv import load_dotenv
from openai import OpenAIload_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
def ask_llm(messages):
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
temperature=0.2
)
return response.choices[0].message.content
def run_agent(user_goal: str) -> str:
system_prompt = (
"You are an AI agent. "
"You must help the user accomplish their goal. "
"If you need tools, request them explicitly using the format: "
"'TOOL: tool_name | tool_input: ...'."
)
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_goal},
]
answer = ask_llm(messages)
return answer
if __name__ == "__main__":
goal = "Create a short study plan for learning Python in 7 days."
print(run_agent(goal))
Step 2: Add Tools (Your Agent’s Superpowers)
- calculator: safely compute math expressions
- weather: return a fake forecast (we’ll make it easy to replace later with a real API)
import mathdef calculator(expression: str) -> str:
# Very small safety approach: allow digits, operators, parentheses, spaces, and dot.
allowed = "0123456789+-*/(). %"
if any(ch not in allowed for ch in expression):
return "Error: expression contains unsupported characters."
try:
result = eval(expression, {"__builtins__": {}} , {})
return str(result)
except Exception as e:
return f"Error: {e}"
def weather(city: str) -> str:
# Mock data for beginners. Replace later with an actual weather API.
city_lower = city.strip().lower()
if city_lower in ["san francisco", "sf"]:
return "San Francisco: 60°F, cloudy, slight breeze."
if city_lower in ["new york", "nyc"]:
return "New York: 72°F, sunny, light wind."
return f"{city.title()}: 65°F, partly cloudy (mock forecast)."
Step 3: Implement a Tool-Calling Agent Loop
- Ask the LLM what to do next
- If it requests a tool, run the tool
- Send the tool result back to the LLM
- Repeat until the LLM provides the final answer
import os
from dotenv import load_dotenv
from openai import OpenAI
from tools import calculator, weatherload_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
def ask_llm(messages):
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
temperature=0.2
)
return response.choices[0].message.content
def parse_tool_request(text: str):
# Expected format: TOOL: tool_name | tool_input: ...
marker = "TOOL:"
if marker not in text:
return None
line = [l for l in text.splitlines() if l.strip().startswith("TOOL:")]
if not line:
return None
tool_part = line[0].split("TOOL:")[1].strip()
# Split tool_name and tool_input
if "| tool_input:" in tool_part:
tool_name, tool_input = tool_part.split("| tool_input:", 1)
return tool_name.strip(), tool_input.strip()
return None
def run_tool(tool_name: str, tool_input: str) -> str:
tool_name = tool_name.lower()
if tool_name == "calculator":
return calculator(tool_input)
if tool_name == "weather":
return weather(tool_input)
return f"Error: Unknown tool '{tool_name}'"
def run_agent(user_goal: str) -> str:
system_prompt = (
"You are an AI agent. Your goal is to help the user accomplish the request. "
"If you need a tool, respond with a single tool request line exactly like: "
"'TOOL: tool_name | tool_input: ...'. "
"Otherwise, respond normally with your final answer."
)
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_goal},
]
for _ in range(5): # Limit iterations to avoid infinite loops
llm_output = ask_llm(messages)
tool_req = parse_tool_request(llm_output)
if tool_req is None:
return llm_output # Final answer
tool_name, tool_input = tool_req
tool_result = run_tool(tool_name, tool_input)
messages.append({"role": "assistant", "content": llm_output})
messages.append({
"role": "user",
"content": f"Tool result for {tool_name}({tool_input}): {tool_result}"
})
return "Sorry—I'm having trouble completing that request."
if __name__ == "__main__":
goal = "What's the weather in San Francisco, and calculate 12*7."
print(run_agent(goal))
Step 4: Add Lightweight Memory (So It Feels Smarter)
- Store the last user request
- Store user preferences (like favorite city)
- Store tool outputs that are useful later
import json
from pathlib import PathMEM_PATH = Path("memory.json")
def load_memory():
if MEM_PATH.exists():
return json.loads(MEM_PATH.read_text())
return {}
def save_memory(mem: dict):
MEM_PATH.write_text(json.dumps(mem, indent=2))
- If user previously said their city is “San Francisco,” your agent can default to it.
- If user likes short answers, store that preference.
Step 5: Test With Realistic Prompts
- “Check the weather in New York and tell me whether I should bring a jacket.”
- “Calculate the total cost if I have 3 items at $19.99 each. Then suggest a budget-friendly shopping list.”
- “Plan a 3-day workout schedule. Use the calculator to compute how many minutes of cardio total if each day includes 20 minutes.”
Common Pitfalls (And How to Avoid Them)
- Infinite loops: Always cap iterations (we used 5).
- Tool misuse: Make the tool request format strict and validate input.
- Unsafe code execution: For calculators, restrict characters and avoid arbitrary eval. For production, use a safer math parser.
- Vague prompts: Tell the model exactly how to request tools and when to provide the final answer.
- No evaluation: Test with a small suite of tasks and compare outputs.
How to Upgrade This Into a Real-World Agent
- Replace mock weather with a real weather API
- Add more tools: web search, database queries, file operations, reminders
- Use structured outputs (JSON) to reduce parsing errors
- Add retrieval (RAG) so it can answer based on documents
- Improve memory with summaries and user-specific profiles
- Add logging so you can debug tool calls and outcomes
Evaluation: How Do You Know It Works?
- Golden test cases: Make 10–30 prompts with expected behavior.
- Tool coverage checks: Ensure the agent uses tools when needed.
- Quality review: Read outputs and score them (accuracy, clarity, completeness).
- Error analysis: If it fails, record why (wrong tool input? missing tool request? ambiguous prompt?).
Security and Safety Notes (Important for AdSense-Friendly Trust)
- Limit tool permissions (don’t let your agent access sensitive systems by default)
- Validate tool inputs to prevent misuse
- Avoid storing sensitive data in plain text memory
- Use safe execution patterns (no arbitrary code execution)
