Velamuvi AIAcademy

Lesson 6 of 7 · A First Agent

Build a Minimal Agent in Python

Build a working AI agent in about 40 lines of Python: tool definitions, the agent loop, parallel tool calls, tool results and a step limit. Runs in the browser.

  • 6 min read
  • Beginner
  • Reviewed
In this lesson you will learn
  • Build a complete agent loop around an LLM API
  • Handle several tool calls in one response
  • Send tool results back in the format the API expects
  • Swap the scripted model for a real one

The plan

You'll build an agent that answers questions using a weather tool. It has every part from this course: tool definitions, a loop, tool calls and results, and a step limit. About 40 lines of Python.

To run here without an API key, the program uses a scripted client: a small class that answers in exactly the same shape as Anthropic's Messages API, following a fixed script. The agent code is identical to the real version, which comes after.

Try it yourselfPython
import json

# ---- Tools: the definitions the model sees, and the functions that run ----
TOOLS = [
    {
        "name": "get_weather",
        "description": "Get today's weather for a city. Returns temperature in °C and the sky.",
        "input_schema": {
            "type": "object",
            "properties": {"city": {"type": "string", "description": "City name, e.g. Lisbon"}},
            "required": ["city"],
        },
    },
]

def get_weather(city):
    data = {"lisbon": {"temp_c": 24, "sky": "sunny"}, "oslo": {"temp_c": 3, "sky": "light snow"}}
    return data.get(city.lower(), {"error": f"No weather data for {city}"})

FUNCTIONS = {"get_weather": get_weather}

from types import SimpleNamespace as Obj

class ScriptedClient:
    """Imitates an LLM API client, following a fixed script, so this page can run without a key.
    It returns responses in the same shape as Anthropic's Messages API."""
    def __init__(self):
        self.messages = self
    def create(self, model, max_tokens, tools, messages):
        last = messages[-1]["content"]
        if isinstance(last, str):                                   # first turn: ask for two tools at once
            return Obj(stop_reason="tool_use", content=[
                Obj(type="text", text="I'll check both cities."),
                Obj(type="tool_use", id="call_1", name="get_weather", input={"city": "Lisbon"}),
                Obj(type="tool_use", id="call_2", name="get_weather", input={"city": "Oslo"}),
            ])
        lisbon, oslo = (json.loads(r["content"]) for r in last)     # read the tool results
        warmer = "Lisbon" if lisbon["temp_c"] > oslo["temp_c"] else "Oslo"
        return Obj(stop_reason="end_turn", content=[Obj(type="text", text=(
            f"{warmer} is warmer today: Lisbon is {lisbon['temp_c']}°C and {lisbon['sky']}, "
            f"Oslo is {oslo['temp_c']}°C with {oslo['sky']}."))])

client = ScriptedClient()          # in real code: client = anthropic.Anthropic()

# ---- The agent loop (identical to the real version) ----
def run_agent(task, max_steps=8):
    messages = [{"role": "user", "content": task}]
    for step in range(max_steps):
        response = client.messages.create(
            model="MODEL_NAME", max_tokens=1000, tools=TOOLS, messages=messages,
        )
        messages.append({"role": "assistant", "content": response.content})

        if response.stop_reason != "tool_use":                 # no tool requested: we're done
            return "".join(b.text for b in response.content if b.type == "text")

        results = []
        for block in response.content:                        # run every tool the model asked for
            if block.type == "tool_use":
                print(f"  tool call: {block.name}({block.input})")
                output = FUNCTIONS[block.name](**block.input)
                results.append({"type": "tool_result", "tool_use_id": block.id, "content": json.dumps(output)})
        messages.append({"role": "user", "content": results})  # results go back as a user message
    return "Stopped: step limit reached."

print("Task: Which is warmer today, Lisbon or Oslo?")
print("Answer:", run_agent("Which is warmer today, Lisbon or Oslo?"))

How it works

The loop (run_agent) calls the model with the conversation and the tool definitions, then looks at stop_reason:

  • "tool_use": the model wants tools run. The loop runs every tool call in the response (here two at once, Lisbon and Oslo), and adds the results as a single user message.
  • anything else: the model has finished, so the loop returns its text.

Tool results are matched to their calls by ID. Each result says which call it answers (tool_use_id), which is how the model knows which temperature belongs to which city.

The real version

On your own computer, install the SDK (pip install anthropic), set your API key (see the Working with AI APIs course), and replace the scripted client with the real one. Everything else stays the same:

import json
import anthropic

client = anthropic.Anthropic()          # reads ANTHROPIC_API_KEY from the environment

# ---- Tools: the definitions the model sees, and the functions that run ----
TOOLS = [
    {
        "name": "get_weather",
        "description": "Get today's weather for a city. Returns temperature in °C and the sky.",
        "input_schema": {
            "type": "object",
            "properties": {"city": {"type": "string", "description": "City name, e.g. Lisbon"}},
            "required": ["city"],
        },
    },
]

def get_weather(city):
    data = {"lisbon": {"temp_c": 24, "sky": "sunny"}, "oslo": {"temp_c": 3, "sky": "light snow"}}
    return data.get(city.lower(), {"error": f"No weather data for {city}"})

FUNCTIONS = {"get_weather": get_weather}

# ---- The agent loop ----
def run_agent(task, max_steps=8):
    messages = [{"role": "user", "content": task}]
    for step in range(max_steps):
        response = client.messages.create(
            model="MODEL_NAME", max_tokens=1000, tools=TOOLS, messages=messages,
        )
        messages.append({"role": "assistant", "content": response.content})

        if response.stop_reason != "tool_use":                 # no tool requested: we're done
            return "".join(b.text for b in response.content if b.type == "text")

        results = []
        for block in response.content:                        # run every tool the model asked for
            if block.type == "tool_use":
                print(f"  tool call: {block.name}({block.input})")
                output = FUNCTIONS[block.name](**block.input)
                results.append({"type": "tool_result", "tool_use_id": block.id, "content": json.dumps(output)})
        messages.append({"role": "user", "content": results})  # results go back as a user message
    return "Stopped: step limit reached."

if __name__ == "__main__":
    print(run_agent("Which is warmer today, Lisbon or Oslo?"))

Replace get_weather's fake data with a call to a real weather API and you have a genuinely useful agent. The answer a real model writes will differ in wording from the scripted one, and it may call the tools in a different order, but the loop handles any order.

Common mistakes

Practice exercise

Write the part of the agent loop that runs every tool the model asked for and packages the results to send back.

Your solutionPython
import json
from types import SimpleNamespace as Obj

def get_weather(city):
    return {"Lisbon": 24, "Oslo": 3}[city]

FUNCTIONS = {"get_weather": get_weather}

# A response in which the model asked for two tools at once
content = [
    Obj(type="text", text="Checking both."),
    Obj(type="tool_use", id="call_1", name="get_weather", input={"city": "Lisbon"}),
    Obj(type="tool_use", id="call_2", name="get_weather", input={"city": "Oslo"}),
]

results = []
# For every block with type "tool_use", run the function and append
# {"type": "tool_result", "tool_use_id": <the block's id>, "content": json.dumps(<output>)}

for r in results:
    print(r["tool_use_id"], r["content"])
Knowledge check

The model's response has stop_reason equal to tool_use and contains two tool calls. What should the loop do?

Summary

  • A minimal agent is tool definitions, functions, and a loop that calls the model until it stops asking for tools.
  • Run every tool call in a response and return results with their call IDs.
  • Append the model's message, then the results, so the history stays complete.
  • A scripted client lets you test the loop without an API; swapping in a real client changes one line.

Next: when an agent is the wrong tool for the job.

Finished reading? Tick it off to track your progress.