Can You Build an AI Agent in Pure Python Without a Framework?
This article examines whether a functional AI agent can be built using only Python, without an orchestration framework. It explains that frameworks mainly handle orchestration rather than intelligence, breaks down the minimal agent core of a loop plus two channels, and walks through four engineering challenges you must handle yourself: context management, tool design, error recovery, and observability. It also outlines when building your own agent is not the right choice and offers practical implementation advice for getting a single scenario working end to end.
1. Frame the Question Correctly: Frameworks Solve Orchestration, Not Intelligence
The question “Can you build an AI agent in pure Python without an existing orchestration framework?” keeps coming up in engineering teams. The debate is not really about technical capability; it is about which abstraction layer the work belongs to. Start from one premise: a large language model only provides the ability to take an input and produce text (or a structured result). It has no memory, cannot take actions on its own, and has no knowledge of the current state of the external world. An agent is a layer of control logic wrapped around the model that lets it loop through observe, decide, and act until the task is complete or an exit condition is triggered.
The value of mainstream orchestration frameworks lies mainly in flow orchestration, state persistence, tool registration, and multi-role collaboration, not in replacing the model’s reasoning. Once this is clear, the conclusion is straightforward: these capabilities can be implemented with standard Python syntax, asynchronous libraries, and a few engineering conventions. You just have to define the boundaries yourself. In real projects, this approach is not only feasible but often the better choice in terms of controllability, dependency size, debugging cost, and data compliance.
2. The Minimal Agent Core: One Loop and Two Channels
Strip away the packaging and every agent has the structure below:
def run_agent(goal, tools, model, max_steps=12):messages = [{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": goal}]for step in range(max_steps):resp = model.chat(messages, tools=tools) # Channel 1: reasoningmessages.append(resp)if not resp.tool_calls:return resp.content # No tool call means convergencefor call in resp.tool_calls:result = tools[call.name](**call.args) # Channel 2: executionmessages.append({"role": "tool","content": str(result),"tool_call_id": call.id})return "Step limit reached; returning current progress"
This is fewer than twenty lines, yet it contains every essential element of an agent: goal input, a context list, a model reasoning channel, a tool execution channel, and a termination condition. “Building it by hand” means gradually thickening this core according to business needs, rather than pulling in a massive dependency tree.
3. Four Engineering Challenges You Must Handle Yourself
1. Context Management: Cost, Latency, and Attention Decay
Context is the scarcest resource for an agent. It is constrained by three things at once: the model’s context window limit, the cost of billing by token, and the drop in decision quality when key information is diluted in a long context. In practice, three techniques are usually combined: a sliding window that keeps the most recent turns; summarization and compression of early content, turning “process” into “conclusions”; and moving stable, unchanging rules to the front of the system prompt to take advantage of prefix caching and reduce repeated overhead. If you connect to a general-purpose large model service that offers context caching, you can further reduce repeated computation of long prefixes.
2. Tool Design: Interface Granularity Sets the Agent’s Ceiling
More tools is not better. A good rule of thumb is to make tool granularity match business actions rather than low-level interfaces, keep parameters few and strongly typed, and control the size of return values while attaching a structured status (success, retryable failure, non-retryable failure). The description text should make clear “when to use it and when not to,” because the model is far more likely to pick the wrong tool than to write a parameter incorrectly. It is best to keep the number of tools within roughly a dozen; beyond that, group them by scenario and inject them dynamically.
3. Error Recovery: Treat Failure as a Normal Branch
In real environments, interface timeouts, parameter validation failures, and insufficient permissions are the norm. A robust agent needs to feed error information back to the model so it can correct itself and retry, while setting a retry limit and a backoff strategy to avoid infinite loops. For irreversible actions (writing data, sending messages, charging fees), you must add a human confirmation or secondary verification step.
4. Observability: No Trace Tracing Means No Maintainability
Every reasoning step and tool call should produce a structured log entry recording the step number, an input summary, elapsed time, token usage, and result status. Combined with general logging services and monitoring and alerting capabilities, this is what lets you quickly pinpoint whether a regression in results is a prompt problem, a tool problem, or model fluctuation.
4. When You Should Not Build Your Own
The cost of building your own must be counted honestly: multi-round collaboration, complex branch rollback, human approval nodes, and cross-agent message passing can often be done with a few dozen lines of configuration in a framework, whereas building your own requires additionally maintaining a state machine and persistence. The decision criteria can be summarized in three points: whether the flow is linear and controllable, whether the toolset is stable, and whether deep coupling with existing systems is needed. When all three are satisfied, building your own yields the greatest benefit; if the requirement is long-term collaboration among multiple roles and frequently changing flow orchestration, adopting a mature solution is more economical.
5. Implementation Advice
First get a single scenario working end to end with the minimal core, then gradually add compression, retries, and tracing; manage prompts, tool definitions, and business code in separate directories under version control; and establish a fixed evaluation set, running success rate and average step count on every change. If you use Baidu AI Cloud’s large models and general cloud capabilities, you can decouple model calls, object storage, logging, and monitoring in layers to avoid binding business logic to infrastructure. To sum up: building an agent by hand in pure Python is not only feasible but, in scenarios with clear flows and high controllability requirements, is the more engineering-oriented choice.
