Building AI Agents with Pure Python: Do You Really Need an Agent Framework?

    Many developers debate whether building an LLM-powered AI Agent requires a mature orchestration framework or whether plain Python with direct API calls is enough. This article examines what frameworks actually encapsulate, demonstrates a minimal but complete Agent kernel in under fifty lines of pure Python, analyzes the real engineering costs of the DIY approach, and provides practical selection criteria: when to hand-roll your Agent and when to adopt a framework.

    Building AI Agents with Pure Python: Do You Really Need an Agent Framework?

    1. The Origin of the Question: A Debate Over “Framework or Not”

    In AI application development communities, one topic keeps resurfacing: when building an AI Agent, should you write it from scratch in pure Python with direct LLM API calls, or must you rely on a mature Agent orchestration framework?

    Both camps have their advocates. One group of developers argues that frameworks encapsulate the tedious work of model invocation, tool registration, and state management, significantly lowering the barrier to entry. Another group has found in practice that the framework’s abstraction layer actually obscures the details of prompts and model responses, making debugging difficult and behavior unpredictable — ultimately, once their projects matured, they removed the framework and returned to raw API calls. Some teams overseas have even publicly shared their experience of removing a mainstream framework from production after a full year of use, citing that “the team became more efficient after removing it.”

    This disagreement is no accident. LLM providers themselves hold a spectrum of positions: some explicitly advise developers to “start with direct API usage, since many patterns require only a few lines of code,” warning that “wrong assumptions about framework internals are a common source of customer issues.” Others promote their own lightweight, code-first SDKs. Yet others believe “using a framework is usually the better choice.” Behind these differing stances lies a different judgment about the cost-benefit tradeoff of abstraction layers.

    This article takes no preset position. Instead, starting from technical fundamentals, it answers three questions: What problems do frameworks actually solve? How hard is a “bare implementation” of those problems? And when should you use a framework, and when is hand-rolling the better option?

    2. Understanding a Framework’s Value: What Does It Encapsulate?

    To judge whether a framework is dispensable, you must first understand the core pain points it tries to address. Mainstream Agent frameworks provide roughly five categories of abstraction:

    1. A unified model invocation interface: Different LLM services have different API formats, parameter naming, and streaming protocols. Frameworks offer unified wrappers to avoid vendor lock-in.
    2. Multi-step orchestration: They structure chained flows like “invoke model — parse result — invoke tool — invoke model again,” reducing the cognitive load of hand-writing loops.
    3. Autonomous decision loop: The heart of an Agent is the loop where “the model decides what to do next.” Frameworks abstract this into a standard executor.
    4. Tools and external system connections: They provide standard protocols for tool registration, parameter validation, and function calling.
    5. State and memory management: Including conversation history maintenance, checkpoint recovery for long-running tasks, and human-in-the-loop approvals.

    Beyond these, one category of frameworks focuses on state graph workflows, modeling Agent logic as a state machine with conditional branches, supporting checkpoints and backtracking. Another category focuses on multi-Agent collaboration, simulating team division of labor through role definitions and task delegation. These abstractions do correspond to real needs. The question is: are they complex enough to warrant a framework?

    3. The Answer Hinges on One Technical Fact: The Agent’s Essence Is Minimal

    There is a key fact that is often overlooked: the essence of an LLM application requires only three things — string processing, API calls, and loops. These are exactly what Python excels at. Once you understand this, it becomes clear why pure hand-rolling is entirely feasible.

    Below, we implement a minimal yet complete Agent kernel in pure Python.

    3.1 Step One: Model Invocation with Tools

    Assuming your LLM service supports function calling, the first step is to define the tool’s JSON Schema and call the API:

    1. import json
    2. import requests
    3. LLM_URL = "https://your-llm-provider.example.com/v1/chat/completions"
    4. TOOLS = [
    5. {
    6. "type": "function",
    7. "function": {
    8. "name": "query_order",
    9. "description": "Query order status by order ID",
    10. "parameters": {
    11. "type": "object",
    12. "properties": {
    13. "order_id": {"type": "string", "description": "Order number"}
    14. },
    15. "required": ["order_id"]
    16. }
    17. }
    18. }
    19. ]
    20. def call_llm(messages, tools=None):
    21. payload = {"messages": messages, "tools": tools or []}
    22. resp = requests.post(LLM_URL, json=payload,
    23. headers={"Authorization": "Bearer <token>"})
    24. return resp.json()["choices"][0]["message"]

    There is no magic here — a so-called “unified model interface” is essentially just an HTTP request wrapper like this.

    3.2 Step Two: Tool Execution and the Decision Loop

    The heart of an Agent is a loop: the model returns a tool-calling intent, the tool is executed locally, the result is fed back into the model, and this continues until the model produces a final answer.

    1. def query_order(order_id: str) -> str:
    2. # In a real project, connect to your internal order system here
    3. return json.dumps({"order_id": order_id, "status": "Shipped"})
    4. TOOL_REGISTRY = {"query_order": query_order}
    5. def run_agent(user_input: str, max_turns: int = 10) -> str:
    6. messages = [
    7. {"role": "system", "content": "You are an order assistant. Use tools to answer questions."},
    8. {"role": "user", "content": user_input},
    9. ]
    10. for _ in range(max_turns): # Key: cap turns to prevent infinite loops
    11. reply = call_llm(messages, tools=TOOLS)
    12. messages.append(reply)
    13. if reply.get("tool_calls"):
    14. for tc in reply["tool_calls"]:
    15. fn_name = tc["function"]["name"]
    16. fn_args = json.loads(tc["function"]["arguments"])
    17. result = TOOL_REGISTRY[fn_name](**fn_args)
    18. messages.append({
    19. "role": "tool",
    20. "tool_call_id": tc["id"],
    21. "content": result,
    22. })
    23. else:
    24. return reply["content"] # Model stopped calling tools — task complete
    25. return "Max turns reached, task aborted."

    In fewer than fifty lines of code, an Agent with tool-calling capability is complete. Once you strip away the abstraction, the “Agent executor” in frameworks shares nearly identical core logic.

    3.3 Step Three: State and Memory Management

    Conversation memory is essentially just maintaining a list of messages; persistence can be added as needed:

    1. class ConversationStore:
    2. """Minimal session state management: in-memory + persistence hooks"""
    3. def __init__(self, ttl_turns: int = 20):
    4. self.sessions: dict[str, list] = {}
    5. self.ttl_turns = ttl_turns
    6. def get(self, session_id: str) -> list:
    7. return self.sessions.setdefault(session_id, [])
    8. def save(self, session_id: str, checkpoint: dict):
    9. # Checkpoint saving: enables resumption of long-running tasks
    10. with open(f"ckpt_{session_id}.json", "w") as f:
    11. json.dump(checkpoint, f, ensure_ascii=False)
    12. def trim(self, session_id: str):
    13. # Context window is limited; overly long history must be truncated or compressed
    14. msgs = self.sessions.get(session_id, [])
    15. if len(msgs) > self.ttl_turns * 2:
    16. self.sessions[session_id] = msgs[-self.ttl_turns * 2:]

    As for “multi-Agent collaboration,” its core is equally plain: each Agent is simply an independent run_agent instance that passes task results to one another via a shared message queue or function calls. Concepts like roles, goals, and background descriptions in frameworks are, once compiled into prompts, fundamentally just system message text.

    4. The Real Costs and Pitfalls of the DIY Approach

    Feasibility does not mean free. Choosing to hand-roll means you take on the following engineering responsibilities yourself:

    • Context management: Context windows are limited, so you need to implement your own strategies for history truncation, summary compression, and retaining key information.
    • Error handling: The model may produce invalid tool arguments or fall into repeated invocation loops. You need parameter validation, turn limits, and backoff retries (the max_turns in the code above is the most basic safeguard).
    • Observability: Frameworks typically include tracing out of the box. When hand-rolling, you must log the prompt, response, and tool latency for each turn yourself, and can integrate with standard logging and alerting systems.
    • Checkpoint recovery: Resuming long-running tasks after interruption requires designing your own state serialization scheme.
    • Multi-model adaptation: If you need to switch between LLM providers, you must normalize the API differences yourself.

    None of these are insurmountable obstacles, but they do represent real engineering effort. On the flip side, these modules usually amount to only a few hundred lines of code, and once written, they become the team’s own asset — every line is transparent and debuggable, with no “black box” problem of abstractions hiding prompts and responses.

    5. A Decision Framework: When to Hand-Roll, When to Use a Framework

    Based on the analysis above, here is a pragmatic set of selection criteria:

    Scenarios favoring hand-rolling (pure Python + API):

    • The Agent flow is relatively clear, with single-digit to a dozen or so tools;
    • Fine-grained control over prompts and model behavior is required (e.g., compliance-heavy business);
    • The team needs a deep understanding of Agent mechanics, or wants to build long-term in-house capability;
    • The project is in an exploratory phase, where fast iteration matters more than completeness.

    Scenarios favoring frameworks:

    • The workflow contains many complex branches, parallelism, or human approval nodes, where graph orchestration offers clear benefits;
    • Mature checkpoint and recovery mechanisms for long-running tasks are needed, and the team lacks the bandwidth to build them;
    • Multi-Agent collaboration is large in scale, and task delegation and role management need ready-made structures;
    • Team turnover is high, and a framework serves as a “common language” that lowers collaboration costs.

    A recommended evolution path: start by building the minimal closed loop in pure Python to validate business value; when process complexity exceeds manageable limits, then introduce a framework or build your own orchestration layer. Even if you eventually adopt a framework, the team will have first-hand knowledge of the underlying mechanisms, avoiding being “held hostage” by the abstraction layer.

    6. Conclusion

    Returning to the title’s question: is it truly feasible to build an AI Agent in pure Python without a framework? The answer is yes — and in quite a few scenarios, it is the better choice. The confidence comes from the technical essence of Agents: string processing, API calls, and loops, all of which Python handles natively and elegantly. A framework’s value lies in encapsulating complexity and providing ready-made orchestration and collaboration mechanisms — but the price of that convenience is an extra abstraction layer, a debugging black box, and potential over-engineering.

    There is no standard answer in technology selection, only fit. What truly matters is not “whether to use a framework” but whether the team understands the underlying mechanics of how Agents run — because regardless of the route taken, the quality of the system is ultimately determined by the fundamentals: prompt design, tool granularity, context management, and error protection. And hand-building a minimal Agent is precisely the fastest way to master those fundamentals.