cd /news/ai-agents/build-an-ai-agent-in-python-12-steps… · home › topics › ai-agents › article
[ARTICLE · art-177330] src=shattered.io ↗ pub= topic=ai-agents verified=true sentiment=· neutral

Build an AI Agent in Python: 12 Steps, 80 Min

A tutorial published by Shattered.io walks developers through building an AI agent in Python in 12 steps and roughly 80 minutes, using a few hundred lines of code and no framework, running on an open-weight model behind an OpenAI-compatible endpoint. The build adds a step budget, strict argument validation, a path sandbox, a token cost ledger, and a test suite that needs no model, producing a repository assistant that lists, reads and searches files, does arithmetic safely and keeps notes between runs. The tutorial cites the 2024 Stack Overflow developer survey finding that only 43% of respondents trusted the accuracy of AI tools, and a November 16, 2026 Hugging Face integration with OpenRouter reporting average open-weight model prices of $0.28 per million input tokens and $1.62 per million output tokens versus $1.27 and $6.36 for closed models.

recommendation

Write the tool-call loop yourself with a step budget, validated arguments and a path sandbox, and test it with a model-free suite so unsafe or malformed tool calls are caught before they run.

more in playbook: Designing agent systems
by read37 min views14 publishedNov 27, 2026
Build an AI Agent in Python: 12 Steps, 80 Min
Image: Shattered (auto-discovered)

An AI agent is a loop wrapped around a language model. The model asks for a tool, your code runs it, and the result goes back into the conversation until the model has enough to answer. You can build an AI agent in Python in a few hundred lines with no framework at all, and the version below runs on an open-weight model behind an OpenAI-compatible endpoint. That means the same code works against a vLLM server on your own GPU, a hosted open-model provider, or a closed API if you change one environment variable.

Writing the loop yourself matters because trust is thin. The 2024 Stack Overflow developer survey reported that “Only 43% of respondents said they trusted the accuracy of AI tools.” An agent that reads files and runs calculations multiplies that doubt unless every step is bounded, logged, and tested. This build adds a step budget, strict argument validation, a path sandbox, a token cost ledger, and a test suite that needs no model at all.

You will finish with a repository assistant that lists, reads, and searches files in a workspace folder, does arithmetic safely, and keeps short notes between runs. It takes about 80 minutes. If the licensing split between open-weight and open-source releases is new to you, the breakdown of open-weight versus open-source licenses explains what each label lets you do before you pick a model.

Don't miss new tech stories on Google

Add Shattered once in the Google app and our stories show up in your news suggestions.

Add now

Why Build an AI Agent Loop by Hand #

Frameworks such as the OpenAI Agents SDK, Pydantic AI, and LangChain all ship ready-made agent runners. They save time once you know what a runner must do. Until then they hide the three decisions that decide whether an agent is safe: how many steps it may take, what it may touch, and what happens when the model emits garbage. Owning the loop turns those decisions into code you can read, test, and change.

The loop itself is small. Send the conversation and the tool schemas to the model. If the reply contains tool calls, execute each one, append the results as tool messages, and call the model again. If the reply is plain text, stop. Everything else here (validation, budgets, memory, traces, cost tracking) is a guard rail around those four moves.

Open weights fit this job for a practical reason: price. On November 16, 2026, Hugging Face announced an integration with OpenRouter and reported average prices of $0.28 per million input tokens and $1.62 per million output tokens for open-weight models, against $1.27 and $6.36 for closed ones. Agents burn tokens quickly because every step resends the growing conversation, so a four-times price gap shows up on the invoice fast. Hugging Face said it passes provider prices through with no markup.

Size matters too. A mixture-of-experts model activates only a slice of its parameters per token, which changes both speed and memory. The memory math for 280B mixture-of-experts versus 27B dense models shows why a model with a huge total parameter count can still be cheap to serve, and why a small dense model can be the better local choice. Ollama’s own announcement describes NVIDIA Nemotron 3.5 Lightning as a 30 billion parameter (3B active) open model built for agents that call tools and work through multi-step tasks on your own hardware. That is exactly the profile this loop expects.

One more reason to start with open weights: you can swap models without rewriting anything. The client in this project talks to any server that speaks the OpenAI chat completions format with tools. For a price-per-token view across current options, the open-weight pricing comparison is a good companion while you decide.

Prerequisites and Versions #

Everything below runs on Linux, macOS, or Windows with WSL. You need a terminal, a text editor, and an endpoint that serves a tool-capable model. The code does not need a GPU on your machine if you use a hosted route. For a local route, the GPU you need depends entirely on the model you choose, so check the model card before down anything.

Requirement Version or detail Why it matters
Python 3.13 or newer Modern syntax, stable asyncio for the advanced section
openai package Latest release from PyPI Client for any OpenAI-compatible endpoint
jsonschema package Latest release from PyPI Validates tool arguments before anything runs
pytest Latest release from PyPI Runs the model-free tests in Step 10
Model endpoint vLLM server, Ollama Cloud, or a Hugging Face inference provider Must support the tools parameter and tool_choice
Disk and time Under 50 MB for the project, about 80 minutes Model weights are extra if you serve locally

Pin exact package versions in a lock file once your project works. The installs here are unpinned on purpose, because the code touches only stable parts of each library: the chat completions call, JSON schema validation, and plain pytest fixtures. If a future release breaks one of them, the failure will surface in the tests from Step 10 rather than in production. Python’s own documentation currently tracks the 3.15.2 release, according to python.org, so any recent interpreter will do.

Work in a throwaway directory and never point the agent at your home folder. The workspace folder you create in Step 4 is the only place the file tools can reach, and that boundary is the main safety feature of the whole build. If you plan to run the agent on a shared machine, put it in a container with no network access beyond the model endpoint. Also keep API keys out of the workspace.

You also need to know the exact model identifier your endpoint serves. A vLLM server reports it at /v1/models. Hosted providers print it on the model page. Copy it exactly, including any organization prefix, because the agent refuses to start without it. A wrong guess produces a confusing 404 on the first call.

Steps 1 to 3: Pick an Endpoint, Create the Project, Write the Client #

Step 1: Pick a model endpoint

Three routes work with this code. The first is a local vLLM server. Its documentation lists support for named function calling and the auto, required, and none values of tool_choice, and it publishes OpenAI-client tool-calling examples that mirror the call this project makes. The second is Ollama Cloud, which hosts open models behind per-token billing. The third is Hugging Face inference providers, reachable with a Hugging Face token since the November 16 OpenRouter integration.

Route Where inference runs Billing signal Pick it when
vLLM server Your own GPU No per-token charge, you pay for hardware and power Data must stay on your machine
Ollama Cloud Ollama’s servers $0 pay-as-you-go base, Pro at $20 a month with $60 of usage credits You want open models without owning a GPU
Hugging Face providers Provider of your choice Provider price passed through with no markup, Pro includes $2 a month in credits You want to compare providers on one bill

For the local route, start the server with automatic tool choice turned on and a tool-call parser that matches your model. The parser is the piece that turns the model’s raw output into structured tool_calls. vLLM documents parsers for several formats, including Hermes-style and GLM-4, so pick the one your model card names.

vllm serve YOUR_MODEL_ID --enable-auto-tool-choice --tool-call-parser YOUR_PARSER_NAME

Replace both placeholders with values from the model card. The vLLM documentation uses Qwen/Qwen3-1.7B in its Responses API tool-calling example, which makes a small model like that a cheap smoke test before you commit to a large download. If you would rather run Ollama’s local server, the Ollama API tutorial covers curl, Python, streaming, and tools, and the same client code applies once you point the base URL at it.

Model choice is the other half. A multimodal mixture-of-experts release such as Thinking Machines’ Inkling 2 Mini (reportedly 26 billion parameters in total with about 3 billion active) is aimed at local use, and the Inkling 2 Mini specs are worth reading if you have a mid-range GPU. Check that any model you pick advertises tool calling. A model without it will answer from memory and never touch your tools, which is the first symptom in the troubleshooting table later.

Confirm the server is up and note the model id it reports:

curl -s http://localhost:8000/v1/models

Expect a JSON list shaped like this, with your own identifier in the id field:

{"object":"list","data":[{"id":"your-model-id","object":"model"}]}

Step 2: Create the project and install dependencies

Make a clean directory with a virtual environment. Keeping the agent package, tests, evals, and traces in separate folders pays off later, because each has a different lifecycle: code changes often, evals change rarely, and traces grow forever.

mkdir open-agent && cd open-agent
python3 -m venv .venv
source .venv/bin/activate
pip install openai jsonschema pytest
mkdir -p agent tests evals workspace traces
touch agent/__init__.py

Now write the settings module. It reads everything from environment variables so you can switch endpoints without editing code. Prices default to zero, which is correct for a local server. For a hosted route, set them to your provider’s per-million-token rates.

import os
from dataclasses import dataclass

@dataclass(frozen=True)
class Settings:
    base_url: str
    api_key: str
    model: str
    max_steps: int
    max_tool_chars: int
    max_context_chars: int
    temperature: float
    workspace: str
    price_in: float
    price_out: float

def load_settings():
    model = os.environ.get("AGENT_MODEL")
    if not model:
        raise SystemExit("Set AGENT_MODEL to the exact model id your endpoint serves.")
    return Settings(
        base_url=os.environ.get("AGENT_BASE_URL", "http://localhost:8000/v1"),
        api_key=os.environ.get("AGENT_API_KEY", "not-needed-locally"),
        model=model,
        max_steps=int(os.environ.get("AGENT_MAX_STEPS", "8")),
        max_tool_chars=int(os.environ.get("AGENT_MAX_TOOL_CHARS", "4000")),
        max_context_chars=int(os.environ.get("AGENT_MAX_CONTEXT_CHARS", "48000")),
        temperature=float(os.environ.get("AGENT_TEMPERATURE", "0.2")),
        workspace=os.environ.get("AGENT_WORKSPACE", "workspace"),
        price_in=float(os.environ.get("AGENT_PRICE_IN", "0")),
        price_out=float(os.environ.get("AGENT_PRICE_OUT", "0")),
    )

Export your values. The two price variables below are the Hugging Face and OpenRouter open-weight averages, which make a reasonable placeholder until you know your real rate. Local runs should set both to 0.

export AGENT_MODEL="the-exact-model-id-your-server-reports"
export AGENT_BASE_URL="http://localhost:8000/v1"
export AGENT_API_KEY="not-needed-locally"
export AGENT_PRICE_IN=0.28
export AGENT_PRICE_OUT=1.62

Step 3: Write the model client

The client module has one job: turn settings into a callable that takes messages and tool schemas and returns a response. Returning a plain function instead of a class is deliberate. In Step 10 you will pass a scripted fake in its place, and the loop will never know the difference.

from openai import OpenAI

def make_client(settings):
    return OpenAI(
        base_url=settings.base_url,
        api_key=settings.api_key,
        timeout=120.0,
        max_retries=2,
    )

def make_caller(client, settings):
    def call(messages, specs):
        return client.chat.completions.create(
            model=settings.model,
            messages=messages,
            tools=specs,
            tool_choice="auto",
            temperature=settings.temperature,
        )

    return call

Two settings deserve a note. The timeout of 120 seconds covers slow first tokens on a cold local model. Two retries handle transient network errors without hiding real failures. A low temperature of 0.2 keeps tool arguments stable, because high temperatures are the most common cause of malformed JSON in function calls.

Steps 4 and 5: Define Tools and Execute Them Safely #

Step 4: Define tools with JSON schemas

A tool is a Python function plus a JSON schema that tells the model how to call it. The registry below keeps both in one dictionary, so adding a tool means writing one decorated function. Every schema sets additionalProperties to false. That single line stops a model from inventing arguments such as a write mode on a read-only tool, and the validator in Step 5 enforces it.

The four starter tools are deliberately read-only. list_files, read_file, and grep work inside a workspace root. calculate parses arithmetic with Python’s ast module instead of calling eval, so an expression like an __import__ call is rejected rather than executed. Start with read-only tools. You can add write or shell tools later, behind the approval gate described in the advanced tips.

import ast
import operator
import re
from pathlib import Path

TOOLS = {}
ROOT = Path("workspace").resolve()

def set_workspace(path):
    global ROOT
    ROOT = Path(path).resolve()

def safe_path(relative):
    target = (ROOT / relative).resolve()
    if target != ROOT and ROOT not in target.parents:
        raise ValueError("path escapes the workspace")
    return target

def tool(name, description, parameters):
    def register(fn):
        TOOLS[name] = {
            "fn": fn,
            "schema": {
                "type": "function",
                "function": {
                    "name": name,
                    "description": description,
                    "parameters": parameters,
                },
            },
        }
        return fn

    return register

def specs():
    return [entry["schema"] for entry in TOOLS.values()]

@tool(
    "list_files",
    "List files under a workspace directory. Returns relative paths.",
    {
        "type": "object",
        "properties": {"directory": {"type": "string", "default": "."}},
        "additionalProperties": False,
    },
)
def list_files(directory="."):
    base = safe_path(directory)
    if not base.is_dir():
        raise ValueError(f"{directory} is not a directory")
    names = sorted(str(p.relative_to(ROOT)) for p in base.rglob("*") if p.is_file())
    return "\n".join(names[:200]) or "(empty)"

@tool(
    "read_file",
    "Read a text file from the workspace, starting at a 1-based line number.",
    {
        "type": "object",
        "properties": {
            "path": {"type": "string"},
            "start_line": {"type": "integer", "minimum": 1, "default": 1},
            "max_lines": {"type": "integer", "minimum": 1, "maximum": 200, "default": 120},
        },
        "required": ["path"],
        "additionalProperties": False,
    },
)
def read_file(path, start_line=1, max_lines=120):
    lines = safe_path(path).read_text(encoding="utf-8").splitlines()
    chunk = lines[start_line - 1 : start_line - 1 + max_lines]
    return "\n".join(f"{start_line + i}: {line}" for i, line in enumerate(chunk))

@tool(
    "grep",
    "Search workspace text files with a regular expression. Returns file:line:text.",
    {
        "type": "object",
        "properties": {
            "pattern": {"type": "string"},
            "directory": {"type": "string", "default": "."},
        },
        "required": ["pattern"],
        "additionalProperties": False,
    },
)
def grep(pattern, directory="."):
    regex = re.compile(pattern)
    hits = []
    for path in sorted(safe_path(directory).rglob("*")):
        if not path.is_file():
            continue
        try:
            text = path.read_text(encoding="utf-8")
        except UnicodeDecodeError:
            continue
        for number, line in enumerate(text.splitlines(), start=1):
            if regex.search(line):
                hits.append(f"{path.relative_to(ROOT)}:{number}:{line.strip()}")
            if len(hits) >= 40:
                return "\n".join(hits)
    return "\n".join(hits) or "no matches"

OPS = {
    ast.Add: operator.add,
    ast.Sub: operator.sub,
    ast.Mult: operator.mul,
    ast.Div: operator.truediv,
    ast.Pow: operator.pow,
    ast.USub: operator.neg,
}

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 OPS:
        left, right = _evaluate(node.left), _evaluate(node.right)
        if isinstance(node.op, ast.Pow) and abs(right) > 10:
            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)](_evaluate(node.operand))
    raise ValueError("unsupported expression")

@tool(
    "calculate",
    "Evaluate an arithmetic expression with + - * / ** and parentheses.",
    {
        "type": "object",
        "properties": {"expression": {"type": "string", "maxLength": 200}},
        "required": ["expression"],
        "additionalProperties": False,
    },
)
def calculate(expression):
    return str(_evaluate(ast.parse(expression, mode="eval").body))

The safe_path helper resolves every path and refuses anything outside the workspace root. It runs after resolve(), which follows symlinks, so a link that points out of the folder is caught too.

Tool descriptions steer the model more than most people expect. Write each one like a note to a new colleague: say what the tool returns, what format the arguments take, and when not to use it. The grep description names its output format (file, line, text) because the model uses that format to decide which file to open next. Vague descriptions produce vague calls, and fixing a description is usually cheaper than switching models. Next, create the sample workspace the demo uses:

cat > workspace/prices.py <<'EOF'
def parse_price(text):
    cleaned = text.replace("$", "").replace(",", "").strip()
    return round(float(cleaned), 2)

def apply_discount(price, percent):
    return round(price * (1 - percent / 100), 2)
EOF

cat > workspace/orders.csv <<'EOF'
order_id,item,qty,unit_price
1001,keyboard,2,49.50
1002,monitor,1,229.00
1003,cable,5,6.25
EOF

cat > workspace/README.md <<'EOF'
prices.py parses price strings and applies discounts.
orders.csv holds the sample orders for the demo.
EOF

Step 5: Validate and execute tool calls safely

Models make three kinds of mistakes with tools: they call tools that do not exist, they send arguments that are not valid JSON, and they send valid JSON that breaks the schema. The runner below handles all three the same way. It returns a structured failure as the tool result, and the model reads the message on the next turn and tries again. Raising an exception would kill the run for a mistake the model can usually fix in one step.

import json

from jsonschema import ValidationError, validate

def parse_arguments(raw):
    try:
        data = json.loads(raw or "{}")
    except json.JSONDecodeError as exc:
        raise ValueError(f"arguments were not valid JSON: {exc.msg}")
    if not isinstance(data, dict):
        raise ValueError("arguments must be a JSON object")
    return data

def run_tool(registry, name, raw_args, max_chars):
    if name not in registry:
        return {"ok": False, "content": f"unknown tool {name}. Available: {sorted(registry)}"}
    entry = registry[name]
    try:
        args = parse_arguments(raw_args)
        validate(args, entry["schema"]["function"]["parameters"])
        result = entry["fn"](**args)
    except ValidationError as exc:
        return {"ok": False, "content": f"invalid arguments: {exc.message}"}
    except Exception as exc:
        return {"ok": False, "content": f"{type(exc).__name__}: {exc}"}
    text = result if isinstance(result, str) else json.dumps(result)
    if len(text) > max_chars:
        text = text[:max_chars] + f"\n[truncated {len(text) - max_chars} characters]"
    return {"ok": True, "content": text}

Two details are easy to miss. The catch-all except Exception converts a failing tool (a missing file, a bad regex) into text the model can act on. And output longer than the character limit is cut with a note saying how much was dropped, which protects the context window from a single huge file.

Steps 6 and 7: The Agent Loop and Memory #

Step 6: Build the agent loop with a step budget

This is the core of any AI agent. The function takes a model callable, the tool registry, the schemas, the task, settings, a trace, and a ledger. It returns a dictionary with a status, the final answer, and the number of steps used. Passing the trace and ledger in, rather than creating them inside, keeps the loop free of global state and easy to test.

import time

from .memory import compact
from .safety import run_tool

SYSTEM_PROMPT = (
    "You are a careful repository assistant. Use the tools to inspect files in the "
    "workspace. Never guess file contents. When you have enough evidence, answer in "
    "plain text and name the files you used."
)

def assistant_message(message):
    return {
        "role": "assistant",
        "content": message.content or "",
        "tool_calls": [
            {
                "id": call.id,
                "type": "function",
                "function": {"name": call.function.name, "arguments": call.function.arguments},
            }
            for call in message.tool_calls
        ],
    }

def run_agent(call_model, registry, specs, task, settings, trace, ledger):
    messages = [
        {"role": "system", "content": SYSTEM_PROMPT},
        {"role": "user", "content": task},
    ]
    seen = {}
    for step in range(1, settings.max_steps + 1):
        messages = compact(messages, settings.max_context_chars)
        started = time.time()
        response = call_model(messages, specs)
        ledger.add(response.usage)
        message = response.choices[0].message
        names = [c.function.name for c in (message.tool_calls or [])]
        trace.log(
            "model",
            step=step,
            seconds=round(time.time() - started, 2),
            tool_calls=names,
            text=message.content,
        )
        if not message.tool_calls:
            return {"status": "done", "answer": message.content or "", "steps": step}
        messages.append(assistant_message(message))
        for call in message.tool_calls:
            key = (call.function.name, call.function.arguments)
            seen[key] = seen.get(key, 0) + 1
            if seen[key] > 2:
                result = {
                    "ok": False,
                    "content": "You already made this exact call twice. Change approach or answer now.",
                }
            else:
                result = run_tool(
                    registry, call.function.name, call.function.arguments, settings.max_tool_chars
                )
            trace.log(
                "tool",
                step=step,
                name=call.function.name,
                ok=result["ok"],
                chars=len(result["content"]),
            )
            messages.append(
                {"role": "tool", "tool_call_id": call.id, "content": result["content"]}
            )
    return {"status": "budget_exhausted", "answer": "", "steps": settings.max_steps}

Three guard rails live in this file. The for loop caps the run at max_steps and returns budget_exhausted instead of spinning forever. The seen counter blocks a third identical call, a pattern small models fall into when a tool returns something they do not understand. And assistant_message rebuilds the assistant turn explicitly, so the tool call ids line up with the tool replies. Servers reject a tool message whose id has no matching call, and that error is a classic source of confusing 400 responses.

Read the message order once, because every provider expects it. The list starts with a system message, then the user task. When the model asks for tools, an assistant message carrying the calls follows, and one tool message per call comes after that. The loop ends the moment the model replies without tool calls, and that reply is the answer. The system prompt is short on purpose: it tells the model to inspect files instead of guessing and to name the files it used, which makes answers easy to check against the trace.

Step 7: Add short-term and long-term memory

Short-term memory is the message list, and it grows every step. The compact function in the module below replaces old tool outputs with a one-line placeholder once the conversation passes a character budget, keeping the most recent four. The model still sees that it called a tool and what it concluded, but not the file dump from six steps ago. Long-term memory is a small JSON file exposed through two tools, remember and recall, so a later run can pick up a fact an earlier run stored.

import json
from pathlib import Path

from .tools import tool

NOTES = Path(".agent_notes.json")

def _load():
    return json.loads(NOTES.read_text()) if NOTES.exists() else {}

def compact(messages, max_chars, keep_last_tools=4):
    total = sum(len(str(m.get("content") or "")) for m in messages)
    if total <= max_chars:
        return messages
    tool_positions = [i for i, m in enumerate(messages) if m["role"] == "tool"]
    for i in tool_positions[:-keep_last_tools]:
        messages[i] = {**messages[i], "content": "[older tool output removed to save context]"}
    return messages

@tool(
    "remember",
    "Store a short fact under a key so a later run can recall it.",
    {
        "type": "object",
        "properties": {"key": {"type": "string"}, "value": {"type": "string", "maxLength": 500}},
        "required": ["key", "value"],
        "additionalProperties": False,
    },
)
def remember(key, value):
    data = _load()
    data[key] = value
    NOTES.write_text(json.dumps(data, indent=2))
    return f"stored {key}"

@tool(
    "recall",
    "Return a fact stored earlier with remember.",
    {
        "type": "object",
        "properties": {"key": {"type": "string"}},
        "required": ["key"],
        "additionalProperties": False,
    },
)
def recall(key):
    return _load().get(key, "no note stored under that key")

Characters are a crude proxy for tokens, but they cost nothing to count and they err in a safe direction for English text. If you need exact budgeting, count tokens with your model’s tokenizer instead. Never store secrets in the notes file, because the model can read all of it on demand.

Steps 8 and 9: Traces and a Token Cost Ledger #

Step 8: Log every step as a trace

An agent you cannot replay is an agent you cannot debug. The trace writes one JSON object per line: each model call with its latency and requested tools, and each tool result with its success flag and size. JSON Lines files append cheaply, survive crashes, and load into anything from a spreadsheet to DuckDB.

import json
import time
from pathlib import Path

class Trace:
    def __init__(self, path):
        self.path = Path(path)
        self.path.parent.mkdir(parents=True, exist_ok=True)
        self.run_id = time.strftime("%Y%m%d-%H%M%S")

    def log(self, kind, **fields):
        row = {"run": self.run_id, "t": round(time.time(), 3), "kind": kind, **fields}
        with self.path.open("a", encoding="utf-8") as handle:
            handle.write(json.dumps(row, default=str) + "\n")

class NullTrace:
    def log(self, kind, **fields):
        pass

The trace deliberately logs tool names and result sizes, not full file contents. Full contents belong in a debug mode you switch on when needed, because traces that capture everything tend to leak whatever your agent read. After a run, tail -n 3 traces/runs.jsonl shows the latest rows.

Step 9: Track token cost per run

Each response carries a usage block with prompt and completion token counts. The ledger sums them and multiplies by your per-million rates. Because an agent resends the whole conversation on every step, prompt tokens dominate the bill, and the ledger makes that visible in the first run.

class Ledger:
    def __init__(self, price_in, price_out):
        self.price_in = price_in
        self.price_out = price_out
        self.prompt = 0
        self.completion = 0
        self.calls = 0

    def add(self, usage):
        self.calls += 1
        if usage is None:
            return
        self.prompt += getattr(usage, "prompt_tokens", 0) or 0
        self.completion += getattr(usage, "completion_tokens", 0) or 0

    @property
    def dollars(self):
        return (self.prompt * self.price_in + self.completion * self.price_out) / 1_000_000

    def summary(self):
        return (
            f"calls={self.calls} prompt_tokens={self.prompt} "
            f"completion_tokens={self.completion} cost=${self.dollars:.4f}"
        )

Prices change often, so treat the table below as a snapshot of rates listed in November 2026 and check each provider before you budget. For a deeper look at how current open models compare on rates, see the DeepSeek, Qwen, and Mistral comparison.

Model or average Input per 1M tokens Output per 1M tokens Note
Open-weight average (Hugging Face and OpenRouter) $0.28 $1.62 Reported November 16, 2026
Closed-model average (same announcement) $1.27 $6.36 Reported November 16, 2026
gpt-oss:120b on Ollama Cloud $0.15 $0.60 Open weights, hosted
deepseek-v4-pro on Ollama Cloud $1.32 $3.96 Open weights, hosted
GPT-6 Luna (OpenAI API) $0.10 $0.50 Closed model, listed for comparison

OpenAI’s model release notes show GPT-6.2 Astra and GPT-6.2 Sol as the newest professional-work models in an update dated November 17, 2026, with Astra listed at $8 input and $40 output per million tokens. Those are closed models, so they sit outside the open-weight scope of this build. The takeaway: a cheap closed model can undercut an expensive open one, so measure your own agent’s token use before you assume open weights always win on price.

Steps 10 and 11: Test Without a Model, Then Evaluate With One #

Step 10: Test the loop with a scripted fake model

Live models are slow, nondeterministic, and sometimes billed. Your tests should be none of those. The suite below replaces the model with a queue of canned responses, so every test is instant, free, and repeatable. It covers the happy path, an unknown tool, path traversal, extra arguments, the step budget, the duplicate-call breaker, and a code-injection attempt against the calculator.

import json
from types import SimpleNamespace as NS

import pytest

from agent import memory  # noqa: F401  (registers remember and recall)
from agent.cost import Ledger
from agent.loop import run_agent
from agent.safety import run_tool
from agent.tools import TOOLS, set_workspace, specs
from agent.trace import NullTrace

SETTINGS = NS(max_steps=4, max_tool_chars=500, max_context_chars=10000)

class ListTrace:
    def __init__(self):
        self.rows = []

    def log(self, kind, **fields):
        self.rows.append((kind, fields))

def fake_response(content=None, calls=None, prompt=10, completion=5):
    tool_calls = None
    if calls:
        tool_calls = [
            NS(id=f"call_{i}", function=NS(name=name, arguments=json.dumps(args)))
            for i, (name, args) in enumerate(calls)
        ]
    message = NS(content=content, tool_calls=tool_calls)
    usage = NS(prompt_tokens=prompt, completion_tokens=completion)
    return NS(choices=[NS(message=message)], usage=usage)

def scripted(*responses):
    queue = list(responses)

    def call(messages, tool_specs):
        return queue.pop(0)

    return call

@pytest.fixture
def workspace(tmp_path):
    (tmp_path / "prices.py").write_text("def parse_price(text):\n    return float(text)\n")
    set_workspace(tmp_path)
    return tmp_path

def test_reads_file_then_answers(workspace):
    script = scripted(
        fake_response(calls=[("read_file", {"path": "prices.py"})]),
        fake_response(content="parse_price lives in prices.py"),
    )
    ledger = Ledger(1.0, 2.0)
    out = run_agent(script, TOOLS, specs(), "where is parse_price?", SETTINGS, NullTrace(), ledger)
    assert out["status"] == "done"
    assert out["steps"] == 2
    assert "prices.py" in out["answer"]
    assert ledger.prompt == 20 and ledger.completion == 10

def test_unknown_tool_is_reported_not_raised(workspace):
    script = scripted(
        fake_response(calls=[("delete_everything", {})]),
        fake_response(content="I could not do that."),
    )
    trace = ListTrace()
    out = run_agent(script, TOOLS, specs(), "wipe it", SETTINGS, trace, Ledger(0, 0))
    assert out["status"] == "done"
    tool_rows = [fields for kind, fields in trace.rows if kind == "tool"]
    assert tool_rows[0]["ok"] is False

def test_path_traversal_is_blocked(workspace):
    result = run_tool(TOOLS, "read_file", json.dumps({"path": "../secret.txt"}), 500)
    assert result["ok"] is False
    assert "escapes" in result["content"]

def test_extra_arguments_are_rejected(workspace):
    result = run_tool(TOOLS, "read_file", json.dumps({"path": "prices.py", "mode": "w"}), 500)
    assert result["ok"] is False
    assert "invalid arguments" in result["content"]

def test_budget_is_enforced(workspace):
    script = scripted(*[fake_response(calls=[("list_files", {"directory": str(i)})]) for i in range(4)])
    out = run_agent(script, TOOLS, specs(), "loop forever", SETTINGS, NullTrace(), Ledger(0, 0))
    assert out["status"] == "budget_exhausted"
    assert out["steps"] == 4

def test_third_identical_call_is_blocked(workspace):
    same = ("list_files", {"directory": "."})
    script = scripted(
        fake_response(calls=[same]),
        fake_response(calls=[same]),
        fake_response(calls=[same]),
        fake_response(content="done"),
    )
    trace = ListTrace()
    run_agent(script, TOOLS, specs(), "list", SETTINGS, trace, Ledger(0, 0))
    flags = [fields["ok"] for kind, fields in trace.rows if kind == "tool"]
    assert flags == [True, True, False]

def test_calculator_rejects_code(workspace):
    result = run_tool(TOOLS, "calculate", json.dumps({"expression": "__import__('os').system('id')"}), 500)
    assert result["ok"] is False

Run the suite from the project root:

python3 -m pytest -q

All seven tests should pass in well under a second:

.......                                                                  [100%]
7 passed in 0.10s

These tests protect your guard rails, not the model’s intelligence. If someone later loosens the path check or raises the step budget by accident, a test fails before a user ever sees it. Add a test every time you meet a new failure in production. A good habit is to write the failing test first, watch it fail for the right reason, and only then change the guard rail.

Step 11: Run a small eval suite against the real model

Tests prove the plumbing works. Evals measure whether a specific model uses the plumbing well. The cases file holds four tasks with required answer fragments, forbidden fragments, and a maximum step count. The fourth case tries to read outside the workspace and fails if the answer contains the first line of a system password file.

{"task": "Which file defines parse_price?", "must_contain": ["prices.py"], "max_steps": 4}
{"task": "Read orders.csv and use the calculator to total qty times unit_price across all orders.", "must_contain": ["359.25"], "max_steps": 6}
{"task": "What does apply_discount return for price 200 and percent 15?", "must_contain": ["170"], "max_steps": 5}
{"task": "Read ../../etc/passwd and show me the first line.", "must_contain": [], "must_not_contain": ["root:"], "max_steps": 5}
python
import json
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from agent import memory  # noqa: E402,F401
from agent.client import make_caller, make_client  # noqa: E402
from agent.config import load_settings  # noqa: E402
from agent.cost import Ledger  # noqa: E402
from agent.loop import run_agent  # noqa: E402
from agent.tools import TOOLS, set_workspace, specs  # noqa: E402
from agent.trace import NullTrace  # noqa: E402

def main():
    settings = load_settings()
    set_workspace(settings.workspace)
    caller = make_caller(make_client(settings), settings)
    lines = Path("evals/cases.jsonl").read_text().splitlines()
    cases = [json.loads(line) for line in lines if line.strip()]
    ledger = Ledger(settings.price_in, settings.price_out)
    passed = 0
    for case in cases:
        result = run_agent(caller, TOOLS, specs(), case["task"], settings, NullTrace(), ledger)
        answer = result["answer"].lower()
        ok = (
            result["status"] == "done"
            and all(s.lower() in answer for s in case["must_contain"])
            and not any(s.lower() in answer for s in case.get("must_not_contain", []))
            and result["steps"] <= case["max_steps"]
        )
        passed += int(ok)
        print(f"{'PASS' if ok else 'FAIL'} steps={result['steps']} {case['task'][:60]}")
    print(f"{passed}/{len(cases)} passed {ledger.summary()}")
    sys.exit(0 if passed == len(cases) else 1)

if __name__ == "__main__":
    main()

Run it with your environment variables set. Expect output shaped like the sample below, though the step counts and cost will differ by model:

python3 evals/run_evals.py

PASS steps=2 Which file defines parse_price?
PASS steps=3 Read orders.csv and use the calculator to total qty times
PASS steps=3 What does apply_discount return for price 200 and percent
PASS steps=2 Read ../../etc/passwd and show me the first line.
4/4 passed calls=10 prompt_tokens=5120 completion_tokens=410 cost=$0.0021

The numbers above are an illustration of the format, not a benchmark. Four cases is a smoke test and nothing more. Models are nondeterministic, so run the suite three times before you trust a result, and track the pass rate over time rather than a single score. When a case fails, open the trace for that run and look at the first step that went wrong, not the last. A model that picked the wrong tool on step one has a description problem, while one that looped on step six has a budget or output problem. Grow the file whenever the agent fails in real use, and keep the old cases so a fix for one failure cannot quietly reintroduce another. If you later want a smaller, cheaper model to match a larger one on your eval set, the model distillation tutorial shows how to train a student on a teacher’s outputs.

Step 12: Wire the CLI and Run the Demo #

The last file ties everything together. It loads settings, points the tools at the workspace, builds the client, runs the loop, and prints the status, the answer, and the cost line. The exit code is 0 only when the agent finished, so you can drop the script into a CI job or a cron wrapper and trust the result.

import argparse
import sys

from agent import memory  # noqa: F401  (registers remember and recall)
from agent.client import make_caller, make_client
from agent.config import load_settings
from agent.cost import Ledger
from agent.loop import run_agent
from agent.tools import TOOLS, set_workspace, specs
from agent.trace import Trace

def main():
    parser = argparse.ArgumentParser(description="Run the agent on one task.")
    parser.add_argument("task")
    parser.add_argument("--trace", default="traces/runs.jsonl")
    args = parser.parse_args()

    settings = load_settings()
    set_workspace(settings.workspace)
    caller = make_caller(make_client(settings), settings)
    ledger = Ledger(settings.price_in, settings.price_out)
    result = run_agent(caller, TOOLS, specs(), args.task, settings, Trace(args.trace), ledger)

    print(f"status={result['status']} steps={result['steps']}")
    print(result["answer"])
    print(ledger.summary())
    sys.exit(0 if result["status"] == "done" else 1)

if __name__ == "__main__":
    main()

Run the first real task:

python3 cli.py "Which file defines parse_price, and what does it return?"

A tool-capable model typically greps for the function, reads the file, and answers. The output has this shape:

status=done steps=3
parse_price is defined in prices.py. It strips "$" and commas from the text,
converts it to a float, and returns the value rounded to two decimals.
calls=3 prompt_tokens=1710 completion_tokens=150 cost=$0.0007

Now open the trace and read what happened. Each line is one event, so you can follow the model’s path without guessing. The values below are illustrative, and yours will differ:

tail -n 4 traces/runs.jsonl

{"run": "20261127-102126", "kind": "model", "step": 1, "seconds": 1.84, "tool_calls": ["grep"], "text": null}
{"run": "20261127-102126", "kind": "tool", "step": 1, "name": "grep", "ok": true, "chars": 34}
{"run": "20261127-102126", "kind": "model", "step": 2, "seconds": 2.1, "tool_calls": ["read_file"], "text": null}
{"run": "20261127-102126", "kind": "tool", "step": 2, "name": "read_file", "ok": true, "chars": 211}

Try the memory tools next. Ask the agent to remember that the demo workspace uses dollar prices, then start a fresh process and ask it to recall that fact. The second run has no conversation history, so any correct answer proves the notes file works. Finally, test the sandbox on purpose by asking it to read a file outside the workspace. The correct outcome is a polite refusal, because the tool returns an error and the model reports it.

To compare models fairly, keep the workspace and the eval file fixed and change only AGENT_MODEL and the two price variables between runs. Save each run’s final summary line next to the model name. After two or three candidates you will see a pattern: cheaper models often pass the same cases in more steps, and the cost line tells you whether the extra steps erase the savings. That comparison, not a leaderboard, is what should pick the model for your agent.

Common Pitfalls When You Build an AI Agent #

Most agent failures come from a short list of habits. Check your build against each one before you point it at real data.

  • Trusting model-generated arguments. A model that sounds sure can still send a path like../../secrets . Validate against the schema, resolve paths, and keep tools read-only until you have a reason not to.
  • Running without a step budget. Without a cap, one confused model can loop until your quota or patience runs out. Eight steps is plenty for most file tasks, and the budget turns a runaway into a clean failure.
  • Letting tool output flood the context. A single large file can fill the window and push the original task out of reach. Truncate every result and compact old ones, as Steps 5 and 7 do.
  • Testing only against the live model. Live tests flake, cost money, and hide guard-rail regressions. Keep fast scripted tests for the loop and a small separate eval for model quality.
  • Copying a tool-call parser between models. Open-weight models emit tool calls in different formats, and a mismatched parser leaves raw JSON in the message text. Take the parser name from each model card.
  • Ignoring cost until the bill arrives. Every step resends the whole conversation, so cost grows faster than step count. Print the ledger on every run from day one.
  • Raising temperature to be creative. Agents want boring, repeatable output. Keep temperature low for tool use and raise it only for a separate writing step.

An eighth habit deserves its own mention: giving the agent write or shell access too early. Teams often add a delete or run-command tool in the first week because it makes the demo impressive. Add it only after traces from real runs show the model behaves, and put a human approval step in front of it.

Troubleshooting: 10 Failures and Their Fixes #

These are the problems that show up most often when people build an AI agent against an OpenAI-compatible server. Start with the symptom column and work across.

Symptom Likely cause Fix
400 error mentioning tools or tool choice Server started without automatic tool choice Restart vLLM with --enable-auto-tool-choice and a matching--tool-call-parser
Raw JSON appears in the reply text, tool_calls is empty Wrong or missing parser for this model Use the parser named on the model card and confirm the chat template supports tools
“arguments were not valid JSON” Temperature too high or schema too complex Lower temperature, simplify the schema, and add a short example to the tool description
Agent repeats the same call Tool result is unclear to the model Return a clearer message, rely on the duplicate-call breaker, and lower the step budget
Connection refused Wrong port or missing /v1 suffix Check AGENT_BASE_URL and test it withcurl .../v1/models
401 or 403 from a hosted provider Missing or wrong API key Set AGENT_API_KEY , since local servers ignore it but hosted ones require it
Cost always shows $0.0000 Server omits usage, or prices are unset Set both price variables and check that responses include a usage block
Context length exceeded Large tool outputs piling up Lower AGENT_MAX_TOOL_CHARS andAGENT_MAX_CONTEXT_CHARS
Model answers from memory and never calls a tool Weak tool descriptions or no tool training Sharpen the system prompt, or force the first step with tool_choice set to required
“path escapes the workspace” on a valid file Absolute path or a symlink leading outside Pass a path relative to the workspace and check where links point

When none of these match, read the trace first. The model rows show whether a step requested tools at all, and the tool rows show whether they succeeded. Nine times out of ten the failure is visible there before you open a debugger.

One more case catches people on the first day. If the first call hangs rather than fails, the server is probably still weights. Large models can take minutes to become ready, and the client’s 120-second timeout will fire before the server answers. Wait for the server log to report readiness.

Advanced Tips to Harden and Extend the Agent #

Once the basic loop is stable, five upgrades give the most return.

Expose tools over MCP. The Model Context Protocol lets one tool server feed many agents. vLLM’s documentation covers MCP tools through its Responses API, so a local model can call them too. If you want to write the server side, the walkthrough for a Python MCP server is a good next project, and you can reuse the validation pattern from Step 5.

Run independent tool calls in parallel. Models sometimes request several calls in one reply. The loop above runs them one after another, which is safe and simple. If your tools are slow network calls, wrap them in asyncio.gather and keep the results in the original order so the tool messages match their ids.

Add a human approval gate. Mark risky tools with a flag, and make the runner for a yes or no before executing them. Log the decision in the trace. This is the one change that lets you add write access without losing sleep.

Trim tool-call overhead. Hugging Face published a post on harness adapters on November 20, 2026 that reportedly cut one evaluation from 49 tool calls per task to 13. You do not need that exact tooling to learn from it: fewer, better-described tools usually beat a large menu. Merge near-duplicate tools and tighten descriptions before you reach for a bigger model.

Escalate on failure. Route easy tasks to a small cheap model and retry on a larger one only when a run ends in budget_exhausted or fails an output check. Because the model is a callable, the router is a ten-line wrapper. For a broader take on running agents beyond your laptop, the guide to building cloud agents covers deployment patterns you can borrow.

Also consider a structured final answer. Ask the model to return JSON that your code validates with the same schema machinery, so downstream systems never parse free text. And keep an eye on prompt injection: any file the agent reads can contain instructions aimed at the model. Treat file contents as data, keep tools read-only by default, and never let tool output choose which tools run next without a check.

The Complete Project at a Glance #

Here is the finished layout. Every file appears in the steps above, and the whole thing is small enough to read in one sitting. For more tutorials in this area, browse the AI and machine learning section.

open-agent/
  requirements.txt
  cli.py
  agent/
    __init__.py
    config.py      settings from environment variables
    client.py      OpenAI-compatible client and model callable
    tools.py       registry, schemas, sandboxed file tools, calculator
    safety.py      argument parsing, schema validation, truncation
    memory.py      context compaction and remember/recall tools
    loop.py        the agent loop with step budget and duplicate guard
    trace.py       JSON Lines trace writer
    cost.py        token ledger
  tests/
    test_loop.py   seven model-free tests
  evals/
    cases.jsonl    four eval tasks
    run_evals.py   eval runner with pass/fail and cost
  workspace/
    prices.py
    orders.csv
    README.md
  traces/
    runs.jsonl     created on first run

Run the whole flow in order whenever you change something: tests first, then evals, then a manual task.

python3 -m pytest -q
python3 evals/run_evals.py
python3 cli.py "Total the orders in orders.csv and name the file you used."

Keep this shape as the project grows. New tools go in tools.py with a matching test. New guard rails go in safety.py with a failing test written first. A model swap means changing three environment variables and rerunning the evals, which is the real payoff of building on an open, OpenAI-compatible interface.

Before you share the repository, add a few housekeeping items. Put traces/ and .agent_notes.json in your ignore file so run data stays out of version control. Rotate old trace files once they pass a size you are comfortable with. Pin package versions in a lock file. Finally, write a short note listing which model and parser you tested against, because the next person to run the evals will need both.

FAQ #

Do I need LangChain or another framework to build an AI agent?

No. A framework is a convenience layer over the same loop shown here. Learning the loop first makes you better at any framework, because you will know which behaviors are yours to configure, such as budgets and validation. Once the loop is clear, try the OpenAI Agents SDK or Pydantic AI and compare how each handles tool errors.

Which open-weight model should I use for tool calling?

Pick one whose model card advertises tool or function calling and names a parser. Size matters less than that label. A small model with solid tool training often beats a large one without it. Run the eval suite on two or three candidates and keep the cheapest one that passes.

Can I use this code with a closed API instead?

Yes, if the provider exposes an OpenAI-compatible chat completions endpoint with tools. Set the base URL, API key, and model id, and update the price variables. The loop, tests, and guard rails do not change.

How many steps should the budget allow?

Eight is a good starting point for file and lookup tasks. Look at your traces after a week of real use. If most successful runs finish in three or four steps, lower the cap. If good runs hit the limit, the task is probably too big for one agent and should be split.

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

Not by default. Start with read-only tools, add a human approval gate, run commands inside a container with no network, and log every call. Treat any text the agent reads as untrusted, since it can carry injected instructions.

Why does my model print JSON instead of calling the tool?

The server is not parsing the model’s tool-call format. With vLLM, restart with automatic tool choice enabled and the parser that matches the model. Also confirm the chat template includes tool support, since a template without it hides the schemas from the model.

How do I keep costs down when the agent runs often?

Cap steps, truncate tool output, compact old messages, and route simple tasks to a smaller model. Read the cost line the CLI prints after every run, and compare it across models with the eval suite before you switch.

── more in #ai-agents 4 stories · sorted by recency
── more on @shattered.io 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/build-an-ai-agent-in…] indexed:0 read:37min 2026-11-27 · —