Building AI Agents in Pure Python Without Frameworks: Is It Feasible?

    This article explores the feasibility and advantages of building AI agents using pure Python and LLM APIs without relying on any AI frameworks. It covers the core concepts of agents, including the tool-calling loop, context management, state machines, and reliability engineering. Additionally, it provides a practical decision-making framework to help developers choose between a framework and a hand-written approach for production environments.

    I. Conclusion First: Feasible, and Often a Better Choice

    Many developers, upon first encountering AI Agents, default to installing an agent development framework and following its documentation to define nodes, edges, roles, or task pipelines. This path is suitable for rapid prototyping, but in serious production engineering projects, manually implementing Agents with “pure Python + LLM API” is being adopted by an increasing number of teams. The reasons are straightforward:

    1. Controllable Dependencies: Framework versions iterate rapidly, and interfaces change frequently, with upgrades often triggering cascading modifications. Pure hand-written code relies only on an HTTP client and the standard library, significantly reducing supply chain risks and maintenance costs.
    2. Transparent Behavior: When an Agent encounters issues, you can trace line-by-line every model call, every prompt, and every tool return value. Within a framework, these details are often wrapped in layers of abstraction, making troubleshooting like opening a blind box.
    3. Fine-grained Cost Control: You can precisely control the token consumption, context pruning strategy, and retry logic of each conversation turn, avoiding the hidden overhead brought by framework default behaviors.

    Of course, this does not mean frameworks are useless. When you need to quickly validate ideas, the team lacks relevant experience, or the business scenario highly aligns with a framework’s preset paradigm, frameworks remain a reasonable choice. The key is: after understanding the essence of an Agent, a framework is just an optional accelerator, not a necessity.

    II. The Essence of an Agent: A Loop with Tools

    Stripped of all framework concepts, the core of an AI Agent can be distilled into one sentence:

    In a loop, let the LLM repeatedly think and call tools until it determines the task is complete.

    Expressed in pseudocode:

    1. while not done:
    2. response = llm.chat(messages, tools=tool_definitions)
    3. if response.has_tool_call:
    4. result = execute_tool(response.tool_call)
    5. messages.append(result)
    6. else:
    7. done = True
    8. return response.text

    This loop is less than ten lines, but it is the entire skeleton of an Agent. Everything a framework provides—node orchestration, state graphs, role collaboration, task decomposition—is essentially a wrapper around this loop at different levels of complexity. Once you understand this, “hand-crafting an Agent” is no longer a mystery.

    III. Pure Code Implementation of Core Modules

    1. Tool System: Describing Capabilities with Function Signatures

    The standard approach to tool calling is: send each tool’s name, parameter structure, and usage description to the model in a structured format along with the prompt, allowing the model to decide whether to call it and what parameters to pass. A pure Python implementation can be quite elegant:

    1. import json
    2. def get_tool_schema(func, description):
    3. """Extract name, description, and parameter structure from function"""
    4. return {
    5. "name": func.__name__,
    6. "description": description,
    7. "parameters": extract_signature(func), # Generated based on type annotations
    8. }
    9. def run_tool(name, arguments, registry):
    10. func = registry[name]
    11. return json.dumps(func(**arguments), ensure_ascii=False)

    Practical tips:

    • Use type annotations to auto-generate parameter descriptions, avoiding the maintenance of two separate copies.
    • The docstring of each tool should clearly explain “when to use it,” which is the primary factor affecting the model’s decision accuracy.
    • Tool execution must have timeouts and exception handling, returning error messages as results to the model for self-correction, rather than crashing the process directly.

    2. Context and Memory Management

    In long tasks, the context expands rapidly. Under a pure hand-written approach, you need to explicitly do three things:

    • Pruning: Keep the system prompt, the most recent N turns of conversation, and key tool results, compressing or discarding intermediate processes.
    • Summarization: When approaching the context window limit, have the model make periodic summaries of the history, replacing the original text with the summary.
    • Persistence: Write key facts to external storage (like a relational database or key-value store) and query them via tools when needed, rather than stuffing everything into the conversation window.

    This layer of “memory” usually comes with default strategies built into frameworks, but default strategies are often neither token-saving nor tailored to the business. Hand-writing allows you to customize based on task characteristics, such as retaining complete file references for code tasks or only retaining user profiles and key demands for customer service tasks.

    3. State Machine: A Pragmatic Alternative to Complex Orchestration Graphs

    Complex multi-step tasks can be managed with an explicit state machine. A Python dictionary and a dispatch function are sufficient:

    1. def agent_step(state):
    2. handler = STATES[state["phase"]]
    3. next_state = handler(state)
    4. state["phase"] = next_state
    5. return state

    Compared to graphical orchestration frameworks, the benefit of this approach is that the state transition logic can be directly unit-tested, debugged with breakpoints, and fully replayed in logs. When the task flow changes, you modify plain Python code rather than some graph definition.

    4. Reliability Engineering: The Watershed for Production Environments

    The gap between prototype and production primarily lies in this layer. Whether using a framework or not, it must be done, and the hand-written approach gives you complete control:

    • Retry and Backoff: Implement exponential backoff retries for model rate limits and transient errors.
    • Structured Output Validation: Validate the schema of the model’s returned call intent; if invalid, inject the error message and request a retry.
    • Loop Limit: Set a maximum number of iterations to prevent the model from falling into meaningless repetitive calls.
    • Full-Link Logging: Record the complete request and response for each turn, coordinating with logging services and monitoring/alerting infrastructure to achieve traceable issues and observable metrics.

    IV. How to Decide: Hand-Write or Use a Framework

    Here is a pragmatic decision-making framework:

    Scenario Recommendation
    Rapid prototyping, validating feasibility Framework speeds things up significantly, usable
    Production service, long-lifecycle maintenance Lean towards hand-writing, fewer dependencies mean more stability
    Highly customized processes and memory strategies Hand-writing, framework abstractions will get in the way
    Team lacks Agent experience, needs standardization Framework’s paradigm constraints have value

    A recommended compromise path is: first use a framework to quickly run the prototype and understand its internal mechanisms; then extract the core loop and rewrite it in pure Python for the production version. Furthermore, if an enterprise is already using a cloud provider’s LLM inference and accompanying cloud services, the hand-written approach can also be integrated with minimal transformation cost—just replace the API endpoint and authentication configuration, with no framework lock-in issues.

    V. Conclusion

    An AI Agent is not some black box magic. In essence, it is a “model thinks—calls tool—observes result” loop, plus memory management, state control, and reliability engineering. Any team with solid engineering capabilities can build a production-grade Agent tailored to their business with a few hundred to a couple of thousand lines of Python. Frameworks solve “fast from zero to one,” while hand-writing solves “stable from one to N.” Once you have hand-written an Agent yourself, looking back at any framework, you will find they are merely wrapping what you already understand. From then on, the choice truly returns to your own hands.