In this Python automation tutorial, imagine you hire an assistant and hand them a single index card with one instruction: If it rains, cancel the meeting. That assistant is useful — but only in one narrow situation. Now imagine hiring someone you can walk up to and say, “Figure out if I should reschedule my outdoor event this weekend, and if so, send the team a message with three alternative dates.” They think, look things up, make decisions, and act. That second assistant is an AI agent. The first one is a traditional script.
This distinction is the entire game. Most of what people call “Python automation” is just that first index card — hardcoded logic, predictable inputs, predictable outputs. AI agents break out of that box entirely. In this Python automation tutorial, you’ll understand why, and you’ll build something that proves it.
The Three Pillars Every AI Agent Is Built On
Before touching code, get this mental model locked in. Every agent — simple or sophisticated — runs on three things:
- Perception (Input): The agent receives something — a user message, a file, a sensor reading. This is raw information coming in.
- Reasoning (LLM): A large language model processes that input, decides what it means, and figures out what to do next. This is the brain.
- Action (Tools): The agent executes something in the real world — a web search, an API call, writing a file. Tools are how agents stop being chatbots and start being useful.
The loop between reasoning and action is what makes agents powerful. The LLM can call a tool, get a result, reason about that result, and call another tool — all on its own, until the job is done.
Tools You Need Before You Start
- Python 3.10 or higher
- An OpenAI API key (or Anthropic, Groq, etc.)
- The
openaiPython SDK (pip install openai) - A free weather API key from Open-Meteo — no account needed
- A terminal and a code editor you trust
Python Automation Tutorial: Building a Weather-Aware Research Agent
Step 1 — Set Up Your Environment
Create a project folder, activate a virtual environment, and install your dependencies.
mkdir weather-agent && cd weather-agent
python -m venv venv && source venv/bin/activate
pip install openai requests
Store your API key as an environment variable — never hardcode it.
export OPENAI_API_KEY="your-key-here"
Step 2 — Define the Agent’s Brain
The “brain” is just a configured OpenAI client plus a system prompt that tells the model what role it plays.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
SYSTEM_PROMPT = """
You are a helpful research assistant. When asked about weather or current conditions,
use the get_weather tool before answering. Always summarize clearly.
"""
Step 3 — Give the Agent Its Tools
Tools are plain Python functions you register with the model. Here’s a minimal weather fetcher using Open-Meteo’s free API.
import requests
def get_weather(latitude: float, longitude: float) -> dict:
url = f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}¤t_weather=true"
response = requests.get(url)
return response.json().get("current_weather", {})
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a latitude/longitude pair.",
"parameters": {
"type": "object",
"properties": {
"latitude": {"type": "number"},
"longitude": {"type": "number"}
},
"required": ["latitude", "longitude"]
}
}
}
]
Step 4 — Set the Reasoning Loop
This is where the magic lives. The agent thinks, optionally calls a tool, gets the result, and thinks again.
import json
def run_agent(user_message: str):
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_message}
]
while True:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=tools,
tool_choice="auto"
)
choice = response.choices[0]
if choice.finish_reason == "tool_calls":
tool_call = choice.message.tool_calls[0]
args = json.loads(tool_call.function.arguments)
result = get_weather(**args)
messages.append(choice.message)
messages.append({"role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(result)})
else:
print("Agent:", choice.message.content)
break
Step 5 — Run Your First Prompt
if __name__ == "__main__":
run_agent("What's the weather like in London right now? Should I bring an umbrella?")
Run it with python agent.py and watch it fetch real data, reason about it, and answer like a person.
Troubleshooting Common Issues
This Python automation tutorial wouldn’t be complete without a reality check on the errors you’ll actually hit:
AuthenticationError: Your API key is missing or wrong. Double-check your environment variable withecho $OPENAI_API_KEY.RateLimitError: You’ve hit your usage cap. Wait a moment or check your billing dashboard.JSONDecodeErroron tool args: The model occasionally returns malformed JSON. Wrap yourjson.loadsin a try/except and log the raw string.- The loop never ends: Add a
max_turnscounter as a safety valve. Five iterations is plenty for most tasks.
Where to Go From Here
You’ve just built something that perceives a question, reasons about it, calls a live API, and summarizes the result in plain English. That’s not a script — that’s an agent.
From here, the path forward is adding more tools (web search, email, database reads), chaining agents together, or exploring frameworks like LangChain or LlamaIndex that handle the loop scaffolding for you. But the foundation you built here? Every one of those systems runs on the same three pillars: Perception, Reasoning, Action.
Now go break something interesting.



