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

    This article examines whether you can build an AI agent using only pure Python, without an orchestration framework. It clarifies what agent frameworks actually provide, defines which use cases are suitable for a hand-written approach, and walks through minimal implementations of five core modules: a unified model interface, a tool layer, the decision loop, state and memory, and orchestration with recovery. It also covers the engineering capabilities you must build yourself and offers a practical adoption path.

    Introduction: Frameworks Solve Abstraction Problems, Not Intelligence Problems

    Before discussing whether you can build an AI agent without an existing orchestration framework, using only pure Python, it helps to clear up a common misconception: the value of mainstream agent development frameworks is not that they make models smarter, but that they turn the engineering problems that repeatedly appear in LLM applications into reusable abstractions. Once this is clear, you have an objective basis for judging whether a self-built approach is feasible.

    By the widely accepted definition, these frameworks typically provide five core abstractions: a unified model invocation interface (which hides payload differences across provider APIs and avoids vendor lock-in), chain orchestration (linking multiple steps into a flow), autonomous decision units (letting the model choose the next action itself), a tool integration layer (connecting external systems and data), and state and memory management (preserving context across multiple interactions). More advanced solutions add graph-based orchestration, conditional branching, checkpoint persistence, and human-in-the-loop nodes on top of these, to express complex flows and long-running task recovery; multi-agent solutions implement collaboration around role definitions and task assignment.

    These abstractions all address real pain points: inconsistent interface formats, the difficulty of completing multi-step tasks in a single call, the model’s inability to perform real actions on its own, hard-to-maintain complex branching, and the inability to resume after a long flow is interrupted. Conversely, as long as you can implement these layers of responsibility in pure Python, the agent will run. A framework is a “packaged answer,” not an “unavoidable law of physics.”

    1. Define the Boundary First: Which Agents Suit a Hand-Written Approach

    The first step in building your own is not writing code, but drawing a clear scope. Three dimensions are useful for the decision:

    • Flow determinism: Steps that are mostly fixed with limited branching suit a hand-written approach; when the model must dynamically plan paths at high frequency, orchestration complexity rises quickly.
    • Runtime duration and recovery requirements: For tasks on the order of seconds to minutes, keeping state in memory is enough; hour-long tasks that need to resume from a breakpoint require external persistence.
    • Number of tools and side effects: With few tools that are mostly read-only, the hand-written cost is low; with many tools that include write operations, the engineering effort for access control and auditing can exceed the orchestration itself.

    The conclusion is pragmatic: for small and medium-sized agents with controllable flows, centered on “a model + a few tools + limited state,” pure Python is entirely feasible, with fewer dependencies, more transparent behavior, and more direct debugging.

    2. Minimal Implementations of Five Core Modules

    1. Unified Model Interface

    Do not scatter calls to a specific provider’s API. Instead, define your own protocol layer that fixes “a list of input messages, and output text plus structured actions.” Switching providers then means changing only one adapter.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class Message:
    4. role: str # system / user / assistant / tool
    5. content: str
    6. class LLMClient:
    7. def chat(self, messages: list[Message], **kw) -> str:
    8. raise NotImplementedError
    9. class AdapterA(LLMClient): # Connects to a general-purpose LLM API
    10. def chat(self, messages, **kw):
    11. # Convert Message objects into the payload format this API requires
    12. ...

    Key points: a unified message structure, unified error semantics (timeouts, rate limiting, and blocked content expressed as distinct exceptions), and a unified retry and backoff strategy.

    2. Tool Layer: Description, Registration, and Invocation

    A tool is essentially “a function the model can call, plus a machine-readable description.” The description must clearly state the name, purpose, parameter structure, and constraints so the model can select it correctly.

    1. TOOLS = {
    2. "get_weather": {
    3. "desc": "Get the current weather for a given city",
    4. "params": {"city": "string"},
    5. "func": lambda city: f"{city}: sunny, 26C"
    6. }
    7. }
    8. def dispatch(name: str, args: dict) -> str:
    9. spec = TOOLS[name]
    10. return spec["func"](**args)

    Engineering practice adds three more things: parameter validation (reject invalid input outright, without letting it enter the model context), timeouts and concurrency limits, and human confirmation plus an audit trail for write operations.

    3. Decision Loop: The Agent’s “Heart”

    Autonomous decision-making comes down to a controlled loop: the model’s output is either a final answer or “call a specific tool with these arguments.” The program executes the tool, feeds the result back, and requests the model again, until a condition is met or a limit is triggered.

    1. def run_agent(query: str, llm: LLMClient, max_steps=8):
    2. msgs = [Message("system", "You are an assistant. Call a tool when you need external information."), Message("user", query)]
    3. for _ in range(max_steps):
    4. out = llm.chat(msgs)
    5. action = parse_action(out) # Parse into {"tool":..., "args":...} or None
    6. if action is None:
    7. return out
    8. result = dispatch(action["tool"], action["args"])
    9. msgs += [Message("assistant", out), Message("tool", result)]
    10. return "Maximum number of steps reached; task terminated."

    You must set a step limit and detect repeated calls; otherwise the model may bounce back and forth between two tools in an unproductive loop.

    4. State and Memory

    Distinguish three kinds of state: short-term context (messages in the current session), working memory (intermediate task results, such as material already retrieved), and long-term memory (cross-session preferences, which need to be persisted and retrieved). A minimal implementation can start with an in-memory dictionary, then move to external storage and vector retrieval as it matures.

    5. Orchestration and Recovery

    When conditional branching appears or human approval is needed, model “what to do next” explicitly as a state transition, and write each step’s input and output to external storage (such as object storage, a message queue, or a logging service). That is enough to resume after an interruption. This is the core idea behind advanced orchestration; writing it by hand is not mysterious, it just means taking on the details of persistence and consistency yourself.

    3. Engineering Capabilities You Must Fill In Yourself

    What frameworks save you is often not the algorithm but the dirty work:

    1. Observability: Log the prompt, latency, token usage, and tool return for each call, so you can pinpoint “why the model chose the wrong tool.”
    2. Fault tolerance: Distinguish retryable from non-retryable errors, and avoid treating rate limiting as a content error.
    3. Security: Tool whitelists, least privilege, secondary confirmation for sensitive operations, and filtering in both directions for input and output.
    4. Cost control: Cache repeated requests, compress historical context, and use lightweight models for small tasks.
    5. Evaluation: Prepare a fixed set of test cases and run regression on “task completion rate, average number of steps, and tool misuse rate,” to prevent capability from quietly degrading after a prompt change.

    4. Example: A Runnable Minimal Loop

    1. if __name__ == "__main__":
    2. llm = AdapterA()
    3. print(run_agent("What is the weather in Beijing today?", llm))

    This code has no third-party orchestration dependency, yet already forms a complete loop of “understand intent, select a tool, feed back the result, generate an answer.” Turning it into a production system requires persistence, monitoring, and access control, not some particular framework.

    5. Conclusion and Recommendations

    Building an agent in pure Python is not only feasible but also the better choice in scenarios with controllable flows, dependency sensitivity, and a need for deep customization: behavior is transparent, troubleshooting is direct, and there is no extra abstraction burden. Conversely, when tasks require complex dynamic planning, long-running execution, and multi-agent orchestration with collaboration among multiple people, the cost of building your own rises quickly and can approach or even exceed adopting a mature solution.

    A pragmatic path is to first get a minimal loop running by hand, and refine the prompts, tool descriptions, and evaluation set until they are stable; then introduce the corresponding capabilities on demand, as specific pain points appear in state persistence, branch orchestration, and multi-role collaboration. If you want to hand off model serving, storage, and monitoring and alerting to a cloud platform, you can look into general cloud product capabilities from providers such as Baidu AI Cloud, so you can focus your effort on the business logic itself.