Building an AI Agent from Scratch in Pure Python—No Framework Required
Is it possible to build a working AI Agent without any orchestration framework, using only Python and a large language model API? This article argues that not only is it feasible, but in many scenarios a "zero-framework" approach is the better choice. It breaks down the essential anatomy of an Agent, shows the core loop in minimal code, explains what frameworks add and what they hide, and outlines the four modules you need to implement yourself—plus practical guidance on when to use a framework and when to stay native.
In real engineering projects, one question keeps coming up: without any off-the-shelf Agent orchestration framework, can you build a usable AI Agent using nothing but Python and a large language model API? The answer is yes—and in quite a few scenarios, this “zero-framework” approach is actually the better option. This article starts from the essence of what an Agent is, dissects its components layer by layer, and offers a practical implementation approach.
1. First, See What an Agent Really Is: A Heavily Wrapped Loop
Many frameworks make Agents sound extremely complex, but peel away the abstraction layers and a typical Agent runtime contains only three things: string processing, API calls, and a loop. The LLM itself cannot “act”—it merely predicts output text from input text. The so-called “agent” is simply us parsing the model’s output into structured instructions (such as “I want to call a certain tool”), executing them, appending the results back to the context, and then entering the next round—until the model decides the task is complete.
Expressed in pseudocode, the core skeleton is astonishingly short:
def run_agent(goal, tools, max_steps=10):messages = [{"role": "user", "content": goal}]for _ in range(max_steps):reply = call_llm(messages, tools) # 1. Call the modelmessages.append(reply)if reply.tool_calls:for call in reply.tool_calls: # 2. Parse and execute toolsresult = tools[call.name](**call.args)messages.append(tool_result(call.id, result))else:return reply.content # 3. No tool calls means we're donereturn "Max steps reached, task terminated"
There is no magic in this code. Understanding this point is the prerequisite for deciding whether to use a framework.
2. What Frameworks Add—and What They Hide
Mainstream Agent development frameworks do provide value: they encapsulate prompt templates, tool registration, state machines, memory storage, and other common capabilities, letting prototypes run quickly. But abstraction layers come at a cost, mainly in three ways.
First, debugging becomes a black box. When the Agent misbehaves, you face a call stack buried under multiple layers of framework internals rather than clear logic you wrote yourself. Answering “why didn’t the model call the expected tool?” often means wading through large amounts of framework source code.
Second, a flexibility straitjacket. Frameworks usually presuppose an orchestration paradigm they consider “correct.” Once your business needs deviate from it—custom retry strategies, special context-trimming rules, non-standard parallel tool calls—you’ll experience friction with the framework’s design and may be forced into inelegant workarounds.
Third, dependency and upgrade risk. Frameworks iterate frequently, and interface changes can force refactors of your production code. Some teams in the industry, after using a certain orchestration framework for roughly a year, chose to remove it entirely and reported that the system became simpler and iteration smoother afterward. This isn’t a blanket rejection of frameworks—it simply shows that when the benefits of abstraction fall below the complexity it introduces, going native is the rational choice. Similarly, some leading model providers advise developers to “start by calling the model API directly”: understand the essence first, then bring in tools as needed.
3. The Four Core Modules of a Pure-Python Implementation
To hand-build a robust Agent, you need to handle the following four areas seriously—they are exactly the parts frameworks hide for you, but which engineering cannot avoid.
1. Loop and termination control. You must set maximum steps, timeouts, and token budgets to prevent the Agent from looping endlessly or consuming without limit. Termination conditions should be explicitly defined: the model produces a final answer, the step limit is reached, or an exception is triggered.
2. Tool invocation and validation. Every tool needs a clear name, parameter schema, and return value. Parameters generated by the model must be validated with exception handling, because the model may produce invalid input.
def safe_call_tool(name, args):if name not in TOOLS:return {"error": f"Unknown tool: {name}"}try:return TOOLS[name](**args)except Exception as e:return {"error": str(e)} # Feed the error back to the model so it can self-correct
3. Context management. Conversation history keeps growing, so you need a trimming or summarization strategy that preserves key information while controlling token cost. This is the key determinant of how well an Agent performs on long tasks.
4. Observability. Use logging services to record every step’s input, model output, tool calls, and timing, combined with monitoring and alerting, so you can quickly reconstruct what went wrong. This is often overlooked, yet it is the baseline for production readiness.
4. When to Use a Framework, and When to Go Native
There is no absolute answer in technology selection, but a few rules of thumb help:
- Prototyping stage: If the goal is to validate an idea within a few hours, a framework’s scaffolding can speed things up—fine for short-term use.
- Long-term production evolution: If your business logic is complex, deep customization is required, and controllability and maintainability matter most, a native implementation is usually less painful.
- Team capability: If the team already understands how Agents work, the marginal cost of a native implementation is low; if not, a framework’s “ease of use” may actually mask problems.
A pragmatic middle path: first build a minimal working loop natively, learn the real requirements, then decide whether a specific capability (such as vector retrieval or workflow orchestration) justifies an external component. Object storage for saving sessions, message queues for asynchronous decoupling, container platforms for the runtime, logging and monitoring for observability—these general-purpose cloud capabilities (such as those offered by Baidu AI Cloud and comparable providers) can integrate smoothly with a native Agent without tying you to any proprietary framework.
5. Conclusion
Building an AI Agent in pure Python is not only feasible—it’s an underrated engineering skill. Its value is not in “rejecting frameworks,” but in letting you truly master every part of an Agent: how the loop terminates, how tools are validated, how context is trimmed, how failures are observed. When you can explain how an Agent works in a few dozen lines of code, you can then decide which abstractions to adopt without being trapped by them. For most teams pursuing long-term maintainability, starting native and expanding on demand is often the clearer-headed choice.
