Can You Build an AI Agent in Pure Python Without a Framework?

    A production-grade AI agent can be implemented with the Python standard library plus a model API: a loop that calls the model, parses structured tool instructions, runs local functions, and updates context. This article unpacks the five-part kernel, a runnable skeleton, production pitfalls, when to build in-house versus use an orchestrator, common anti-patterns, and a staged rollout.

    1. Bottom line: it is feasible—and often more controllable

    In real engineering work, you can ship an AI agent without any orchestration framework: Python, a model API, and code you own. When control, observability, and cost are hard requirements, a custom kernel is often a better fit than an off-the-shelf stack.

    The runtime is not mysterious. Strip the wrappers and you have five steps: send the task and context to the model, parse structured instructions, run the matching local functions, write results back into context, and decide whether to loop. Frameworks mainly manage that loop’s state and a tool registry. When you need tight token budgets, retry policy, and audit logs, that layer gets in the way.

    2. Minimal agent kernel

    2.1 Five required pieces

    • Model gateway: request construction, timeouts, retries, rate limits, and fallbacks—business code should not depend on a vendor’s request shape.
    • Context manager: message trimming, summarization, token counting.
    • Tool registry and dispatch: JSON Schema for tools, name-to-callable mapping.
    • Loop controller: continue, converge, or force-stop.
    • State store: sessions, intermediate artifacts, execution traces, and resume-from-checkpoint.

    2.2 A runnable skeleton

    1. import json
    2. TOOLS = {
    3. "query_order": {
    4. "schema": {
    5. "type": "object",
    6. "properties": {"order_id": {"type": "string"}},
    7. "required": ["order_id"],
    8. },
    9. "func": lambda order_id: db.query_order(order_id),
    10. },
    11. }
    12. def run_agent(user_input, max_steps=8):
    13. messages = [
    14. {"role": "system", "content": SYSTEM_PROMPT + json.dumps(
    15. {n: t["schema"] for n, t in TOOLS.items()}, ensure_ascii=False)},
    16. {"role": "user", "content": user_input},
    17. ]
    18. for step in range(max_steps):
    19. resp = llm.chat(messages, tools=list(TOOLS)) # custom gateway
    20. messages.append(resp.message)
    21. calls = resp.tool_calls or []
    22. if not calls:
    23. return resp.content # converge and exit
    24. for c in calls:
    25. spec = TOOLS.get(c.name)
    26. if spec is None:
    27. result = {"error": f"unknown tool: {c.name}"}
    28. else:
    29. try:
    30. result = spec["func"](**c.arguments)
    31. except Exception as e:
    32. result = {"error": str(e)}
    33. messages.append({"role": "tool", "content": json.dumps(result)})
    34. return "Max steps reached; task incomplete" # forced convergence

    Fewer than forty lines, but it already has what an agent needs. The point: every line is yours, so failures map to a specific line.

    3. The hard problems sit outside the loop

    A prototype is easy; production is not. Six issues a custom path must face.

    Context growth and compression. Multi-turn tool use inflates the message list and hits the window. A practical split: keep recent messages in full, summarize the middle as structured notes, keep only key conclusions and artifact refs from the early history, and park large objects in external storage with IDs in context. Count tokens before each append, not after an error.

    Errors the model can act on. The model never sees a stack trace—only the string you write back. Errors should be structured and actionable: missing parameter, resource not found, insufficient permission—so the model can recover. Do not dump raw exceptions and kill the loop.

    Multiple stop conditions. “The model stopped requesting tools” is not enough. Production should combine max steps, max tokens, max wall-clock time, and duplicate-call detection (same name and args in a row). Any trigger converges and returns a clear incomplete reason.

    Idempotency and side effects. Write tools need an idempotency key so retries do not double-submit. Register read-only and write tools separately; writes can require a second confirmation or a human approval step.

    Observability. Persist structured records per turn: input summary, tool name, latency, tokens, return code. Feed logs and alerts so you can dashboard step counts, tool failure rates, and per-task cost. An agent without traces is not operable.

    Concurrency and isolation. A single serial process becomes a bottleneck. Run the agent runtime in containers and scale out by session; offload long tools via a message queue and wake the loop on callback; keep session state in object storage or a cache so instances stay stateless and can resume.

    4. When to build it yourself

    Build in-house when the flow is relatively fixed but accuracy is strict, you need audit and compliance traces, cost requires fine token control, you depend on many private internal tools, or you need a deeply custom loop.

    If you only need a multi-role collaboration PoC and the team cannot budget runtime maintenance, a mature orchestrator is cheaper. The test is not which stack is “better”—it is whether what you must control is exactly what the framework hides.

    5. Common anti-patterns

    Writing the system prompt like a requirements document; no step cap and infinite loops; stuffing huge tool payloads back into context; writes with no idempotency; success logs only, no failure traces; retries in the business layer instead of the gateway. These six show up most often in production incidents.

    6. A practical rollout

    First, close a single-tool loop with the minimal kernel. Second, add token budgets and compression. Third, traces and metrics. Fourth, idempotency, approval, and concurrency isolation. Fifth, load-test cost and latency, then decide whether to add an external orchestrator. Keep the framework replaceable, not the foundation of the architecture—that is the long-term payoff of building the kernel yourself.