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.
- Beginner: The Basic Agent Loop
Almost every agent in the world is a variation of this short loop:
Remember: The history list is the memory of the run. Each new tool result makes the next model call better informed.
- 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 goal | Strong goal | Why it is better |
|---|---|---|
| Find me a laptop | Find a laptop under 1000 that is in stock and give the price with 18% tax | Has a budget, a condition and an output |
| Help with my data | Report the total sales per customer from the orders table | Names the source and the result |
| Research agents | Find three recent sources about agents and summarize each in two sentences | Has 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.
- 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:
| Tool | Input | Output |
|---|---|---|
| search_products | max_price | A list of matching products |
| check_stock | product_id | Whether it is in stock |
| calculate_total | price, tax_percent | The total with tax |
- 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.
- Advanced: Common First-Agent Mistakes
| Mistake | What goes wrong | Fix |
|---|---|---|
| No step limit | Endless loops and big bills | Always set a maximum number of steps |
| Vague goal | The agent wanders or stops early | State the outcome and constraints |
| Too many tools | The model picks the wrong one | Start with a few distinct tools |
| Ignoring tool errors | The agent repeats the same failing call | Return clear errors into the history |
| No logging | You cannot see why it failed | Print or record every step |
| Trusting the model blindly | Wrong or unsafe calls get executed | Validate 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.
- 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.
Click to see what the trace is forCompare ▼
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.
- 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.
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.")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
Key Points
The Big Picture
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.