Everyone is talking about AI agents these days, and many explanations make them sound far more complicated than they actually are.
Once you strip away the frameworks, an agent is a relatively small piece of code. In this article, we'll build one from scratch in plain Python in about 150 lines, so you can see exactly what is happening under the hood.
So, What Is an AI Agent?
The simplest way to put it is: a chatbot talks, while an agent does things.
You give an agent a goal, and it works out which tools to use, checks what those tools return, and continues until it has an answer.
Suppose you ask a normal chatbot:
Is it warmer in Mumbai or Delhi right now?Without access to a live weather tool, it cannot reliably answer. It can only make an estimate based on information available to the model.
An agent handles the same question differently:
It calls a weather tool for Mumbai.
It calls the same tool again for Delhi.
It compares the two temperatures.
It tells you which city is warmer.
The interesting part is that nobody explicitly coded those three steps. The model decided which tools to call and in what order.
What We're Going to Build
We'll build a small command-line assistant called Atlas. It will have three tools:
Tool | What It Does | Example Question |
|---|---|---|
get_weather | Fetches live weather for any city using a free API with no API key | "Do I need an umbrella in Pune today?" |
calculate | Performs mathematical calculations safely | "What is 18% GST on 4,750?" |
get_current_time | Returns the date and time for a specified timezone | "What time is it in New York?" |
Atlas itself is a small learning project, but the pattern is widely applicable. Frameworks such as LangChain, CrewAI, Microsoft Agent Framework, and other agent frameworks implement variations of this same basic loop.
Once you understand the loop, these frameworks become much easier to understand.
How the Agent Loop Works
At its core, an agent repeatedly performs four steps:
Think — Send the conversation and the list of available tools to the model.
Decide — The model either answers directly or requests one or more tools.
Act — Python executes the requested tool. The model itself does not execute the code; it only requests the action.
Observe — Send the tool output back to the model and continue the loop.
When the model returns a final answer instead of requesting another tool, the loop ends.
The process looks like this:
User question
|
v
+--------------------+ wants a tool +---------------------+
| Model thinks | -----------------> | Python runs tool |
| (with tool list) | <----------------- | (weather, math...) |
+--------------------+ tool result +---------------------+
|
| final answer
v
Show to userEverything else in this article is essentially these four steps implemented in Python.
What You'll Need
Before starting, make sure you have the following:
Python 3.9 or later. Run
python --versionto check.An Anthropic API key.
A code editor such as VS Code.
This example uses Claude as the model. If you prefer OpenAI, Gemini, Azure OpenAI, or another provider, the overall architecture remains the same. The primary difference is the model client and API call.
Create a Project and Virtual Environment
Create a project folder and virtual environment:
mkdir atlas-agent
cd atlas-agent
python -m venv venv
# Windows
venv\Scripts\activate
# macOS / Linux
source venv/bin/activateInstall the Required Packages
Install the packages used by the project:
pip install anthropic requests python-dotenv tzdataEach package has a specific role:
anthropic — The SDK used to communicate with the model.
requests — Used to call the weather API.
python-dotenv — Loads the API key from the .env file.
tzdata — Provides timezone data, which is especially useful on Windows.
Keep the API Key Out of Your Code
Create a .env file in the project directory:
ANTHROPIC_API_KEY=sk-ant-your-key-hereIf the project uses Git, add .env to `.gitignore before committing the project.
API keys should never be hard-coded into source files or committed to a public repository.
Step 1: Make Sure Python Can Reach the Model
Before building the agent, verify that Python can communicate with the model.
Create a file named hello.py:
from dotenv import load_dotenv
from anthropic import Anthropic
load_dotenv() # Reads ANTHROPIC_API_KEY from .env
client = Anthropic()
response = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=500,
messages=[
{
"role": "user",
"content": "Say hello in one short sentence."
}
],
)
print(response.content[0].text)Run the program:
python hello.pyYou should receive a short response from the model.
If you receive an authentication error, check that:
The .env file exists in the project directory.
The API key is correct.
You are running the script from the expected directory.
The environment variable name matches ANTHROPIC_API_KEY.
The messages collection contains the conversation history. Each message has a role and content.
The model does not automatically remember previous API calls. The application needs to send the conversation history with each request. Our agent will continuously add messages to this list as it works through a request.
Step 2: Write the Tools
A tool is simply a Python function that the model can request.
Create agent.py and add the imports and three tools:
import ast
import json
import operator
from datetime import datetime
from zoneinfo import ZoneInfo
import requests
from dotenv import load_dotenv
from anthropic import Anthropic
load_dotenv()
client = Anthropic()
MODEL = "claude-sonnet-5-5"
# ---------- Tool 1: Weather ----------
def get_weather(city: str) -> dict:
geo = requests.get(
"https://geocoding-api.open-meteo.com/v1/search",
params={"name": city, "count": 1},
timeout=10,
).json()
if not geo.get("results"):
return {"error": f"City '{city}' not found"}
place = geo["results"][0]
weather = requests.get(
"https://api.open-meteo.com/v1/forecast",
params={
"latitude": place["latitude"],
"longitude": place["longitude"],
"current": (
"temperature_2m,"
"relative_humidity_2m,"
"precipitation,"
"wind_speed_10m"
),
},
timeout=10,
).json()
return {
"city": place["name"],
"country": place.get("country"),
**weather["current"],
}
# ---------- Tool 2: Safe Calculator ----------
OPERATORS = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.Pow: operator.pow,
ast.Mod: operator.mod,
ast.USub: operator.neg,
ast.UAdd: operator.pos,
}
def _evaluate(node):
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
return node.value
if isinstance(node, ast.BinOp) and type(node.op) in OPERATORS:
return OPERATORS[type(node.op)](
_evaluate(node.left),
_evaluate(node.right),
)
if isinstance(node, ast.UnaryOp) and type(node.op) in OPERATORS:
return OPERATORS[type(node.op)](
_evaluate(node.operand)
)
raise ValueError("Only numbers and + - * / ** % are allowed")
def calculate(expression: str) -> dict:
try:
result = _evaluate(
ast.parse(expression, mode="eval").body
)
return {
"expression": expression,
"result": result,
}
except Exception as e:
return {"error": str(e)}
# ---------- Tool 3: Current Time ----------
def get_current_time(timezone: str = "UTC") -> dict:
try:
now = datetime.now(ZoneInfo(timezone))
return {
"timezone": timezone,
"datetime": now.strftime(
"%A, %d %B %Y, %I:%M %p"
),
}
except Exception:
return {
"error": (
f"Unknown timezone '{timezone}'. "
"Use a name like 'Asia/Kolkata'."
)
}There are two important practices in this code that are useful for production agent development.
Return Tool Errors Instead of Stopping the Agent
The tools return errors as structured data instead of allowing an exception to stop the entire agent.
For example, if a user enters an invalid city name, the weather tool returns an error that the model can understand. The model can then try another spelling or ask the user for clarification.
Never Use eval() for Model-Generated Expressions
The calculator does not use Python's eval() function.
You should treat anything returned by a model as untrusted input, just as you would treat user input. Passing arbitrary model-generated expressions directly to eval() could allow unintended Python code to execute.
Instead, this example parses the expression using Python's ast module and allows only a specific set of arithmetic operations.
Step 3: Tell the Model Which Tools Are Available
The model cannot directly inspect your Python functions.
Instead, the application sends the model a description of each tool, including:
The tool name.
A description of when it should be used.
A JSON Schema describing its inputs.
Add the following after the tool functions:
TOOLS = [
{
"name": "get_weather",
"description": (
"Get the current weather for a city. Use this for any "
"question about weather, temperature, rain, humidity or wind."
),
"input_schema": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, e.g. 'Mumbai'",
}
},
"required": ["city"],
},
},
{
"name": "calculate",
"description": (
"Evaluate a math expression. Use this for any arithmetic "
"instead of calculating in your head."
),
"input_schema": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "e.g. '4750 * 0.18'",
}
},
"required": ["expression"],
},
},
{
"name": "get_current_time",
"description": (
"Get the current date and time in an IANA timezone."
),
"input_schema": {
"type": "object",
"properties": {
"timezone": {
"type": "string",
"description": (
"e.g. 'Asia/Kolkata', 'America/New_York'"
),
}
},
"required": ["timezone"],
},
},
]
TOOL_FUNCTIONS = {
"get_weather": get_weather,
"calculate": calculate,
"get_current_time": get_current_time,
}The tool description is particularly important.
The model chooses tools based on the information provided in these definitions. A vague description can cause an agent to ignore a tool or select the wrong one.
Instead of describing only what a tool does, explain when the model should use it.
For example:
Get the current weather for a city.
Use this for questions about weather, temperature, rain, humidity, or wind.is more useful than:
Returns weather information.Step 4: Write the Agent Loop
This is the core of the agent.
It implements the Think, Decide, Act, and Observe cycle described earlier.
SYSTEM_PROMPT = (
"You are Atlas, a helpful assistant. Use your tools whenever they give "
"a more accurate answer than guessing. Keep answers short and clear."
)
def run_agent(messages: list, max_steps: int = 10) -> str:
for _ in range(max_steps):
# 1. THINK: Send the conversation and tool list.
response = client.messages.create(
model=MODEL,
max_tokens=1024,
system=SYSTEM_PROMPT,
tools=TOOLS,
messages=messages,
)
messages.append({
"role": "assistant",
"content": response.content,
})
# 2. DECIDE: No tool request means the model is done.
if response.stop_reason != "tool_use":
return "".join(
block.text
for block in response.content
if block.type == "text"
)
# 3. ACT: Execute every requested tool.
tool_results = []
for block in response.content:
if block.type == "tool_use":
print(
f" [tool] {block.name}({block.input})"
)
try:
result = TOOL_FUNCTIONS[block.name](
**block.input
)
except Exception as e:
result = {"error": str(e)}
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(result),
})
# 4. OBSERVE: Send tool results back to the model.
messages.append({
"role": "user",
"content": tool_results,
})
return "Sorry, I could not finish that within the step limit."Several details in this function are important.
stop_reason
stop_reason tells the application why the model stopped generating.
If it is:
tool_usethe model is requesting one or more tools.
If it stops for another reason, the application can treat the response as the final answer.
block.id
The tool-use ID connects a tool result to the specific tool request that generated it.
This becomes important when the model requests multiple tools in a single response.
For example, it might request weather information for both Mumbai and Delhi. Each tool request receives an ID, allowing the corresponding results to be associated correctly.
Tool Results
The tool results are sent back to the model as part of the next message.
The model uses those results as observations and decides whether it needs another tool or can provide the final answer.
max_steps
The max_steps value acts as a safety limit.
Without a limit, a model that repeatedly requests tools could continue indefinitely and consume unnecessary API credits.
In production systems, additional limits such as token budgets, execution timeouts, tool-specific rate limits, and authorization checks are also useful.
Step 5: Add a Simple Chat Interface
The final piece is a small command-line interface.
Add this to the bottom of agent.py:
def main():
print("Atlas is ready. Type 'exit' to quit.\n")
messages = []
while True:
user_input = input("You: ").strip()
if user_input.lower() in {"exit", "quit"}:
break
if not user_input:
continue
messages.append({
"role": "user",
"content": user_input,
})
print(f"Atlas: {run_agent(messages)}\n")
if __name__ == "__main__":
main()Run the application:
python agent.pyYou can now interact with Atlas from the terminal.
Example Agent Session
Try a question that requires multiple tools:
Atlas is ready. Type 'exit' to quit.
You: Is it warmer in Mumbai or Delhi right now? And what time is it there?
[tool] get_weather({'city': 'Mumbai'})
[tool] get_weather({'city': 'Delhi'})
[tool] get_current_time({'timezone': 'Asia/Kolkata'})
Atlas: Mumbai is warmer at 31.2°C, compared with 24.8°C in Delhi.
It's 10:58 AM on Saturday in both cities (they share IST).
You: What is 18% GST on 4750?
[tool] calculate({'expression': '4750 * 0.18'})
Atlas: 18% GST on 4,750 is 855, making the total 5,605.Your actual weather and time values will be different because the application uses live data.
The important part is the [tool] output.
We did not explicitly program Atlas to:
Check Mumbai.
Check Delhi.
Compare the temperatures.
Check the current Indian time.
The model decided which tools were necessary based on the available tool descriptions and the user's request.
That decision-making loop is what makes the application an agent rather than a basic chatbot.
Because the messages list contains the conversation history, follow-up questions can also use previous context.
For example:
And in Bangalore?Atlas can understand that the question refers to the previous weather discussion.
How the Pieces Fit Together
At this point, the complete architecture can be summarized as:
User Question
|
v
+---------------+
| Language |
| Model |
+-------+-------+
|
Tool Request
|
v
+---------------+
| Python Agent |
| Loop |
+-------+-------+
|
+-----------+-----------+
| | |
v v v
Weather Calculator Time
| | |
+-----------+-----------+
|
Tool Result
|
v
+---------------+
| Language |
| Model |
+-------+-------+
|
v
Final AnswerThe model provides reasoning and tool-selection decisions. Your Python application remains responsible for actually executing the tools.
This separation is important for security and control.
Troubleshooting
Problem | Likely Cause | Fix |
|---|---|---|
AuthenticationError | The API key is missing or incorrect. | Make sure |
ModuleNotFoundError | The virtual environment is not active or dependencies are missing. | Activate |
The model answers without calling a tool | The tool description may be too vague. | Update the description so it clearly explains when the tool should be used. |
Unknown timezone error on Windows | Timezone data is unavailable. | Install |
The agent hits the step limit | A tool may be repeatedly failing or the model may be unable to complete the task. | Log tool requests and results to identify what is happening. |
Taking the Agent Further
The basic agent is now working, but the same architecture can be extended in several directions.
Add More Tools
Create another Python function, describe it in TOOLS, and register it in TOOL_FUNCTIONS.
Possible additions include:
File readers.
Web search.
Database queries.
Internal knowledge-base searches.
API integrations.
System monitoring tools.
Add Confirmation for Risky Actions
Read-only tools are relatively easy to control.
Tools that perform actions require additional safeguards.
For example, if an agent can send emails or delete database records, require explicit user confirmation before executing those operations.
A simple implementation could use a confirmation step such as:
confirmation = input("Allow this action? (y/n): ")For production systems, authorization, audit logging, scoped permissions, and policy enforcement should also be considered.
Add Memory Across Sessions
The current implementation stores the conversation only while the program is running.
You could persist the messages collection to a database or file and restore it when the application starts.
For larger applications, memory should usually be designed separately from the model conversation itself. Long conversations can increase token usage, so summarization or retrieval-based memory may be more appropriate.
Try an Agent Framework
Once the basic loop is clear, frameworks such as LangChain, CrewAI, Microsoft Agent Framework, or the Claude Agent SDK become easier to understand.
Instead of treating the framework as a black box, you can map its components back to the same concepts:
Model.
Tools.
Tool definitions.
Agent loop.
Tool execution.
Tool results.
Guardrails.
Memory.
The framework mainly provides additional infrastructure around these building blocks.
Production Considerations
The 150-line example is intentionally simple. A production agent needs more controls around the same basic architecture.
Some areas to consider include:
Tool Authorization
Not every user or agent should have access to every tool. Apply permissions based on the user's identity and the operation being performed.
Timeouts
External APIs can fail or become slow. Apply timeouts to HTTP requests and tool executions.
Rate Limiting
An agent can potentially call a tool multiple times during a single request. Rate limits help protect external services and control costs.
Logging and Observability
Log tool calls, execution time, errors, model responses, and important decisions without exposing secrets or sensitive user data.
Cost Controls
Use maximum step counts, token limits, and tool-specific budgets to prevent unexpected usage.
Input Validation
Treat model-generated tool arguments as untrusted input. Validate arguments before passing them to external systems.
Error Handling
Tool failures should be returned in a structured form that the model can understand, while sensitive implementation details should remain hidden from the user.
Wrapping Up
There's nothing magical about the basic architecture of an AI agent.
Take a language model, give it a set of clearly described tools, and place it inside a loop where it can request those tools and observe their results until it has enough information to produce an answer.
In this article, we built each of those pieces by hand in plain Python.
The implementation included:
Three practical tools.
Structured tool definitions.
Safe mathematical evaluation.
Tool error handling.
A Think, Decide, Act, and Observe loop.
Multiple tool calls.
Conversation history.
A maximum execution-step limit.
A simple command-line interface.
The agents used in coding assistants, research applications, customer-support systems, and automation platforms follow the same fundamental pattern, although production implementations add more tools, memory, security controls, observability, and guardrails.
Understanding this underlying loop makes it much easier to reason about agent frameworks and build your own agent-based applications.


Join the conversation! Your thoughts help the community grow.