Building Your First AI Agent

Build your first AI agent step by step: the basic agent loop, giving the agent a clear goal, adding tools, and running a multi-step task from start to finish, with a complete agent in Python.

30 minBeginnerCode Examples

The Core Idea: Your first agent is only a loop: send the goal and history to the model, run the tool it asks for, add the result to the history, and repeat until the model gives a final answer or a step limit stops it.

  1. Beginner: The Basic Agent Loop

Almost every agent in the world is a variation of this short loop:

1
Start with messages: A list that begins with the goal as the first user message.
2
Ask the model: Send the messages. The reply is either a tool call or a final answer.
3
If it is a tool call: Validate it, run the tool, and append the result as a tool message.
4
If it is a final answer: Stop and return it.
5
Safety net: If the step counter reaches the maximum, stop with a clear message.

Remember: The history list is the memory of the run. Each new tool result makes the next model call better informed.

  1. Beginner: Giving an Agent a Goal

The goal is the most important input. A clear goal tells the agent what to achieve and when it is finished.

Weak goalStrong goalWhy it is better
Find me a laptopFind a laptop under 1000 that is in stock and give the price with 18% taxHas a budget, a condition and an output
Help with my dataReport the total sales per customer from the orders tableNames the source and the result
Research agentsFind three recent sources about agents and summarize each in two sentencesHas a count and a format

A good goal has: a clear outcome, constraints (budget, time, allowed tools) and a way to tell when it is done.

  1. Medium: Adding Tools

Start small. Give the first agent two or three tools that match the goal. In our example the shop agent has exactly three:

ToolInputOutput
search_productsmax_priceA list of matching products
check_stockproduct_idWhether it is in stock
calculate_totalprice, tax_percentThe total with tax
How to add a tool safely
Write the function, give it a clear name and description, test it alone with normal and bad input, then add it to the registry the agent can see. An untested tool makes the agent look broken.

  1. Medium: Running Multi-Step Tasks

The goal in the code needs four steps, and the agent finds them itself: search, check stock, handle the out-of-stock case by checking the next product, then calculate the total. Each step depends on the one before it, which is the reason an agent is used here instead of one fixed script.

Look at step 3 in the output: Laptop A was out of stock, so the agent did not give up. It checked the next product. Reacting to a result is the defining behavior of an agent.

Printing every step, as the code does, gives you a trace. A trace is the best debugging tool you have: when an agent does something strange, read the trace from the top.

  1. Advanced: Common First-Agent Mistakes

MistakeWhat goes wrongFix
No step limitEndless loops and big billsAlways set a maximum number of steps
Vague goalThe agent wanders or stops earlyState the outcome and constraints
Too many toolsThe model picks the wrong oneStart with a few distinct tools
Ignoring tool errorsThe agent repeats the same failing callReturn clear errors into the history
No loggingYou cannot see why it failedPrint or record every step
Trusting the model blindlyWrong or unsafe calls get executedValidate every call in code

Reminder: The loop in this lesson uses a rule-based stand-in for the model so it runs without an API key. With a real model, nothing about the loop changes, only the function that decides the next step.

  1. Visual Explanation: One Goal, Five Steps

The figure follows the run of the shop agent from the code, then lists what a good goal contains.

Part 1 · The Run in the CodeOne goal, five steps
FindSteps 1 to 3
search_products under 1000
↓
check_stock of Laptop A: out of stock
↓
check_stock of Laptop B: in stock
↓
Laptop B is the pick
CalculateStep 4
calculate_total for 950 at 18% tax
↓
Total: 1121.0
AnswerStep 5
Model sees all results
↓
Writes the final answer
↓
Laptop B is in stock. Total with tax: 1121.0
Part 2 · What a Goal NeedsThree parts
Outcome
What to deliver
Price with tax, a report, three sources.
Constraints
Limits
Budget, time, allowed tools.
Done test
How to stop
A clear sign the goal is met.
Click to see what the trace is forCompare ▼
The trace lists every action and result in order. If the agent behaves strangely, read it from the top and find the first step where reality differed from what you expected.

Part 1 groups the five steps into find, calculate and answer. Part 2 lists the three parts of a goal. Open the bar to see why the trace matters.

  1. Python Implementation: A Complete Multi-Step Agent

This script is a full agent: three tools, a goal, a message history, a loop with a step limit, and a rule-based stand-in for the model. It searches, checks stock, recovers when an item is out of stock, and calculates the final price.

first_agent.pyPython 3.10+ · standard library only
import json PRODUCTS = [    {"id": 1, "name": "Laptop A", "price": 800, "stock": 0},    {"id": 2, "name": "Laptop B", "price": 950, "stock": 4},    {"id": 3, "name": "Laptop C", "price": 1200, "stock": 9},] def search_products(max_price):    found = [p for p in PRODUCTS if p["price"] <= max_price]    return [{"id": p["id"], "name": p["name"], "price": p["price"]} for p in sorted(found, key=lambda p: p["price"])] def check_stock(product_id):    product = next(p for p in PRODUCTS if p["id"] == product_id)    return {"id": product_id, "in_stock": product["stock"] > 0} def calculate_total(price, tax_percent):    return {"total": round(price * (1 + tax_percent / 100), 2)} TOOLS = {"search_products": search_products, "check_stock": check_stock, "calculate_total": calculate_total} def fake_llm(messages):    # Stands in for a real model: decides the next step from the conversation so far    tool_msgs = [m for m in messages if m["role"] == "tool"]    if not tool_msgs:        return {"tool": "search_products", "arguments": {"max_price": 1000}}    found = json.loads(tool_msgs[0]["content"])    stock_checks = [m for m in tool_msgs if m["name"] == "check_stock"]    if stock_checks and json.loads(stock_checks[-1]["content"])["in_stock"]:        product_id = json.loads(stock_checks[-1]["content"])["id"]        product = next(p for p in found if p["id"] == product_id)        totals = [m for m in tool_msgs if m["name"] == "calculate_total"]        if not totals:            return {"tool": "calculate_total", "arguments": {"price": product["price"], "tax_percent": 18}}        return {"answer": product["name"] + " is in stock. Total with tax: " + str(json.loads(totals[-1]["content"])["total"])}    if len(stock_checks) >= len(found):        return {"answer": "Nothing under budget is in stock."}    return {"tool": "check_stock", "arguments": {"product_id": found[len(stock_checks)]["id"]}} def run_agent(goal, max_steps=8):    messages = [{"role": "user", "content": goal}]    for step in range(1, max_steps + 1):        decision = fake_llm(messages)        if "answer" in decision:            print("Step", step, "| FINAL:", decision["answer"])            return decision["answer"]        name, args = decision["tool"], decision["arguments"]        result = TOOLS[name](**args)        print("Step", step, "|", name, args, "->", result)        messages.append({"role": "tool", "name": name, "content": json.dumps(result)})    return "Stopped: step limit reached" run_agent("Find a laptop under 1000 that is in stock and tell me the price with 18% tax.")
EXPECTED OUTPUT (your numbers may differ slightly)
Step 1 | search_products {'max_price': 1000} -> [{'id': 1, 'name': 'Laptop A', 'price': 800}, {'id': 2, 'name': 'Laptop B', 'price': 950}]
Step 2 | check_stock {'product_id': 1} -> {'id': 1, 'in_stock': False}
Step 3 | check_stock {'product_id': 2} -> {'id': 2, 'in_stock': True}
Step 4 | calculate_total {'price': 950, 'tax_percent': 18} -> {'total': 1121.0}
Step 5 | FINAL: Laptop B is in stock. Total with tax: 1121.0

The agent hits an out-of-stock item at step 2, changes course, and still finishes the task. The trace prints each tool call and result, which is exactly what you should read when debugging a real agent.

Knowledge Check

Question 1: What makes a goal strong?
Question 2: What did the agent do when the first laptop was out of stock?

Key Points

✓A first agent is a loop: ask the model, run the tool, append the result, repeat.
✓The message history is the agent's working memory for the run.
✓A strong goal states the outcome, the constraints and how to tell it is done.
✓Start with two or three clear tools and test each one alone.
✓Printing a trace of every step is the best debugging tool.
✓Always set a step limit, validate calls and return clear errors.

The Big Picture

Your First Agent in One Line

Goal in the history → model picks a tool → run it → append the result → repeat → final answer

The same loop powers far more advanced agents. What changes is the quality of the tools, the memory and the reasoning.

Up Next: Your agent so far uses simple tools. In Agents with External Tools you will connect it to APIs, databases, web search, code execution and files, safely.