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

    This article explores whether you can build a functional AI Agent using only pure Python, without any orchestration framework. It breaks down what frameworks actually do, the four core engineering problems they abstract, and the four minimal modules you can write yourself: a model call adapter, tool registration and execution, the decision loop, and state management. You will also find guidance on when to build from scratch versus when to adopt a framework, plus common pitfalls and best practices around step limits, context growth, and observability.

    1. The Short Answer: Yes, but Know What a Framework Does for You

    Is it feasible to hand-write an AI Agent in pure Python, without any existing orchestration framework? Yes. An Agent is not mysterious: it is a loop that takes input, calls the model for reasoning, decides whether to call a tool, executes the tool, feeds the result back into the context, and reasons again. You can get this loop running in a few dozen lines of Python.

    But “it runs” and “it works well” are two different things. Orchestration frameworks exist because they package up a handful of engineering problems that keep recurring. Before deciding whether you need one, it helps to see what those abstractions actually solve.

    2. The Four Core Abstractions Are All Engineering Problems

    1. A unified model interface. Different model providers differ in request and response formats, authentication, and streaming protocols. A unified interface keeps business logic from being tightly coupled to one provider, so switching models means changing configuration, not logic.

    2. Multi-step chaining and autonomous decisions. A single model call only handles one question and one answer. Complex tasks need decomposition, planning, and reflection. This leads to fixed-flow chains and to decision loops where the model chooses the next action itself.

    3. Connecting tools and external systems. A model on its own cannot query a database, send requests, or read and write files. The tool layer translates the model’s intent into a real call against an external system and returns the result in a structured form.

    4. State and memory management. Multi-turn conversations and long-running tasks need to preserve intermediate state, support resume after interruption, rollback, and human intervention.

    Once you see these four points, it becomes clear that frameworks are not magic. They standardize the capabilities above. You can absolutely write them yourself; you just take on the responsibility for consistency and robustness.

    3. Four Minimal Modules to Hand-Roll in Pure Python

    Module 1: A model call adapter. Wrap request construction, authentication, timeouts, and retries in a single function to hide the underlying differences.

    1. def call_model(messages, tools=None, temperature=0.2):
    2. # Unified input: message list + optional tool definitions
    3. # Handles authentication, timeout, retries, and exceptions internally
    4. return normalized_response # Unified structure: text + optional tool call intent

    Module 2: Tool registration and execution. Use a decorator to register a plain function as a “tool the model can call,” keeping its name, description, and parameter schema.

    1. TOOLS = {}
    2. def tool(name, description):
    3. def deco(fn):
    4. TOOLS[name] = {"fn": fn, "description": description}
    5. return fn
    6. return deco
    7. @tool("search", "Search for information by keyword")
    8. def search(query: str):
    9. return f"Results for {query}"

    Module 3: The decision loop. This is the heart of an Agent: if the model output contains a tool call intent, execute the tool, feed the result back, and keep reasoning; otherwise, stop.

    1. def run_agent(query, max_steps=8):
    2. messages = [{"role": "user", "content": query}]
    3. for _ in range(max_steps):
    4. resp = call_model(messages, tools=TOOLS)
    5. if resp.tool_call:
    6. result = TOOLS[resp.tool_call.name]["fn"](**resp.tool_call.args)
    7. messages.append({"role": "tool", "content": str(result)})
    8. else:
    9. return resp.text
    10. return "Maximum number of steps reached"

    Module 4: State and memory. Use a session object to hold the message history and intermediate variables. When you need persistence, serialize it to a local file or external storage.

    4. When to Build Your Own and When to Use a Framework

    Building your own fits scenarios with a relatively fixed flow, controllable dependencies, a need for deep customization or a minimal dependency footprint. It is also the recommended first step when you are learning how things work.

    Adopting a framework fits scenarios with complex branching and loops, long-running tasks that need checkpoint recovery, multi-role collaboration, or visual orchestration with human review nodes. Hand-writing all of that means the state machine and recovery logic balloon quickly.

    A pragmatic middle ground: own the core loop yourself, and bring in general-purpose capabilities only when you genuinely need them, such as writing state to object storage, decoupling long tasks with a message queue, or observing the chain with logging and monitoring services. Avoid taking on a heavy framework from day one.

    5. Common Pitfalls and Best Practices

    • Runaway steps and cost: Always set a maximum step count and a timeout to prevent infinite loops.
    • Uncontrolled tool output: Truncate the length of tool results and validate their structure to avoid polluting the context.
    • Context bloat: Summarize and compress history, keeping only the key state.
    • Observability: Log the input and output of every step so you can pinpoint why the model made a wrong decision.
    • Idempotency and rollback: Design tools with side effects to be retryable and compensable.

    In short, hand-writing an Agent in pure Python is not only feasible but also the best way to understand what an Agent really is. Frameworks address the engineering burden that comes with scale and complex orchestration, so bring them in as needed.