AI

How to Build an AI Agent From Scratch in Python, for Free

How to Build an AI Agent From Scratch in Python, for Free

Short answer: an AI agent is a large language model (LLM) that can call your functions (tools) inside a loop. The model reads the question and asks for a tool. Your code runs the tool and sends back the result, and this repeats until the model answers. You can build one in about 60 lines of plain Python, for free, with a local model running in Ollama.

This post builds that agent step by step, with no framework and no pip install. Every output shown was produced by running the code on a laptop.

What is an AI agent?

An agent has three parts. Each one is simpler than it sounds.

  1. The LLM. A large language model, like the one behind ChatGPT, reads text and writes text. It cannot run code, open files or check today's date on its own. It only predicts what text should come next.
  2. Tools. A tool is an ordinary function in your program, such as a calculator. You describe each tool to the model with a name, a one-line description and the arguments it takes. The model cannot run the tool. It can only reply "please run calculator with 2499 * 0.18".
  3. The loop. Your code runs the tool the model asked for and sends the result back. Then it asks the model again. The loop ends when the model replies with plain text instead of a tool request.

Anthropic's guide Building effective agents was published on 19 December 2024. It puts it in one line: agents "are typically just LLMs using tools based on environmental feedback in a loop". Earlier, the 2022 research paper ReAct (Yao et al.) had LLMs produce "reasoning traces and task-specific actions in an interleaved manner".

Think of the model as a manager who cannot touch a keyboard. It gives instructions, an assistant (your loop) carries them out, and the manager decides what to do next from the results.

Plain chatbotAgent
Can call your functionsNoYes, through tool calls
Number of model calls per questionOneOne per step, until it answers
Arithmetic and datesGuessed from training textComputed by your code
Main new riskWrong answersWrong actions, if tools can change things

What you need (all free)

  • Python 3. The code uses only the standard library: json, urllib, ast and datetime. We tested on Python 3.12.
  • Ollama. A free program that downloads open models and serves them on your laptop at http://localhost:11434. Install it from ollama.com/download.
  • A small model that supports tool calling. We use qwen2.5:3b, a 3-billion-parameter model from Alibaba's Qwen team. Its download is 1.9 GB on the Ollama library page, which tags it with "tools". Get it with ollama pull qwen2.5:3b. Unlike most Qwen 2.5 sizes, the 3B model is not Apache 2.0. ollama show lists the Qwen Research License below, so read it before any commercial use.

Ollama added tool calling on 25 July 2024 (announcement). You can confirm that your model supports it:

ollama show qwen2.5:3b
  Model
    architecture        qwen2     
    parameters          3.1B      
    context length      32768     
    embedding length    2048      
    quantization        Q4_K_M    

  Capabilities
    completion    
    tools         

  System
    You are Qwen, created by Alibaba Cloud. You are a helpful assistant.    

  License
    Qwen RESEARCH LICENSE AGREEMENT                                     
    Qwen RESEARCH LICENSE AGREEMENT Release Date: September 19, 2024    
    ...                                                                 

The tools line under Capabilities is what we need. If a model does not list it, pick another model for this post.

Step 1: write the tools

Our agent gets three small, safe tools: a calculator, a unit converter and a date counter. A language model predicts text, so it can get exact arithmetic and calendar maths wrong. These are real gaps a tool fills. Save this as tools.py:

# tools.py: three small tools and their JSON schemas (standard library only)
import ast
import json
import operator
from datetime import date

OPS = {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 calculator(expression):
    """Evaluate arithmetic like '2 * (3 + 4)' without eval(). Only numbers and OPS allowed."""
    if len(expression) > 200:
        raise ValueError("expression too long")
    def walk(node):
        if isinstance(node, ast.Constant) and type(node.value) in (int, float):
            return node.value
        if isinstance(node, ast.BinOp) and type(node.op) in OPS:
            left, right = walk(node.left), walk(node.right)
            if isinstance(node.op, ast.Pow) and abs(right) > 100:
                raise ValueError("exponent too large")
            return OPS[type(node.op)](left, right)
        if isinstance(node, ast.UnaryOp) and type(node.op) in OPS:
            return OPS[type(node.op)](walk(node.operand))
        raise ValueError(f"not allowed in a calculator: {type(node).__name__}")
    result = walk(ast.parse(expression, mode="eval").body)
    return round(result, 6) if isinstance(result, float) else result


METRES = {"m": 1, "km": 1000, "cm": 0.01, "mi": 1609.344, "ft": 0.3048}


def convert_units(value, from_unit, to_unit):
    """Convert a length (m, km, cm, mi, ft) or a temperature (C, F)."""
    value = float(value)
    if from_unit in ("C", "F") and to_unit in ("C", "F"):
        celsius = value if from_unit == "C" else (value - 32) / 1.8
        out = celsius if to_unit == "C" else celsius * 1.8 + 32
    elif from_unit in METRES and to_unit in METRES:
        out = value * METRES[from_unit] / METRES[to_unit]
    else:
        raise ValueError(f"cannot convert {from_unit} to {to_unit}; known units: m, km, cm, mi, ft, C, F")
    return round(out, 4)


def days_between(start, end):
    """Days from start to end (dates as YYYY-MM-DD) and the weekday of end."""
    d1, d2 = date.fromisoformat(start), date.fromisoformat(end)
    return {"days": (d2 - d1).days, "end_weekday": d2.strftime("%A")}


def schema(fn, description, **params):
    """Build the JSON schema that tells the model what a tool does and what it takes."""
    props = {p: {"type": t, "description": d} for p, (t, d) in params.items()}
    return {"type": "function", "function": {
        "name": fn.__name__, "description": description,
        "parameters": {"type": "object", "properties": props, "required": list(props)}}}


TOOLS = {f.__name__: f for f in (calculator, convert_units, days_between)}
SCHEMAS = [
    schema(calculator, "Evaluate an arithmetic expression with + - * / ** % and brackets.",
           expression=("string", "for example (12.5 * 4) / 3")),
    schema(convert_units, "Convert a length (m, km, cm, mi, ft) or a temperature (C, F).",
           value=("number", "the amount"), from_unit=("string", "unit to convert from"),
           to_unit=("string", "unit to convert to")),
    schema(days_between, "Count days between two dates and give the weekday of the end date.",
           start=("string", "start date, YYYY-MM-DD"), end=("string", "end date, YYYY-MM-DD")),
]

if __name__ == "__main__":
    print(calculator("2 * (3 + 4) ** 2"))
    print(convert_units(42, "km", "mi"), convert_units(37, "C", "F"))
    print(days_between("2026-11-20", "2027-01-26"))
    for bad in ["__import__('os').system('ls')", "10 / 0"]:
        try:
            calculator(bad)
        except Exception as e:
            print(f"{type(e).__name__}: {e}")
    print(json.dumps(SCHEMAS[0], indent=2))
98
26.0976 98.6
{'days': 67, 'end_weekday': 'Tuesday'}
ValueError: not allowed in a calculator: Call
ZeroDivisionError: division by zero
{
  "type": "function",
  "function": {
    "name": "calculator",
    "description": "Evaluate an arithmetic expression with + - * / ** % and brackets.",
    "parameters": {
      "type": "object",
      "properties": {
        "expression": {
          "type": "string",
          "description": "for example (12.5 * 4) / 3"
        }
      },
      "required": [
        "expression"
      ]
    }
  }
}

Three things to notice:

  • The calculator never calls eval(). Python's documentation warns that eval "executes arbitrary code". A model's tool call is untrusted input, so we parse the text with the ast module instead. An AST (abstract syntax tree) is the parsed structure of the expression. We walk it and allow only numbers and maths operators. The __import__('os') attack is rejected as a Call. The length and exponent limits stop inputs that are slow to compute.
  • The conversion factors are exact. One mile is 1,609.344 m and one foot is 0.3048 m, from NIST SP 811, Appendix B.8. Fahrenheit uses °C = (°F − 32)/1.8 from the same table.
  • Each schema is JSON Schema. It is a standard way to describe JSON data: the argument names, their types and which ones are required. The model sees only this description, never your Python code. A clear description is the main way you steer which tool it picks.

Step 2: one tool call by hand

Before writing a loop, do one round trip by hand to see the messages. Ollama's /api/chat endpoint takes the conversation as a list of messages plus a tools list. Each message has a role: system (standing instructions), user, assistant (the model) or tool (a tool result).

Start ollama serve in one terminal (the desktop app starts it for you), then run first_call.py from the folder that holds tools.py:

# first_call.py: one tool call by hand, so you can see the raw messages
import json
import urllib.request

from tools import SCHEMAS, TOOLS


def chat(messages):
    body = {"model": "qwen2.5:3b", "messages": messages, "tools": SCHEMAS, "stream": False,
            "options": {"temperature": 0, "seed": 42}}
    request = urllib.request.Request("http://localhost:11434/api/chat",
                                     data=json.dumps(body).encode(),
                                     headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(request, timeout=600) as response:
        return json.load(response)["message"]


messages = [{"role": "user", "content": "What is 18% GST on an order of 2499 rupees?"}]
reply = chat(messages)
call = reply["tool_calls"][0]["function"]
print("1. model asks for:", json.dumps(call))

result = json.dumps(TOOLS[call["name"]](**call["arguments"]))
messages += [reply, {"role": "tool", "tool_name": call["name"], "content": result}]
print("2. we send back:  ", json.dumps(messages[-1]))

print("3. model answers: ", chat(messages)["content"])
1. model asks for: {"index": 0, "name": "calculator", "arguments": {"expression": "(2499 * 18 / 100)"}}
2. we send back:   {"role": "tool", "tool_name": "calculator", "content": "449.82"}
3. model answers:  The GST on an order of 2499 rupees at a rate of 18% is 449.82 rupees.

This output came from qwen2.5:3b on Ollama 0.24.0, with temperature 0 and seed 42. Your wording in line 3 may differ, but the tool call and the number should match.

Here is the format, as documented in Ollama's tool calling guide:

  1. The model's reply has an empty content and a tool_calls list. Each entry names a function and gives its arguments as a JSON object.
  2. You run the function yourself. The model never touches your machine.
  3. You append two messages: the model's reply, then a {"role": "tool", "tool_name": ..., "content": ...} message with the result as text.
  4. You call the model again with the longer history. It now writes the answer.

The model has no memory between calls. Every call sends the whole conversation again, and that matters for cost later.

Step 3: the agent loop

An agent is step 2 in a loop. The model may need several tools, one after another, before it can answer. Save this as agent.py:

# agent.py: an AI agent in plain Python. Talks to a local Ollama server; no pip install.
import json
import sys
import urllib.request

from tools import SCHEMAS, TOOLS

MODEL = "qwen2.5:3b"
SYSTEM = ("You are a careful assistant. Use the tools for every calculation, unit conversion "
          "and date question. Never guess a number. When you have the answer, reply briefly.")


def ollama_chat(messages, tools):
    """Send the conversation and tool list to Ollama's /api/chat; return the reply message."""
    body = {"model": MODEL, "messages": messages, "tools": tools, "stream": False,
            "options": {"temperature": 0, "seed": 42}}
    request = urllib.request.Request("http://localhost:11434/api/chat",
                                     data=json.dumps(body).encode(),
                                     headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(request, timeout=600) as response:
        return json.load(response)["message"]


def run_tool(call):
    """Run one tool call. Every failure becomes an error message the model can read."""
    name = call["function"]["name"]
    args = call["function"].get("arguments") or {}
    if name not in TOOLS:
        return f"error: unknown tool {name!r}; available tools: {', '.join(TOOLS)}"
    if isinstance(args, str):  # some APIs send the arguments as a JSON string
        try:
            args = json.loads(args)
        except json.JSONDecodeError:
            return f"error: arguments are not valid JSON: {args!r}"
    try:
        return json.dumps(TOOLS[name](**args))
    except TypeError as e:  # wrong or missing argument names
        return f"error: bad arguments for {name}: {e}"
    except Exception as e:  # the tool itself failed: bad unit, divide by zero, ...
        return f"error: {type(e).__name__}: {e}"


def run_agent(question, chat=ollama_chat, max_steps=6):
    """The agent loop: ask the model, run the tools it asks for, repeat until it answers."""
    messages = [{"role": "system", "content": SYSTEM},
                {"role": "user", "content": question}]
    for step in range(1, max_steps + 1):
        reply = chat(messages, SCHEMAS)
        messages.append(reply)
        calls = reply.get("tool_calls") or []
        if not calls:  # no tool requested, so this is the final answer
            return reply.get("content", "")
        for call in calls:
            result = run_tool(call)
            fn = call["function"]
            print(f"step {step}: {fn['name']}({json.dumps(fn.get('arguments'))}) -> {result}")
            messages.append({"role": "tool", "tool_name": fn["name"], "content": result})
    return f"stopped: no final answer after {max_steps} steps"


if __name__ == "__main__":
    question = " ".join(sys.argv[1:]) or "A cab ride is 42 km each way. How many miles is the round trip?"
    print("answer:", run_agent(question))
step 1: convert_units({"value": 42, "from_unit": "km", "to_unit": "mi"}) -> 26.0976
answer: The round trip that is 84 km (42 km each way) is approximately 26.0976 miles.

Again this is real qwen2.5:3b output. Look closely, because the answer is wrong. A round trip is 84 km, which is about 52.2 miles. The model even wrote "84 km" in its answer. But it asked the tool to convert 42 km, got 26.0976, and called that the round trip.

Nothing in the loop failed. The tool call was valid and the tool returned an exact number. The mistake was in the model's plan: it never asked for 42 × 2 first. This is the most important lesson about agents. Tools make each step exact, but the model still decides which steps to take. We tried the tip from Ollama's docs and told the model it was in a loop and could call tools several times. The 3B model made the same mistake. Step 4 shows how to test the loop itself, and the limits section comes back to this.

The agent loop messages go to the LLM. If the reply has tool_calls, run_tool runs them and the results are added to messages, then the loop repeats. If there are no tool_calls, the reply is the answer. max_steps stops the loop after a fixed number of rounds. messages the conversation LLM reads, then replies tool_calls? run_tool your code runs it answer send yes append result no tool_calls guard: max_steps stop after 6 rounds
The whole agent: ask the model, run the tools it asks for, repeat until it answers or max_steps runs out.

The loop has five jobs, and each is a few lines:

  • ollama_chat sends one HTTP POST with urllib from the standard library. "stream": False returns the whole reply as one JSON object. Temperature 0 and a fixed seed make runs repeatable. The 600-second timeout is generous because a small model on a CPU can take minutes per call.
  • run_agent keeps the message list. If the reply has no tool_calls, that reply is the answer. Otherwise it runs each call and appends the results.
  • max_steps is the guard. A confused model can keep calling tools forever, and every call costs time (or money on a paid API). After six steps the loop stops and says so.
  • run_tool turns every failure into an error message. An unknown tool name, wrong argument names, broken JSON or a tool that raises an exception all become text like error: bad arguments.... The loop does not crash. The model reads the error and can try again.
  • The print in the loop is your trace. When an agent gives a wrong answer, this log tells you which step went wrong.

Step 4: test the loop without a model

Real models are slow and their replies vary, so you cannot unit test the loop with one. Instead, pass run_agent a fake chat function that returns scripted replies. This is the same trick as mocking a database in a normal test. Save as test_agent.py:

# test_agent.py: test the agent loop with a scripted fake model. No LLM, no network.
from agent import run_agent, run_tool


def call(name, **args):
    """An assistant message that asks for one tool call, in Ollama's format."""
    return {"role": "assistant", "content": "",
            "tool_calls": [{"function": {"name": name, "arguments": args}}]}


def scripted(*replies):
    """A fake chat function: returns the given replies in order and records what it was sent."""
    queue = list(replies)

    def chat(messages, tools):
        chat.sent.append(messages[-1])
        return queue.pop(0)
    chat.sent = []
    return chat


# 1. The model makes two mistakes, recovers, then answers.
fake = scripted(
    call("calc", expression="42 * 2"),                       # tool does not exist
    call("convert_units", value=84, unit="km"),              # wrong argument names
    call("convert_units", value=84, from_unit="km", to_unit="mi"),
    {"role": "assistant", "content": "The round trip is about 52.2 miles."},
)
print("answer:", run_agent("A cab ride is 42 km each way. Round trip in miles?", chat=fake))
assert fake.sent[-1] == {"role": "tool", "tool_name": "convert_units", "content": "52.1952"}

# 2. A model that never stops calling tools is cut off by max_steps.
stuck = scripted(*[call("calculator", expression="1 + 1")] * 10)
print("answer:", run_agent("loop forever", chat=stuck, max_steps=3))
assert len(stuck.sent) == 3
# 3. Arguments sent as a JSON string, the way OpenAI's APIs send them: valid, then cut short.
print(run_tool({"function": {"name": "days_between",
                             "arguments": '{"start": "2026-11-20", "end": "2027-01-26"}'}}))
print(run_tool({"function": {"name": "days_between", "arguments": '{"start": "2026-11-20"'}}))
print("all tests passed")
step 1: calc({"expression": "42 * 2"}) -> error: unknown tool 'calc'; available tools: calculator, convert_units, days_between
step 2: convert_units({"value": 84, "unit": "km"}) -> error: bad arguments for convert_units: convert_units() got an unexpected keyword argument 'unit'
step 3: convert_units({"value": 84, "from_unit": "km", "to_unit": "mi"}) -> 52.1952
answer: The round trip is about 52.2 miles.
step 1: calculator({"expression": "1 + 1"}) -> 2
step 2: calculator({"expression": "1 + 1"}) -> 2
step 3: calculator({"expression": "1 + 1"}) -> 2
answer: stopped: no final answer after 3 steps
{"days": 67, "end_weekday": "Tuesday"}
error: arguments are not valid JSON: '{"start": "2026-11-20"'
all tests passed

This output is exact: no model, no network, the same on every machine. It proves three behaviours:

  • A wrong tool name and wrong argument names come back as readable errors, and the loop carries on to the correct call.
  • A model stuck calling tools is stopped after max_steps calls (3 here).
  • Arguments sent as a JSON string are parsed, and a string cut short becomes an error instead of a crash.

Step 5: harder questions on the real model

Now give the real model questions that need a tool it might misuse. The date question needs days_between with ISO dates (YYYY-MM-DD), but the user writes dates in words:

python3 agent.py "How many days are there from 20 November 2026 to Republic Day, 26 January 2027? What weekday is Republic Day?"
step 1: days_between({"end": "2027-01-26", "start": "2026-11-20"}) -> {"days": 67, "end_weekday": "Tuesday"}
step 1: days_between({"end": "2027-01-26", "start": "2026-11-20"}) -> {"days": 67, "end_weekday": "Tuesday"}
answer: From 20 November 2026 to Republic Day on 26 January 2027, there are 67 days. Republic Day falls on a Tuesday.

This one worked. The model turned "20 November 2026" into 2026-11-20 by itself, and the answer quotes the tool's numbers. It did ask for the same call twice in one reply. That is harmless here, but it shows why tools should be safe to repeat.

The next question asks for a unit the converter does not know:

python3 agent.py "How tall is 5 feet 9 inches in centimetres?"
step 1: convert_units({"from_unit": "feet", "to_unit": "centimetres", "value": 5.875}) -> error: ValueError: cannot convert feet to centimetres; known units: m, km, cm, mi, ft, C, F
step 2: convert_units({"value": 5.875, "from_unit": "feet_inches", "to_unit": "centimetres"}) -> error: ValueError: cannot convert feet_inches to centimetres; known units: m, km, cm, mi, ft, C, F
step 3: convert_units({"from_unit": "inches", "to_unit": "centimetres", "value": 69}) -> error: ValueError: cannot convert inches to centimetres; known units: m, km, cm, mi, ft, C, F
answer: It seems there is a persistent issue with converting the measurement directly. I will perform the calculation manually:

5 feet = 60 inches (since 1 foot = 12 inches)
Total inches = 60 + 9 = 69 inches

To convert inches to centimeters, we use the conversion factor: 1 inch = 2.54 cm.

Therefore, 69 inches * 2.54 cm/inch = 175.26 cm

So, 5 feet 9 inches is approximately 175.26 centimeters.

This run shows three different failures in one answer:

  • It ignored the error message. Each error listed the known units (ft, cm), but the model kept inventing names like feet, feet_inches and centimetres.
  • It got the input wrong. 5 feet 9 inches is 5.75 ft, not 5.875 ft.
  • It broke the rules to finish. The system prompt says "Never guess a number", yet it did the maths in its own reply. This time 69 × 2.54 = 175.26 is correct, but nothing checked it.

The loop did its job: no crash, every error went back to the model, and the run ended. The fixes are on the tool side. Accept common spellings like feet and inch, or list the allowed values in the schema with a JSON Schema enum (a fixed list of allowed values). A bigger model is the other option.

The same loop on OpenAI and Anthropic APIs

Hosted APIs use the same loop with different field names. Only two things change: how you describe a tool and how you send a result back. This script prints both shapes for our days_between tool:

# adapters.py: one tool and one tool result, in the shapes four APIs expect
import json

from tools import SCHEMAS

f = SCHEMAS[2]["function"]  # days_between, as written for Ollama
shapes = {
    "Ollama, OpenAI Chat Completions": SCHEMAS[2],
    "OpenAI Responses": {"type": "function", "name": f["name"],
                         "description": f["description"], "parameters": f["parameters"]},
    "Anthropic Messages": {"name": f["name"], "description": f["description"],
                           "input_schema": f["parameters"]},
}
for api, tool in shapes.items():
    print(f"{api:32} tool keys: {list(tool)}")

result = "67 days, Tuesday"
messages = {
    "Ollama": {"role": "tool", "tool_name": "days_between", "content": result},
    "OpenAI Chat Completions": {"role": "tool", "tool_call_id": "call_1", "content": result},
    "OpenAI Responses": {"type": "function_call_output", "call_id": "call_1", "output": result},
    "Anthropic Messages": {"role": "user", "content": [
        {"type": "tool_result", "tool_use_id": "toolu_1", "content": result}]},
}
for api, message in messages.items():
    print(f"{api}:\n  {json.dumps(message)}")
Ollama, OpenAI Chat Completions  tool keys: ['type', 'function']
OpenAI Responses                 tool keys: ['type', 'name', 'description', 'parameters']
Anthropic Messages               tool keys: ['name', 'description', 'input_schema']
Ollama:
  {"role": "tool", "tool_name": "days_between", "content": "67 days, Tuesday"}
OpenAI Chat Completions:
  {"role": "tool", "tool_call_id": "call_1", "content": "67 days, Tuesday"}
OpenAI Responses:
  {"type": "function_call_output", "call_id": "call_1", "output": "67 days, Tuesday"}
Anthropic Messages:
  {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_1", "content": "67 days, Tuesday"}]}
Ollama /api/chatOpenAI Chat CompletionsOpenAI ResponsesAnthropic Messages
Tool definition{"type": "function", "function": {...}}same as Ollamaflat: type, name, parametersname, description, input_schema
Where calls appearmessage.tool_callsmessage.tool_calls, each with an idoutput items of type function_call with a call_idcontent blocks of type tool_use with an id
ArgumentsJSON objectJSON stringJSON stringJSON object (input)
Result goes back asrole tool + tool_namerole tool + tool_call_idfunction_call_output + call_idtool_result block + tool_use_id, in a user message
Loop ends whenno tool_callsno tool_callsno function_call itemsstop_reason is not tool_use

Sources: OpenAI's function calling guide, Anthropic's tool use overview and handling tool calls.

Three details to copy into your loop when you switch:

  • OpenAI sends arguments as a string. That is why run_tool already calls json.loads when it gets a string.
  • Hosted APIs match results by ID. When the model makes two calls at once, the ID tells it which result belongs to which call. Ollama uses the tool name instead.
  • Anthropic has an error flag. A tool_result block can set is_error: true when the tool failed, which is the same idea as our error: prefix.

Ollama also serves an OpenAI-compatible API at http://localhost:11434/v1/, and its supported features include tools. So you can prototype on your laptop with the OpenAI client and switch to a paid model later by changing the base URL and model name.

What agent frameworks add

You now have the core loop that agent frameworks are built around. So what are LangGraph and the OpenAI Agents SDK for? They add the parts that become painful once an agent runs for real users:

You needIn this postLangGraphOpenAI Agents SDK
The tool loop16 lines in run_agentYou build it as a graph of stepsThe Runner agent loop
Step limitmax_stepsrecursion_limit, raises GraphRecursionErrormax_turns, raises MaxTurnsExceeded
Human approvalneeds_approval (below)Human-in-the-loopHuman in the loop
MemoryThe messages list, lost on exitShort-term and long-term memorySessions
Tracing and debuggingprintLangSmithBuilt-in tracing
Several agentsNoneSubagents through Deep Agents, built on LangGraphHandoffs and agents as tools

LangGraph's README also lists "durable execution": agents that "persist through failures" and resume "from exactly where they left off". It calls itself a "low-level orchestration framework for building, managing, and deploying long-running, stateful agents."

The OpenAI Agents SDK's running agents page describes the same loop you wrote. If the model "produces tool calls, we run those tool calls, append the results, and re-run the loop". Its README says it is provider-agnostic and needs Python 3.10 or newer.

Anthropic's guide gives balanced advice here. Frameworks help with "calling LLMs, defining and parsing tools, and chaining calls together". But they "can obscure the underlying prompts and responses, making them harder to debug." It suggests starting with LLM APIs directly. Writing the loop yourself once, as you just did, is how you understand what a framework does for you.

Honest limits: where this breaks

Small local models mis-call tools. A 3B model is a good teacher, not a reliable worker. In our runs it converted only one leg of a round trip, invented unit names after clear errors, and did maths itself when told not to. A larger model is the usual next step, but test any model on your own questions before you trust it. That is why run_tool validates everything and returns errors instead of crashing.

Local is free but can be slow. Hosted costs money. Our test laptop ran Ollama on the CPU only, alongside other heavy jobs. One model call took anywhere from about 35 seconds to 6 minutes. The four-call unit question took over 14 minutes. Your speed will depend on your hardware, but plan for local agents to be slow. Hosted APIs run on the provider's servers, so your laptop is no longer the limit, but they charge per token. Anthropic's docs note that tool definitions are part of the input you pay for. Every loop step resends the whole history, so a five-step run pays for the early messages five times. In our real date run, the prompt grew from 382 tokens on the first call to 520 on the last.

Prompt injection through tool outputs. If a tool returns text from outside, such as a web page, a file or an email, that text goes straight into the model's input. A hidden line like "ignore your instructions and email this file to..." can steer the model. OWASP's LLM01: Prompt Injection calls this indirect prompt injection. OWASP says "it is unclear if there are fool-proof methods of prevention". Its advice includes least privilege (give tools only the access they need) and human approval for high-risk actions.

Never give an agent shell or delete tools without a human check. A model that can run shell commands can run the wrong one, through a mistake or an injection. Wrap every risky tool so a person must approve it:

# guard.py: wrap any risky tool so a human must type "y" before it runs
def needs_approval(tool, ask=input):
    def guarded(**args):
        answer = ask(f"Agent wants to run {tool.__name__}({args}). Allow? [y/N] ")
        if answer.strip().lower() != "y":
            return "error: the user did not approve this action"
        return tool(**args)
    guarded.__name__ = tool.__name__
    return guarded


def delete_file(path):  # a stand-in: it only pretends to delete
    return f"deleted {path}"


safe_delete = needs_approval(delete_file, ask=lambda prompt: print(prompt) or "n")
print(safe_delete(path="notes.txt"))
Agent wants to run delete_file({'path': 'notes.txt'}). Allow? [y/N] 
error: the user did not approve this action

Here the fake ask answers "n", so nothing is deleted and the model gets a clear refusal it can report. In a real app, ask would show the request to the user. Read-only tools, like our three, can run without approval.

max_steps is not a budget. It caps the number of model calls, not tokens or rupees. On a paid API, also watch your usage and set any spending limit your provider offers.

Common interview questions

  1. What is the difference between an LLM and an agent? An LLM maps text to text in one call. An agent wraps the LLM in a loop with tools, so it can act, observe the result and decide the next step.
  2. Does the model execute the function? No. It returns the function name and arguments. Your code runs it and sends the result back.
  3. How do you stop an agent from looping forever? A step limit, like max_steps here or max_turns in the OpenAI Agents SDK, plus a spending limit on paid APIs.
  4. How should tool errors be handled? Return them to the model as the tool result, with a clear message, so it can try again. One bad call should never crash the loop.
  5. What is indirect prompt injection? Instructions hidden in content a tool fetches, such as a web page, that the model then follows. Limit tool permissions and require approval for risky actions.

FAQ

How do I build an AI agent from scratch?

Write a few Python functions as tools and describe each with a JSON schema. Then write a loop: send the conversation and tool list to an LLM, run any tool it asks for, append the result and ask again. Stop when it replies with text. Add a step limit and turn tool errors into messages.

Can I build an AI agent for free?

Yes. Ollama is free and runs open models on your own laptop, and the code in this post uses only Python's standard library. We used qwen2.5:3b, a 1.9 GB download. The cost is speed and accuracy. In our tests the small local model was slow on a CPU, and it made real tool-calling mistakes.

What is tool calling in an LLM?

Tool calling, also called function calling, lets a model reply with a structured request to run a function instead of plain text. The request names the function and gives its arguments as JSON. Your program runs the function and sends back the result, which the model uses in its next reply.

Which Ollama models support tool calling?

Models that list "tools" under Capabilities in ollama show <model>, or carry the tools tag on the Ollama library. The Ollama website has a search filter for tool models. We tested qwen2.5:3b, whose library page lists it. Check each model before you build on it, and pull the latest version.

Do I need LangChain or LangGraph to build an AI agent?

No. The core loop in this post is 16 lines of Python. LangGraph and the OpenAI Agents SDK add memory, tracing, human approval and multi-agent handoffs, and LangGraph adds durable execution. Learn the plain loop first, then pick a framework when you need those features for a real product.

Is it safe to let an AI agent run shell commands?

Not without a human check. The model can choose the wrong command by mistake, and text from a web page or file can trick it through prompt injection. Give agents read-only tools where possible. Wrap anything that deletes, pays, sends or executes so that a person must approve each call.

Keep going

For a wider view of how LLM apps fit together, read how to build your own Jarvis with LLMs. Then read whether AI will replace developers and how it is changing software work.

If you want to build and ship LLM apps, RAG systems and agents with industry mentors guiding your builds, look at Crio's Fellowship Program in AI Engineering.

You've successfully subscribed to Crio Blog
Great! Next, complete checkout to get full access to all premium content.
Welcome back! You've successfully signed in.
Unable to sign you in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Billing info update failed.