Can You Build an AI Agent in Pure Python?

    A thin, handwritten Python agent—model calls plus your own loop—is often enough for production. This article explains the reasoning–action–memory loop, tool contracts, state, failure handling, observability, and when a framework is worth adding.

    In real projects, an agent written only in Python against a large-model API is entirely workable. Without a heavy orchestration framework, it is often more controllable and easier to audit. Frameworks shorten the path to a demo, but they also hide the state machine, retries, permissions, and cost inside a black box. When business rules are strict, the call chain must be explainable, or the runtime is sensitive to dependency size, a thin handwritten loop usually fits delivery standards better.

    An agent is essentially a closed loop of model reasoning, external actions, and memory or state. On each turn, the model first produces a structured intent. The program then calls a tool or queries data, writes the result back into context, and decides whether to continue reasoning or stop. What a framework standardizes is the loop, tool registration, and message assembly. Those pieces can be implemented in a small amount of clear code whose behavior is fully visible.

    A handwritten core loop usually includes system constraints, the current task and a history summary, the list of available tools, one model output, action parsing, execution, writing the observation back, and a termination check. Termination conditions should be fixed on the program side: a step limit, consecutive tool failures, an explicit user stop, or a final answer from the model that passes validation. Do not leave “whether to stop” entirely to the model.

    The tool layer should follow one protocol: name, parameter schema, timeout, permission tags, and an idempotency note. Validate the schema and check permissions before the call. After the call, trim the result so oversized logs or sensitive fields are not copied back into context unchanged. Network, database, retrieval, and compute calls should all go through the same adapter so rate limits, circuit breaking, and audit are consistent. Tool execution has real side effects, so “what the model wants to do” must stay separate from “what the system is allowed to do.”

    State does not need to start as a complex graph. Most workloads can use a few fields: goal, completed steps, items awaiting confirmation, a summary of key facts, and an error count. Long conversations should be compressed into summaries on a schedule, with raw detail stored in object storage or a logging service and retrieved only when needed. That keeps context short while preserving traceability. If the flow truly has branches and parallelism, an explicit state machine or a task queue is enough. There is no need to adopt a hard-to-debug implicit graph just to “look like an agent.”

    Fault tolerance is where a handwritten design wins or loses. Model output may be invalid, tools may time out, and the same action may be proposed again. In practice: if parsing fails, require a retry in a fixed format; if a tool fails, record the observation and allow a limited number of strategy changes; use idempotency keys for writes; and set timeouts and concurrency caps on external calls. For cost, enforce hard quotas on tokens per turn, steps per task, and calls per day. When a quota is exceeded, fall back to a human or a fixed rule instead of burning the API in an unbounded loop.

    Observability decides whether the system can go to production. At minimum, record a request identifier, a summary of the model input at each step, the parsed action, tool latency and error codes, and the reason for termination. Logging and alerts should cover failure rate, average step count, and timeout ratio. When something breaks, you should be able to pull the full chain for one task. That is more direct than relying on internal framework instrumentation.

    Handwriting fits better when the tool set is small and stable, the flow is driven mainly by deterministic business rules, security or compliance requires auditable actions, and the team wants as few dependencies as possible. A mature orchestration component is worth considering for long-running multi-role collaboration, hot-plugging many heterogeneous tools, or visual debugging when the team already accepts that abstraction. Even then, keep permissions, quotas, and state persistence in your own code so critical control does not sit in an invisible layer.

    A practical split has four layers: an interface layer for sessions and authentication; an orchestration layer that only runs the loop and termination; a capability layer that wraps tools; and a memory layer for summaries and retrieval. Keep the model API replaceable, and version prompts and tool descriptions. In tests, unit-test the parser, permissions, and stop conditions, and run fixed-script regression on typical tasks so the agent does not merely “sound capable” while failing at the edges.

    The conclusion is straightforward: a pure-Python agent is not only feasible, it is often the better choice in systems that emphasize control and operability. The framework is not the source of capability. The closed-loop design, tool constraints, state governance, and observation are. Write that layer thin and thoroughly first, then add orchestration only as needed, and you can reach production both quickly and steadily.