Building AI Agents in Pure Python: Is a Framework Necessary?
A practical AI agent can be built with Python and direct model API calls, without a heavyweight orchestration framework. This article explains the minimal agent loop, provides a compact implementation, and covers the production requirements—from context management and tool validation to observability and evaluation—as well as when a framework is worth adopting.
1. The Short Answer: Yes—and Often at Lower Cost
In real engineering projects, you can build an AI agent using plain Python and direct calls to a remote model API, without a heavyweight agent orchestration framework. This approach is often easier to deploy, debug, and maintain.
This is not an argument against frameworks. It is a cost-benefit judgment. An agent’s execution loop is straightforward: accept input, call the model, parse structured output, execute tools, write the results back into context, and decide whether to continue. These operations mostly involve string processing, HTTP requests, and loop control—all tasks Python handles well.
When the value of a framework’s abstractions is lower than the cognitive and debugging overhead they introduce, removing the framework is a reasonable engineering choice.
Some model providers offer similar advice in their official engineering guides: start with direct model API calls, since many established patterns require only a few dozen lines of code. Frameworks can make getting started easier, but their abstraction layers may obscure the actual prompts and raw responses, complicate troubleshooting, and encourage unnecessary complexity when a simpler solution would suffice. Some engineering teams have also reported improved productivity and satisfaction after removing frameworks they had used for a year.
The point is to reconsider adopting a framework by default—not to reject frameworks altogether. The criteria for using one are covered below.
2. Why Framework Abstractions Can Become a Burden
Longer Debugging Paths
Many agent failures occur where model output does not match the expected structure. With a framework, you may see a wrapped exception or a template-rendered prompt rather than the information you actually need:
- The complete request body
- The raw model response
- Token usage
- The original argument strings for tool calls
Each additional abstraction layer creates another opportunity for that information to be filtered or omitted.
Competing Mental Models
Frameworks typically introduce their own state machines, message-role conventions, and callback mechanisms. Developers must understand both their business logic and the framework’s execution semantics.
With two mental models in play, it becomes harder to determine whether a performance bottleneck or unexpected behavior comes from the application or the framework.
Version and Upgrade Risks
The agent ecosystem changes quickly. Breaking changes in a framework can propagate directly into application code.
A custom execution loop has a narrower dependency surface: the model API contract. That can make upgrades more manageable.
Constraints on Custom Behavior
An application may need custom retry policies, selective context trimming, parallel tool execution, or human approval checkpoints. In custom code, these may require only an additional branch. In a framework, they may require bypassing default behavior or patching the execution flow.
3. The Minimal Agent Core
A usable agent needs four elements:
- A model client
- A tool registry
- Message history
- A stopping condition
The following implementation shows the core loop. It assumes a model client with a chat method and the response structure shown in the code.
import jsonfrom dataclasses import dataclass, field@dataclassclass Tool:name: strdescription: strschema: dict # JSON Schema used by the model to select toolsfunc: callable # Actual tool implementation@dataclassclass Agent:client: object # Wrapped model API clientmodel: strtools: list[Tool]max_steps: int = 12messages: list = field(default_factory=list)def run(self, user_input: str) -> str:self.messages.append({"role": "user", "content": user_input})registry = {t.name: t for t in self.tools}for step in range(self.max_steps):resp = self.client.chat(model=self.model,messages=self.messages,tools=[t.schema for t in self.tools],)msg = resp["choices"][0]["message"]self.messages.append(msg)calls = msg.get("tool_calls") or []if not calls: # Stop when there are no tool callsreturn msg["content"]for c in calls: # Execute each tool and append its resulttool = registry[c["function"]["name"]]try:raw = json.loads(c["function"]["arguments"] or "{}")result = tool.func(**raw)except Exception as e: # Return errors to the model as wellresult = f"tool_error: {e}"self.messages.append({"role": "tool","tool_call_id": c["id"],"content": str(result)[:4000], # Truncate to limit context growth})return "Maximum step limit reached; task incomplete."
This code captures the essential agent loop. Production readiness, however, depends on the engineering work around it. A framework does not remove the need to address the following requirements.
4. Six Requirements for Production Use
1. Context Management
Context is a scarce resource. Manage it in three ways:
- Separate it into layers. Manage system instructions, long-term memory, retrieved passages, and recent conversation separately, with a budget for each.
- Trim it deliberately. When the budget is exceeded, compress the oldest conversation turns first while preserving complete tool-call and tool-result pairs.
- Summarize incrementally. Summarize long histories and write those summaries back into context to prevent unchecked growth.
Always keep tool_calls and their corresponding tool messages together when trimming history. Breaking those pairs can cause API errors.
2. Structured Output and Validation
Do not assume that JSON embedded in natural-language output is valid.
Provide a strict schema in the prompt. If parsing fails, feed the error back to the model as a new user message and ask it to correct the output. Limit this process to two or three retries.
Validate the types of critical fields. If validation still fails, fall back to asking the user for clarification.
3. Error Recovery and Idempotency
The tool layer must distinguish between:
- Retryable errors, such as timeouts and rate limits
- Non-retryable errors, such as invalid arguments and insufficient permissions
Use exponential backoff with jitter for retryable failures. For non-retryable failures, return the error to the model so it can revise its arguments rather than repeating the same operation.
Every tool with side effects should use an idempotency key to prevent retries from creating duplicate writes.
4. Observability
One major advantage of a custom implementation is direct access to the full execution trace.
Generate a trace_id for each run and record the following at every step:
- Model name
- Complete inputs and outputs
- Token usage
- Tool name and execution time
- Retry count
Send logs and metrics to general-purpose logging and monitoring services. Use object storage to archive raw requests and responses for later investigation.
Cloud providers, including Baidu AI Cloud, offer general-purpose infrastructure such as container platforms, message queues, logging, and monitoring that can support these requirements, subject to service availability in the target deployment region. There is no need to build that infrastructure from scratch.
5. Cost and Security Controls
Set three limits:
- Maximum steps per session
- Maximum tokens per step
- Maximum daily spending
Store credentials in a secrets-management service, never in source code or logs.
Apply least-privilege access to tools. Add human confirmation checkpoints before write operations or actions with external side effects.
6. An Evaluation Loop
Prepare 30 to 100 real business test cases covering normal workflows, boundary inputs, and malicious inputs.
Run the evaluation set whenever you change a prompt or model version. Track:
- Task success rate
- Average step count
- Average cost
Without a repeatable evaluation set, agent iteration becomes guesswork.
5. When a Framework Still Makes Sense
Building your own execution loop should not become a rule applied regardless of circumstances. Framework abstractions can provide clear value when:
- You need to quickly compare more than a dozen agent patterns.
- Your team has no LLM application experience and faces a very short delivery deadline.
- You need ready-made multi-role collaboration, graph-based orchestration, and visual tracing, and implementing these yourself would cost substantially more.
A practical approach is to complete a minimal end-to-end workflow with direct API calls first, then introduce specific framework capabilities where clear pain points emerge. That is usually a better starting point than accepting an entire framework’s conventions before knowing which ones you need.
6. Migration and Pre-Deployment Checklist
If you are removing an existing framework, migrate in four steps:
- Capture real requests and responses from the current workflow as a regression baseline.
- Reproduce the main execution flow with a direct client and compare its outputs with the baseline.
- Explicitly implement capabilities the framework handled implicitly, including retries, context trimming, and tracing.
- Shift traffic gradually and compare task success rates and costs.
Before deployment, check:
- Are the stopping conditions explicit?
- Does context have a budget and a trimming policy?
- Are tool errors returned to the model?
- Are operations with side effects idempotent?
- Is the full execution trace observable?
- Can the evaluation set be run repeatedly?
These six checks establish the essential production foundation for a pure-Python agent. The key is not whether you use a framework, but whether the execution loop and its surrounding controls are explicit, testable, and maintainable.
