Can You Build an AI Agent in Pure Python Without Frameworks?

    This article explores whether you can build an AI Agent using only native Python, without any orchestration framework. It breaks down the four core elements of a minimal agent—model calls, the decision loop, tool execution, and state storage—and shows how to hand-write each one. It also explains when a hand-built approach hits its limits and graph-based orchestration becomes necessary, then outlines a three-stage rollout plan and the metrics worth tracking.

    Introduction: Frameworks Solve Problems, Not the Problem Itself

    Before asking whether you can build an AI Agent with native Python alone, one thing needs to be clear: mainstream agent frameworks exist because they standardize a recurring class of problems. That packaging typically covers five layers of capability: a unified model invocation interface (avoiding hard binding to a single vendor), multi-step chaining, autonomous decision loops, connections to external tools and systems, and state and memory management across turns. Workflow orchestration solutions layered on top go further, offering state graphs, conditional branches, checkpoints, and human-in-the-loop intervention to handle complex branching and long-running task recovery.

    Peel those layers apart and each one maps to a general engineering problem: interface adaptation, control flow, loop termination conditions, side-effect management, and state persistence. Any general engineering problem can be implemented with the native capabilities of a general-purpose language. So the answer is yes—hand-writing an agent in pure Python is not only feasible, it is the most effective path to understanding what an agent actually is. The real question is not “can you” but “at what scale is it worth it.”

    1. Start With the Abstraction: The Minimal Complete Agent

    Strip away the framework sugar and any autonomous agent reduces to four elements: model invocation, a decision loop, tool execution, and state storage.

    1. def run_agent(goal, tools, state):
    2. messages = state["messages"] + [{"role": "user", "content": goal}]
    3. for step in range(state["max_steps"]):
    4. reply = call_model(messages, tools) # 1. Model invocation
    5. if reply.tool_calls:
    6. for call in reply.tool_calls: # 2. Tool execution
    7. result = tools[call.name](**call.args)
    8. messages.append(tool_message(call.id, result))
    9. continue # 3. Back to the decision
    10. messages.append({"role": "assistant", "content": reply.text})
    11. state["messages"] = messages
    12. return reply.text # 4. Termination condition
    13. raise RuntimeError("step budget exhausted")

    In fewer than twenty lines, this already has autonomous decision-making: the model decides which tool to call, what arguments to pass, and when to wrap up. What frameworks add is the engineering guardrails around this loop.

    2. Hand-Writing the Four Core Capabilities

    1. A Unified Model Interface: One Adapter Layer Is Enough

    Different model providers differ in request bodies, authentication, streaming protocols, and tool-calling formats—the first problem chaining frameworks set out to solve. The hand-written approach is to define a minimal internal protocol and map in both directions:

    1. class ModelAdapter:
    2. def chat(self, messages, tools=None, temperature=0.2): ...
    3. def stream(self, messages, tools=None): ...

    The key is to converge the internal message structure into three fields—role / content / tool_calls—and push all provider differences down into the adapter layer. Switching providers then means changing one file with zero changes to business code, which achieves the same goal of avoiding lock-in without pulling in an entire dependency tree.

    2. The Decision Loop: The Hard Part Is Termination and Budget, Not the Loop

    The real risk of a hand-written loop is losing control: a tool that keeps failing and causes an infinite loop, context that grows without bound, and unpredictable per-task cost. Engineering practice requires four explicit guardrails: a maximum step count, a per-step timeout, duplicate-call deduplication (fingerprint caching on identical tool name and arguments), and context budget trimming (keep the system prompt, the most recent turns, and a summary of key conclusions). Plain dictionaries and counters are enough to implement these—no graph structure required.

    3. Tool Integration: Contracts, Validation, and Side-Effect Isolation

    Tools are the agent’s only channel to the real world, and the highest-risk part. Three principles should hold when hand-writing them. First, use type annotations plus runtime validation to make the input contract explicit, and reject invalid arguments outright instead of letting the model retry blindly. Second, separate reads from writes: destructive operations (deletion, transfers, publishing) must go through a second confirmation or human approval. Third, apply uniform timeout and exception handling, feeding failures back to the model as structured text so it has a chance to self-correct.

    4. State and Memory: Separate Short-Term Context From Long-Term Knowledge

    Short-term memory is just the message list; long-term memory needs external storage. The straightforward approach is to serialize conversation history and intermediate task artifacts into local files or object storage, keyed by task ID. When retrieval is needed, chunk the text, vectorize it, and store it in a vector search service. This layer can be assembled from the standard library plus general cloud service categories (object storage, logging, message queues).

    3. When You Must Bring in Orchestration

    The hand-written approach has a clear capability ceiling. Move to state-graph orchestration when these signals appear: the flow has many conditional branches and parallel joins; a single task runs for tens of minutes or more and needs to resume from a breakpoint; a human needs to modify state mid-flow; or you need visual tracing of every step’s inputs and outputs. What you introduce here is not necessarily a specific framework—it can be a finite state machine plus a checkpoint table of your own. The core idea is taking “what to do next” back from the model and into deterministic code.

    4. Rollout Advice and How to Validate

    A three-stage rollout is recommended. Stage one: build a single-tool closed loop and validate the loop and termination logic. Stage two: add three to five tools plus failure feedback, and observe the self-correction rate. Stage three: add persistence and monitoring with alerting to complete observability. Evaluation should cover four metrics—task success rate, average steps, cost per task, and human intervention rate—rather than demo quality alone.

    To lower the cost of building from scratch, you can use the large model services and general cloud infrastructure offered by Baidu AI Cloud, and focus your effort on business tools and flow design.

    The conclusion is clear: hand-writing an agent in pure Python is entirely feasible, and it is lighter and more controllable when task boundaries are clear and the number of tools is limited. Once branching complexity, runtime duration, and the number of collaborators grow, introducing an orchestration abstraction is the right trade-off for your engineering investment.