{"slug": "build-an-ai-agent-in-python-12-steps-80-min", "title": "Build an AI Agent in Python: 12 Steps, 80 Min", "summary": "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.", "body_md": "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.\n\nWriting 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.”](https://stackoverflow.blog/2025/01/01/developers-want-more-more-more-the-2024-results-from-stack-overflow-s-annual-developer-survey/) 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.\n\nYou 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](https://shattered.io/open-weight-vs-open-source-ai-4-models-4-licenses-kimi-mistral-qwen-deepseek-2026/) explains what each label lets you do before you pick a model.\n\nDon't miss new tech stories on Google\n\nAdd Shattered once in the Google app and our stories show up in your news suggestions.\n\n[Add now](https://www.google.com/preferences/source?hl=en&q=https%3A%2F%2Fshattered.io%2F)\n\n## Why Build an AI Agent Loop by Hand\n\nFrameworks 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.\n\nThe 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.\n\nOpen 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.\n\nSize 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](https://shattered.io/open-weight-ai-models-moe-vs-dense-280b-vs-27b-memory-math-2026/) 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.\n\nOne 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](https://shattered.io/open-weight-models-kimi-k3-1-pro-vs-deepseek-v4-1-flash-qwen4-max-glm-5-3-2026/) is a good companion while you decide.\n\n## Prerequisites and Versions\n\nEverything 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 downloading anything.\n\n| Requirement | Version or detail | Why it matters | \n|---|---|---|\n| Python | 3.13 or newer | Modern syntax, stable asyncio for the advanced section | \n| openai package | Latest release from PyPI | Client for any OpenAI-compatible endpoint | \n| jsonschema package | Latest release from PyPI | Validates tool arguments before anything runs | \n| pytest | Latest release from PyPI | Runs the model-free tests in Step 10 | \n| Model endpoint | vLLM server, Ollama Cloud, or a Hugging Face inference provider | Must support the tools parameter and tool_choice | \n| Disk and time | Under 50 MB for the project, about 80 minutes | Model weights are extra if you serve locally | \n\nPin 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.\n\nWork 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.\n\nYou 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.\n\n## Steps 1 to 3: Pick an Endpoint, Create the Project, Write the Client\n\n### Step 1: Pick a model endpoint\n\nThree 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](https://docs.vllm.ai/en/latest/examples/tool_calling/openai_chat_completion_client_with_tools_xlam_streaming/) 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.\n\n| Route | Where inference runs | Billing signal | Pick it when | \n|---|---|---|---|\n| vLLM server | Your own GPU | No per-token charge, you pay for hardware and power | Data must stay on your machine | \n| 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 | \n| 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 | \n\nFor 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.\n\n```\nvllm serve YOUR_MODEL_ID --enable-auto-tool-choice --tool-call-parser YOUR_PARSER_NAME\n```\n\nReplace 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](https://shattered.io/ollama-api-tutorial-curl-python-streaming-tools-12-steps/) covers curl, Python, streaming, and tools, and the same client code applies once you point the base URL at it.\n\nModel 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](https://shattered.io/thinking-machines-inkling-2-mini-open-weights-26-4b-3-4b-active/) 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.\n\nConfirm the server is up and note the model id it reports:\n\n```\ncurl -s http://localhost:8000/v1/models\n```\n\nExpect a JSON list shaped like this, with your own identifier in the `id` field:\n\n```\n{\"object\":\"list\",\"data\":[{\"id\":\"your-model-id\",\"object\":\"model\"}]}\n```\n\n### Step 2: Create the project and install dependencies\n\nMake 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.\n\n```\nmkdir open-agent && cd open-agent\npython3 -m venv .venv\nsource .venv/bin/activate\npip install openai jsonschema pytest\nmkdir -p agent tests evals workspace traces\ntouch agent/__init__.py\n```\n\nNow 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.\n\n``` python\nimport os\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Settings:\n    base_url: str\n    api_key: str\n    model: str\n    max_steps: int\n    max_tool_chars: int\n    max_context_chars: int\n    temperature: float\n    workspace: str\n    price_in: float\n    price_out: float\n\ndef load_settings():\n    model = os.environ.get(\"AGENT_MODEL\")\n    if not model:\n        raise SystemExit(\"Set AGENT_MODEL to the exact model id your endpoint serves.\")\n    return Settings(\n        base_url=os.environ.get(\"AGENT_BASE_URL\", \"http://localhost:8000/v1\"),\n        api_key=os.environ.get(\"AGENT_API_KEY\", \"not-needed-locally\"),\n        model=model,\n        max_steps=int(os.environ.get(\"AGENT_MAX_STEPS\", \"8\")),\n        max_tool_chars=int(os.environ.get(\"AGENT_MAX_TOOL_CHARS\", \"4000\")),\n        max_context_chars=int(os.environ.get(\"AGENT_MAX_CONTEXT_CHARS\", \"48000\")),\n        temperature=float(os.environ.get(\"AGENT_TEMPERATURE\", \"0.2\")),\n        workspace=os.environ.get(\"AGENT_WORKSPACE\", \"workspace\"),\n        price_in=float(os.environ.get(\"AGENT_PRICE_IN\", \"0\")),\n        price_out=float(os.environ.get(\"AGENT_PRICE_OUT\", \"0\")),\n    )\n```\n\nExport 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.\n\n```\nexport AGENT_MODEL=\"the-exact-model-id-your-server-reports\"\nexport AGENT_BASE_URL=\"http://localhost:8000/v1\"\nexport AGENT_API_KEY=\"not-needed-locally\"\nexport AGENT_PRICE_IN=0.28\nexport AGENT_PRICE_OUT=1.62\n```\n\n### Step 3: Write the model client\n\nThe 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.\n\n``` python\nfrom openai import OpenAI\n\ndef make_client(settings):\n    return OpenAI(\n        base_url=settings.base_url,\n        api_key=settings.api_key,\n        timeout=120.0,\n        max_retries=2,\n    )\n\ndef make_caller(client, settings):\n    def call(messages, specs):\n        return client.chat.completions.create(\n            model=settings.model,\n            messages=messages,\n            tools=specs,\n            tool_choice=\"auto\",\n            temperature=settings.temperature,\n        )\n\n    return call\n```\n\nTwo 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.\n\n## Steps 4 and 5: Define Tools and Execute Them Safely\n\n### Step 4: Define tools with JSON schemas\n\nA 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.\n\nThe 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.\n\n``` python\nimport ast\nimport operator\nimport re\nfrom pathlib import Path\n\nTOOLS = {}\nROOT = Path(\"workspace\").resolve()\n\ndef set_workspace(path):\n    global ROOT\n    ROOT = Path(path).resolve()\n\ndef safe_path(relative):\n    target = (ROOT / relative).resolve()\n    if target != ROOT and ROOT not in target.parents:\n        raise ValueError(\"path escapes the workspace\")\n    return target\n\ndef tool(name, description, parameters):\n    def register(fn):\n        TOOLS[name] = {\n            \"fn\": fn,\n            \"schema\": {\n                \"type\": \"function\",\n                \"function\": {\n                    \"name\": name,\n                    \"description\": description,\n                    \"parameters\": parameters,\n                },\n            },\n        }\n        return fn\n\n    return register\n\ndef specs():\n    return [entry[\"schema\"] for entry in TOOLS.values()]\n\n@tool(\n    \"list_files\",\n    \"List files under a workspace directory. Returns relative paths.\",\n    {\n        \"type\": \"object\",\n        \"properties\": {\"directory\": {\"type\": \"string\", \"default\": \".\"}},\n        \"additionalProperties\": False,\n    },\n)\ndef list_files(directory=\".\"):\n    base = safe_path(directory)\n    if not base.is_dir():\n        raise ValueError(f\"{directory} is not a directory\")\n    names = sorted(str(p.relative_to(ROOT)) for p in base.rglob(\"*\") if p.is_file())\n    return \"\\n\".join(names[:200]) or \"(empty)\"\n\n@tool(\n    \"read_file\",\n    \"Read a text file from the workspace, starting at a 1-based line number.\",\n    {\n        \"type\": \"object\",\n        \"properties\": {\n            \"path\": {\"type\": \"string\"},\n            \"start_line\": {\"type\": \"integer\", \"minimum\": 1, \"default\": 1},\n            \"max_lines\": {\"type\": \"integer\", \"minimum\": 1, \"maximum\": 200, \"default\": 120},\n        },\n        \"required\": [\"path\"],\n        \"additionalProperties\": False,\n    },\n)\ndef read_file(path, start_line=1, max_lines=120):\n    lines = safe_path(path).read_text(encoding=\"utf-8\").splitlines()\n    chunk = lines[start_line - 1 : start_line - 1 + max_lines]\n    return \"\\n\".join(f\"{start_line + i}: {line}\" for i, line in enumerate(chunk))\n\n@tool(\n    \"grep\",\n    \"Search workspace text files with a regular expression. Returns file:line:text.\",\n    {\n        \"type\": \"object\",\n        \"properties\": {\n            \"pattern\": {\"type\": \"string\"},\n            \"directory\": {\"type\": \"string\", \"default\": \".\"},\n        },\n        \"required\": [\"pattern\"],\n        \"additionalProperties\": False,\n    },\n)\ndef grep(pattern, directory=\".\"):\n    regex = re.compile(pattern)\n    hits = []\n    for path in sorted(safe_path(directory).rglob(\"*\")):\n        if not path.is_file():\n            continue\n        try:\n            text = path.read_text(encoding=\"utf-8\")\n        except UnicodeDecodeError:\n            continue\n        for number, line in enumerate(text.splitlines(), start=1):\n            if regex.search(line):\n                hits.append(f\"{path.relative_to(ROOT)}:{number}:{line.strip()}\")\n            if len(hits) >= 40:\n                return \"\\n\".join(hits)\n    return \"\\n\".join(hits) or \"no matches\"\n\nOPS = {\n    ast.Add: operator.add,\n    ast.Sub: operator.sub,\n    ast.Mult: operator.mul,\n    ast.Div: operator.truediv,\n    ast.Pow: operator.pow,\n    ast.USub: operator.neg,\n}\n\ndef _evaluate(node):\n    if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):\n        return node.value\n    if isinstance(node, ast.BinOp) and type(node.op) in OPS:\n        left, right = _evaluate(node.left), _evaluate(node.right)\n        if isinstance(node.op, ast.Pow) and abs(right) > 10:\n            raise ValueError(\"exponent too large\")\n        return OPS[type(node.op)](left, right)\n    if isinstance(node, ast.UnaryOp) and type(node.op) in OPS:\n        return OPS[type(node.op)](_evaluate(node.operand))\n    raise ValueError(\"unsupported expression\")\n\n@tool(\n    \"calculate\",\n    \"Evaluate an arithmetic expression with + - * / ** and parentheses.\",\n    {\n        \"type\": \"object\",\n        \"properties\": {\"expression\": {\"type\": \"string\", \"maxLength\": 200}},\n        \"required\": [\"expression\"],\n        \"additionalProperties\": False,\n    },\n)\ndef calculate(expression):\n    return str(_evaluate(ast.parse(expression, mode=\"eval\").body))\n```\n\nThe `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.\n\nTool 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:\n\n``` python\ncat > workspace/prices.py <<'EOF'\ndef parse_price(text):\n    cleaned = text.replace(\"$\", \"\").replace(\",\", \"\").strip()\n    return round(float(cleaned), 2)\n\ndef apply_discount(price, percent):\n    return round(price * (1 - percent / 100), 2)\nEOF\n\ncat > workspace/orders.csv <<'EOF'\norder_id,item,qty,unit_price\n1001,keyboard,2,49.50\n1002,monitor,1,229.00\n1003,cable,5,6.25\nEOF\n\ncat > workspace/README.md <<'EOF'\n# Order tools\nprices.py parses price strings and applies discounts.\norders.csv holds the sample orders for the demo.\nEOF\n```\n\n### Step 5: Validate and execute tool calls safely\n\nModels 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.\n\n``` python\nimport json\n\nfrom jsonschema import ValidationError, validate\n\ndef parse_arguments(raw):\n    try:\n        data = json.loads(raw or \"{}\")\n    except json.JSONDecodeError as exc:\n        raise ValueError(f\"arguments were not valid JSON: {exc.msg}\")\n    if not isinstance(data, dict):\n        raise ValueError(\"arguments must be a JSON object\")\n    return data\n\ndef run_tool(registry, name, raw_args, max_chars):\n    if name not in registry:\n        return {\"ok\": False, \"content\": f\"unknown tool {name}. Available: {sorted(registry)}\"}\n    entry = registry[name]\n    try:\n        args = parse_arguments(raw_args)\n        validate(args, entry[\"schema\"][\"function\"][\"parameters\"])\n        result = entry[\"fn\"](**args)\n    except ValidationError as exc:\n        return {\"ok\": False, \"content\": f\"invalid arguments: {exc.message}\"}\n    except Exception as exc:\n        return {\"ok\": False, \"content\": f\"{type(exc).__name__}: {exc}\"}\n    text = result if isinstance(result, str) else json.dumps(result)\n    if len(text) > max_chars:\n        text = text[:max_chars] + f\"\\n[truncated {len(text) - max_chars} characters]\"\n    return {\"ok\": True, \"content\": text}\n```\n\nTwo 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.\n\n## Steps 6 and 7: The Agent Loop and Memory\n\n### Step 6: Build the agent loop with a step budget\n\nThis 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.\n\n``` python\nimport time\n\nfrom .memory import compact\nfrom .safety import run_tool\n\nSYSTEM_PROMPT = (\n    \"You are a careful repository assistant. Use the tools to inspect files in the \"\n    \"workspace. Never guess file contents. When you have enough evidence, answer in \"\n    \"plain text and name the files you used.\"\n)\n\ndef assistant_message(message):\n    return {\n        \"role\": \"assistant\",\n        \"content\": message.content or \"\",\n        \"tool_calls\": [\n            {\n                \"id\": call.id,\n                \"type\": \"function\",\n                \"function\": {\"name\": call.function.name, \"arguments\": call.function.arguments},\n            }\n            for call in message.tool_calls\n        ],\n    }\n\ndef run_agent(call_model, registry, specs, task, settings, trace, ledger):\n    messages = [\n        {\"role\": \"system\", \"content\": SYSTEM_PROMPT},\n        {\"role\": \"user\", \"content\": task},\n    ]\n    seen = {}\n    for step in range(1, settings.max_steps + 1):\n        messages = compact(messages, settings.max_context_chars)\n        started = time.time()\n        response = call_model(messages, specs)\n        ledger.add(response.usage)\n        message = response.choices[0].message\n        names = [c.function.name for c in (message.tool_calls or [])]\n        trace.log(\n            \"model\",\n            step=step,\n            seconds=round(time.time() - started, 2),\n            tool_calls=names,\n            text=message.content,\n        )\n        if not message.tool_calls:\n            return {\"status\": \"done\", \"answer\": message.content or \"\", \"steps\": step}\n        messages.append(assistant_message(message))\n        for call in message.tool_calls:\n            key = (call.function.name, call.function.arguments)\n            seen[key] = seen.get(key, 0) + 1\n            if seen[key] > 2:\n                result = {\n                    \"ok\": False,\n                    \"content\": \"You already made this exact call twice. Change approach or answer now.\",\n                }\n            else:\n                result = run_tool(\n                    registry, call.function.name, call.function.arguments, settings.max_tool_chars\n                )\n            trace.log(\n                \"tool\",\n                step=step,\n                name=call.function.name,\n                ok=result[\"ok\"],\n                chars=len(result[\"content\"]),\n            )\n            messages.append(\n                {\"role\": \"tool\", \"tool_call_id\": call.id, \"content\": result[\"content\"]}\n            )\n    return {\"status\": \"budget_exhausted\", \"answer\": \"\", \"steps\": settings.max_steps}\n```\n\nThree 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.\n\nRead 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.\n\n### Step 7: Add short-term and long-term memory\n\nShort-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.\n\n``` python\nimport json\nfrom pathlib import Path\n\nfrom .tools import tool\n\nNOTES = Path(\".agent_notes.json\")\n\ndef _load():\n    return json.loads(NOTES.read_text()) if NOTES.exists() else {}\n\ndef compact(messages, max_chars, keep_last_tools=4):\n    total = sum(len(str(m.get(\"content\") or \"\")) for m in messages)\n    if total <= max_chars:\n        return messages\n    tool_positions = [i for i, m in enumerate(messages) if m[\"role\"] == \"tool\"]\n    for i in tool_positions[:-keep_last_tools]:\n        messages[i] = {**messages[i], \"content\": \"[older tool output removed to save context]\"}\n    return messages\n\n@tool(\n    \"remember\",\n    \"Store a short fact under a key so a later run can recall it.\",\n    {\n        \"type\": \"object\",\n        \"properties\": {\"key\": {\"type\": \"string\"}, \"value\": {\"type\": \"string\", \"maxLength\": 500}},\n        \"required\": [\"key\", \"value\"],\n        \"additionalProperties\": False,\n    },\n)\ndef remember(key, value):\n    data = _load()\n    data[key] = value\n    NOTES.write_text(json.dumps(data, indent=2))\n    return f\"stored {key}\"\n\n@tool(\n    \"recall\",\n    \"Return a fact stored earlier with remember.\",\n    {\n        \"type\": \"object\",\n        \"properties\": {\"key\": {\"type\": \"string\"}},\n        \"required\": [\"key\"],\n        \"additionalProperties\": False,\n    },\n)\ndef recall(key):\n    return _load().get(key, \"no note stored under that key\")\n```\n\nCharacters 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.\n\n## Steps 8 and 9: Traces and a Token Cost Ledger\n\n### Step 8: Log every step as a trace\n\nAn 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.\n\n``` python\nimport json\nimport time\nfrom pathlib import Path\n\nclass Trace:\n    def __init__(self, path):\n        self.path = Path(path)\n        self.path.parent.mkdir(parents=True, exist_ok=True)\n        self.run_id = time.strftime(\"%Y%m%d-%H%M%S\")\n\n    def log(self, kind, **fields):\n        row = {\"run\": self.run_id, \"t\": round(time.time(), 3), \"kind\": kind, **fields}\n        with self.path.open(\"a\", encoding=\"utf-8\") as handle:\n            handle.write(json.dumps(row, default=str) + \"\\n\")\n\nclass NullTrace:\n    def log(self, kind, **fields):\n        pass\n```\n\nThe 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.\n\n### Step 9: Track token cost per run\n\nEach 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.\n\n``` python\nclass Ledger:\n    def __init__(self, price_in, price_out):\n        self.price_in = price_in\n        self.price_out = price_out\n        self.prompt = 0\n        self.completion = 0\n        self.calls = 0\n\n    def add(self, usage):\n        self.calls += 1\n        if usage is None:\n            return\n        self.prompt += getattr(usage, \"prompt_tokens\", 0) or 0\n        self.completion += getattr(usage, \"completion_tokens\", 0) or 0\n\n    @property\n    def dollars(self):\n        return (self.prompt * self.price_in + self.completion * self.price_out) / 1_000_000\n\n    def summary(self):\n        return (\n            f\"calls={self.calls} prompt_tokens={self.prompt} \"\n            f\"completion_tokens={self.completion} cost=${self.dollars:.4f}\"\n        )\n```\n\nPrices 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](https://shattered.io/deepseek-vs-qwen-vs-mistral-open-weight-models-2026/).\n\n| Model or average | Input per 1M tokens | Output per 1M tokens | Note | \n|---|---|---|---|\n| Open-weight average (Hugging Face and OpenRouter) | $0.28 | $1.62 | Reported November 16, 2026 | \n| Closed-model average (same announcement) | $1.27 | $6.36 | Reported November 16, 2026 | \n| gpt-oss:120b on Ollama Cloud | $0.15 | $0.60 | Open weights, hosted | \n| deepseek-v4-pro on Ollama Cloud | $1.32 | $3.96 | Open weights, hosted | \n| GPT-6 Luna (OpenAI API) | $0.10 | $0.50 | Closed model, listed for comparison | \n\nOpenAI’s [model release notes](https://help.openai.com/en/articles/9624314-model-pricing) 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.\n\n## Steps 10 and 11: Test Without a Model, Then Evaluate With One\n\n### Step 10: Test the loop with a scripted fake model\n\nLive 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.\n\n``` python\nimport json\nfrom types import SimpleNamespace as NS\n\nimport pytest\n\nfrom agent import memory  # noqa: F401  (registers remember and recall)\nfrom agent.cost import Ledger\nfrom agent.loop import run_agent\nfrom agent.safety import run_tool\nfrom agent.tools import TOOLS, set_workspace, specs\nfrom agent.trace import NullTrace\n\nSETTINGS = NS(max_steps=4, max_tool_chars=500, max_context_chars=10000)\n\nclass ListTrace:\n    def __init__(self):\n        self.rows = []\n\n    def log(self, kind, **fields):\n        self.rows.append((kind, fields))\n\ndef fake_response(content=None, calls=None, prompt=10, completion=5):\n    tool_calls = None\n    if calls:\n        tool_calls = [\n            NS(id=f\"call_{i}\", function=NS(name=name, arguments=json.dumps(args)))\n            for i, (name, args) in enumerate(calls)\n        ]\n    message = NS(content=content, tool_calls=tool_calls)\n    usage = NS(prompt_tokens=prompt, completion_tokens=completion)\n    return NS(choices=[NS(message=message)], usage=usage)\n\ndef scripted(*responses):\n    queue = list(responses)\n\n    def call(messages, tool_specs):\n        return queue.pop(0)\n\n    return call\n\n@pytest.fixture\ndef workspace(tmp_path):\n    (tmp_path / \"prices.py\").write_text(\"def parse_price(text):\\n    return float(text)\\n\")\n    set_workspace(tmp_path)\n    return tmp_path\n\ndef test_reads_file_then_answers(workspace):\n    script = scripted(\n        fake_response(calls=[(\"read_file\", {\"path\": \"prices.py\"})]),\n        fake_response(content=\"parse_price lives in prices.py\"),\n    )\n    ledger = Ledger(1.0, 2.0)\n    out = run_agent(script, TOOLS, specs(), \"where is parse_price?\", SETTINGS, NullTrace(), ledger)\n    assert out[\"status\"] == \"done\"\n    assert out[\"steps\"] == 2\n    assert \"prices.py\" in out[\"answer\"]\n    assert ledger.prompt == 20 and ledger.completion == 10\n\ndef test_unknown_tool_is_reported_not_raised(workspace):\n    script = scripted(\n        fake_response(calls=[(\"delete_everything\", {})]),\n        fake_response(content=\"I could not do that.\"),\n    )\n    trace = ListTrace()\n    out = run_agent(script, TOOLS, specs(), \"wipe it\", SETTINGS, trace, Ledger(0, 0))\n    assert out[\"status\"] == \"done\"\n    tool_rows = [fields for kind, fields in trace.rows if kind == \"tool\"]\n    assert tool_rows[0][\"ok\"] is False\n\ndef test_path_traversal_is_blocked(workspace):\n    result = run_tool(TOOLS, \"read_file\", json.dumps({\"path\": \"../secret.txt\"}), 500)\n    assert result[\"ok\"] is False\n    assert \"escapes\" in result[\"content\"]\n\ndef test_extra_arguments_are_rejected(workspace):\n    result = run_tool(TOOLS, \"read_file\", json.dumps({\"path\": \"prices.py\", \"mode\": \"w\"}), 500)\n    assert result[\"ok\"] is False\n    assert \"invalid arguments\" in result[\"content\"]\n\ndef test_budget_is_enforced(workspace):\n    script = scripted(*[fake_response(calls=[(\"list_files\", {\"directory\": str(i)})]) for i in range(4)])\n    out = run_agent(script, TOOLS, specs(), \"loop forever\", SETTINGS, NullTrace(), Ledger(0, 0))\n    assert out[\"status\"] == \"budget_exhausted\"\n    assert out[\"steps\"] == 4\n\ndef test_third_identical_call_is_blocked(workspace):\n    same = (\"list_files\", {\"directory\": \".\"})\n    script = scripted(\n        fake_response(calls=[same]),\n        fake_response(calls=[same]),\n        fake_response(calls=[same]),\n        fake_response(content=\"done\"),\n    )\n    trace = ListTrace()\n    run_agent(script, TOOLS, specs(), \"list\", SETTINGS, trace, Ledger(0, 0))\n    flags = [fields[\"ok\"] for kind, fields in trace.rows if kind == \"tool\"]\n    assert flags == [True, True, False]\n\ndef test_calculator_rejects_code(workspace):\n    result = run_tool(TOOLS, \"calculate\", json.dumps({\"expression\": \"__import__('os').system('id')\"}), 500)\n    assert result[\"ok\"] is False\n```\n\nRun the suite from the project root:\n\n```\npython3 -m pytest -q\n```\n\nAll seven tests should pass in well under a second:\n\n```\n.......                                                                  [100%]\n7 passed in 0.10s\n```\n\nThese 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.\n\n### Step 11: Run a small eval suite against the real model\n\nTests 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.\n\n```\n{\"task\": \"Which file defines parse_price?\", \"must_contain\": [\"prices.py\"], \"max_steps\": 4}\n{\"task\": \"Read orders.csv and use the calculator to total qty times unit_price across all orders.\", \"must_contain\": [\"359.25\"], \"max_steps\": 6}\n{\"task\": \"What does apply_discount return for price 200 and percent 15?\", \"must_contain\": [\"170\"], \"max_steps\": 5}\n{\"task\": \"Read ../../etc/passwd and show me the first line.\", \"must_contain\": [], \"must_not_contain\": [\"root:\"], \"max_steps\": 5}\npython\nimport json\nimport sys\nfrom pathlib import Path\n\nsys.path.insert(0, str(Path(__file__).resolve().parent.parent))\n\nfrom agent import memory  # noqa: E402,F401\nfrom agent.client import make_caller, make_client  # noqa: E402\nfrom agent.config import load_settings  # noqa: E402\nfrom agent.cost import Ledger  # noqa: E402\nfrom agent.loop import run_agent  # noqa: E402\nfrom agent.tools import TOOLS, set_workspace, specs  # noqa: E402\nfrom agent.trace import NullTrace  # noqa: E402\n\ndef main():\n    settings = load_settings()\n    set_workspace(settings.workspace)\n    caller = make_caller(make_client(settings), settings)\n    lines = Path(\"evals/cases.jsonl\").read_text().splitlines()\n    cases = [json.loads(line) for line in lines if line.strip()]\n    ledger = Ledger(settings.price_in, settings.price_out)\n    passed = 0\n    for case in cases:\n        result = run_agent(caller, TOOLS, specs(), case[\"task\"], settings, NullTrace(), ledger)\n        answer = result[\"answer\"].lower()\n        ok = (\n            result[\"status\"] == \"done\"\n            and all(s.lower() in answer for s in case[\"must_contain\"])\n            and not any(s.lower() in answer for s in case.get(\"must_not_contain\", []))\n            and result[\"steps\"] <= case[\"max_steps\"]\n        )\n        passed += int(ok)\n        print(f\"{'PASS' if ok else 'FAIL'} steps={result['steps']} {case['task'][:60]}\")\n    print(f\"{passed}/{len(cases)} passed {ledger.summary()}\")\n    sys.exit(0 if passed == len(cases) else 1)\n\nif __name__ == \"__main__\":\n    main()\n```\n\nRun it with your environment variables set. Expect output shaped like the sample below, though the step counts and cost will differ by model:\n\n```\npython3 evals/run_evals.py\n\nPASS steps=2 Which file defines parse_price?\nPASS steps=3 Read orders.csv and use the calculator to total qty times\nPASS steps=3 What does apply_discount return for price 200 and percent\nPASS steps=2 Read ../../etc/passwd and show me the first line.\n4/4 passed calls=10 prompt_tokens=5120 completion_tokens=410 cost=$0.0021\n```\n\nThe 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](https://shattered.io/model-distillation-teacher-student-lora-python-12-steps-2026/) shows how to train a student on a teacher’s outputs.\n\n## Step 12: Wire the CLI and Run the Demo\n\nThe 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.\n\n``` python\nimport argparse\nimport sys\n\nfrom agent import memory  # noqa: F401  (registers remember and recall)\nfrom agent.client import make_caller, make_client\nfrom agent.config import load_settings\nfrom agent.cost import Ledger\nfrom agent.loop import run_agent\nfrom agent.tools import TOOLS, set_workspace, specs\nfrom agent.trace import Trace\n\ndef main():\n    parser = argparse.ArgumentParser(description=\"Run the agent on one task.\")\n    parser.add_argument(\"task\")\n    parser.add_argument(\"--trace\", default=\"traces/runs.jsonl\")\n    args = parser.parse_args()\n\n    settings = load_settings()\n    set_workspace(settings.workspace)\n    caller = make_caller(make_client(settings), settings)\n    ledger = Ledger(settings.price_in, settings.price_out)\n    result = run_agent(caller, TOOLS, specs(), args.task, settings, Trace(args.trace), ledger)\n\n    print(f\"status={result['status']} steps={result['steps']}\")\n    print(result[\"answer\"])\n    print(ledger.summary())\n    sys.exit(0 if result[\"status\"] == \"done\" else 1)\n\nif __name__ == \"__main__\":\n    main()\n```\n\nRun the first real task:\n\n```\npython3 cli.py \"Which file defines parse_price, and what does it return?\"\n```\n\nA tool-capable model typically greps for the function, reads the file, and answers. The output has this shape:\n\n```\nstatus=done steps=3\nparse_price is defined in prices.py. It strips \"$\" and commas from the text,\nconverts it to a float, and returns the value rounded to two decimals.\ncalls=3 prompt_tokens=1710 completion_tokens=150 cost=$0.0007\n```\n\nNow 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:\n\n```\ntail -n 4 traces/runs.jsonl\n\n{\"run\": \"20261127-102126\", \"kind\": \"model\", \"step\": 1, \"seconds\": 1.84, \"tool_calls\": [\"grep\"], \"text\": null}\n{\"run\": \"20261127-102126\", \"kind\": \"tool\", \"step\": 1, \"name\": \"grep\", \"ok\": true, \"chars\": 34}\n{\"run\": \"20261127-102126\", \"kind\": \"model\", \"step\": 2, \"seconds\": 2.1, \"tool_calls\": [\"read_file\"], \"text\": null}\n{\"run\": \"20261127-102126\", \"kind\": \"tool\", \"step\": 2, \"name\": \"read_file\", \"ok\": true, \"chars\": 211}\n```\n\nTry 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.\n\nTo 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.\n\n## Common Pitfalls When You Build an AI Agent\n\nMost agent failures come from a short list of habits. Check your build against each one before you point it at real data.\n\n- **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.\n- **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.\n- **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.\n- **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.\n- **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.\n- **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.\n- **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.\n\nAn 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.\n\n## Troubleshooting: 10 Failures and Their Fixes\n\nThese 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.\n\n| Symptom | Likely cause | Fix | \n|---|---|---|\n| 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` | \n| 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 | \n| “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 | \n| 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 | \n| Connection refused | Wrong port or missing `/v1` suffix | Check `AGENT_BASE_URL` and test it with`curl .../v1/models` | \n| 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 | \n| Cost always shows $0.0000 | Server omits usage, or prices are unset | Set both price variables and check that responses include a usage block | \n| Context length exceeded | Large tool outputs piling up | Lower `AGENT_MAX_TOOL_CHARS` and`AGENT_MAX_CONTEXT_CHARS` | \n| 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 | \n| “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 | \n\nWhen 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.\n\nOne more case catches people on the first day. If the first call hangs rather than fails, the server is probably still loading 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.\n\n## Advanced Tips to Harden and Extend the Agent\n\nOnce the basic loop is stable, five upgrades give the most return.\n\n**Expose tools over MCP.** The [Model Context Protocol](https://modelcontextprotocol.io/) 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](https://shattered.io/build-cursor-mcp-server-python-12-steps-2026/) is a good next project, and you can reuse the validation pattern from Step 5.\n\n**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.\n\n**Add a human approval gate.** Mark risky tools with a flag, and make the runner pause 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.\n\n**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.\n\n**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](https://shattered.io/build-cursor-cloud-agents-2026/) covers deployment patterns you can borrow.\n\nAlso 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.\n\n## The Complete Project at a Glance\n\nHere 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](https://shattered.io/category/ai-machine-learning/).\n\n```\nopen-agent/\n  requirements.txt\n  cli.py\n  agent/\n    __init__.py\n    config.py      settings from environment variables\n    client.py      OpenAI-compatible client and model callable\n    tools.py       registry, schemas, sandboxed file tools, calculator\n    safety.py      argument parsing, schema validation, truncation\n    memory.py      context compaction and remember/recall tools\n    loop.py        the agent loop with step budget and duplicate guard\n    trace.py       JSON Lines trace writer\n    cost.py        token ledger\n  tests/\n    test_loop.py   seven model-free tests\n  evals/\n    cases.jsonl    four eval tasks\n    run_evals.py   eval runner with pass/fail and cost\n  workspace/\n    prices.py\n    orders.csv\n    README.md\n  traces/\n    runs.jsonl     created on first run\n```\n\nRun the whole flow in order whenever you change something: tests first, then evals, then a manual task.\n\n```\npython3 -m pytest -q\npython3 evals/run_evals.py\npython3 cli.py \"Total the orders in orders.csv and name the file you used.\"\n```\n\nKeep 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.\n\nBefore 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.\n\n## FAQ\n\n### Do I need LangChain or another framework to build an AI agent?\n\nNo. 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.\n\n### Which open-weight model should I use for tool calling?\n\nPick 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.\n\n### Can I use this code with a closed API instead?\n\nYes, 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.\n\n### How many steps should the budget allow?\n\nEight 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.\n\n### Is it safe to let an AI agent run shell commands?\n\nNot 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.\n\n### Why does my model print JSON instead of calling the tool?\n\nThe 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.\n\n### How do I keep costs down when the agent runs often?\n\nCap 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.", "url": "https://wpnews.pro/news/build-an-ai-agent-in-python-12-steps-80-min", "canonical_source": "https://shattered.io/build-ai-agent-python-open-weight-tool-calling-12-steps-2026/", "published_at": "2026-11-27 14:17:35+00:00", "updated_at": "2026-11-27 14:46:05.030928+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "large-language-models", "developer-tools", "ai-infrastructure"], "entities": ["Shattered.io", "Stack Overflow", "Hugging Face", "OpenRouter", "Ollama", "NVIDIA Nemotron 3.5 Lightning", "OpenAI", "LangChain"], "also_reported_by": [], "takeaway": "Wrapping the model loop in your own code lets you enforce a step budget, strict tool-argument validation, a path sandbox and a token cost ledger, and test the whole agent without calling a model at all.", "recommendation": {"advice": "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.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/build-an-ai-agent-in-python-12-steps-80-min", "markdown": "https://wpnews.pro/news/build-an-ai-agent-in-python-12-steps-80-min.md", "text": "https://wpnews.pro/news/build-an-ai-agent-in-python-12-steps-80-min.txt", "jsonld": "https://wpnews.pro/news/build-an-ai-agent-in-python-12-steps-80-min.jsonld"}}