Can You Build an AI Agent in Pure Python?

    This article explains why an AI agent is a composable engineering pattern rather than a framework-only feature, and how a small Python loop with a unified model interface, tool protocol, memory, and explicit termination can cover many internal workflows. It covers five core abstractions, a minimal skeleton, when to stay with a hand-rolled loop versus a state machine, and a practical checklist for safety, reliability, and evaluation.

    An agent is not a capability owned by any single framework. It is a set of composable engineering patterns: treat a large language model as a replaceable reasoning engine, wire “think—choose a tool—execute—observe—decide again” into an explicit loop, and keep context in a state object. Typical agent kits share the same core abstractions: a unified model interface, multi-step chains, an autonomous decision loop, external tools, and session memory. Those abstractions address real pain points: inconsistent request and response formats across model APIs, single-shot generation that cannot cover multi-hop work, and models that cannot talk to business systems directly. Graph-style orchestration goes further, focusing on branches, loops, checkpoints, and human-in-the-loop steps so complex flows and long-running jobs can resume. Once those needs are clear, reproducing the backbone in pure Python is entirely feasible for many production scenarios.

    The essence of the problem: an agent is a loop, not magic

    A chat completion only returns text. An agent’s value is turning that text into an executable plan. The smallest closed loop is usually: accept a user goal; fold current state (conversation, intermediate results, tool returns) into the prompt; have the model emit a structured action (which tool and arguments, or a final answer); validate and run the tool; write the observation back into state; decide whether to stop. Termination must be explicit: step budget, consecutive failures, user cancel, or the model declaring completion. “Autonomy” without stop conditions easily becomes unbounded calling.

    In pure Python you do not need a graph engine for this loop. A while, a state dict, and a tool registry already cover a large class of internal automation: query a database, call an API, write a file, run a script. Graph orchestration solves a different class of problems: many conditional edges, pause-and-wait for review, and per-node checkpoint resume. If the business is mostly linear or multi-hop tool use, a hand-rolled loop is lighter and easier to control.

    Five abstractions you should implement yourself

    1. Unified model interface. Hide vendor differences behind an adapter: input is a message list (system, user, assistant, tool results); output is text or a “tool-call intent.” Timeouts, retries, streaming and non-streaming belong inside the client. Business code depends only on the interface, which avoids lock-in and makes local versus cloud models interchangeable.

    2. Tool protocol. Each tool needs a stable name, a natural-language description, JSON Schema-style parameter constraints, and a sync or async function. The runtime may call only a whitelist; arguments must be validated against the schema. Never pass model-invented paths, SQL, or URLs straight to the OS. Tool failures should return an error summary the model can understand, not a raw stack dump in context.

    3. Decision loop (ReAct-style or function-calling). With native function calling, the model returns a structured call. If the model lacks that, use a strict JSON protocol plus parse-and-retry. Parse failure is a recoverable error: ask the model to rewrite to the format, do not silently continue. Log every step: prompt summary, raw model output, parse result, tool inputs and outputs, for audit.

    4. Memory and state. Short-term memory is the current task state: goal, steps taken, key facts, todos. Long-term memory, if needed, should be on-demand recall via vector search or a relational store, not stuffing full history into the window. State should be serializable for logs, replay, and human takeover.

    5. Orchestration depth. Simple agents can stay on a loop. When you need classify-then-route, failure fallback, parallel fetches, or mid-flow human confirmation, use an explicit state machine: pure node functions, conditional edges, one global state dataclass. A checkpoint is a state snapshot in object storage or a database; human-in-the-loop is a node that sets waiting_human and resumes from that node when the API continues. That is the same class of capability as a dedicated graph framework, implemented more plainly.

    A minimal illustrative skeleton

    The following is structural sketch code, not a production implementation, and it is not bound to any third-party SDK.

    1. from dataclasses import dataclass, field
    2. from typing import Any, Callable, Dict, List, Optional
    3. @dataclass
    4. class AgentState:
    5. goal: str
    6. messages: List[dict] = field(default_factory=list)
    7. step: int = 0
    8. done: bool = False
    9. final: Optional[str] = None
    10. class Tool:
    11. def __init__(self, name: str, desc: str, schema: dict, fn: Callable[..., Any]):
    12. self.name, self.desc, self.schema, self.fn = name, desc, schema, fn
    13. class Agent:
    14. def __init__(self, llm, tools: List[Tool], max_steps: int = 8):
    15. self.llm = llm
    16. self.tools = {t.name: t for t in tools}
    17. self.max_steps = max_steps
    18. def run(self, goal: str) -> str:
    19. s = AgentState(goal=goal)
    20. s.messages.append({"role": "user", "content": goal})
    21. while not s.done and s.step < self.max_steps:
    22. s.step += 1
    23. action = self.llm.decide(s.messages, self._tool_specs())
    24. if action.get("type") == "final":
    25. s.done, s.final = True, action["text"]
    26. break
    27. name, args = action["tool"], action.get("args") or {}
    28. if name not in self.tools:
    29. s.messages.append({"role": "tool", "content": f"unknown tool: {name}"})
    30. continue
    31. try:
    32. obs = self.tools[name].fn(**args)
    33. except Exception as e:
    34. obs = f"execution failed: {e}"
    35. s.messages.append({"role": "tool", "name": name, "content": str(obs)})
    36. return s.final or "did not finish within step budget"

    The key split: llm.decide turns state into a final answer or a tool call; the tool layer owns side effects; the loop owns budget and termination. Production still needs argument validation, timeouts, idempotency, second confirmation for sensitive actions, and token-budget trimming.

    Hand-rolling is feasible—know the boundary

    Typical good fits: internal ops assistants (metrics, logs, restarting a job in a specified environment), document Q&A plus retrieval, form fill and ticket drafts, constrained data queries. These have a narrow tool surface, clear permissions, and rollback-friendly failures.

    Do not brute-force with pure handwritten control when you have very long flows that need precise checkpoint resume, many conditional edges and parallel joins, multi-agent negotiation, or strong compliance audit and visual ops. Introduce workflow or state-machine middleware instead of piling on if/else. On the cloud you can put session state in object storage, enqueue async work, run isolated tool processes on a container platform, and watch failure rate and latency with logs and alerts—these are general capabilities, independent of any agent framework.

    Engineering checklist

    Safety: least privilege, tool sandboxing, no arbitrary code execution; outbound network and secrets via a server-side proxy. Reliability: per-step timeouts, overall step and cost caps, idempotency keys. Observability: structured logs per step, correlated trace IDs, sampled replay of failures. Prompts: freeze goals, constraints, tool descriptions, and output protocol; version them. Eval: a fixed task set to regress whether the agent picks the right tool, whether arguments are valid, and whether it fabricates “done.”

    Conclusion: Without a heavy orchestration library, a pure-Python AI agent is not only feasible; it helps a team understand an agent’s real production boundaries. Frameworks offer polished abstractions and ecosystem, not irreplaceable magic. Ship one high-value path with a minimal loop first, then upgrade to a state graph when branch complexity demands it. Keep model, tools, state, and policy separate so swapping model vendors or plugging in an enterprise knowledge base stays straightforward.