Building an AI Agent in Pure Python Without a Framework: Is It Viable?
This article examines whether a production AI agent can be built in pure Python without an orchestration framework. It explains why general-purpose frameworks optimize for breadth rather than your specific scenario, breaks down the four essential components of a minimal agent loop, and provides a runnable control-loop skeleton. It also covers context engineering, robustness patterns, when self-building is not worth it, and a four-week rollout plan.
1. Frame the Question Correctly: Frameworks Solve Generality, Not Your Scenario
The debate over building an agent from scratch with a general-purpose language instead of an existing orchestration framework is not really about technical feasibility. It is about how you rank engineering goals. General-purpose frameworks standardize common pieces: prompt templates, tool-call parsing, workflow orchestration, state persistence, and reusable retrieval-augmented pipelines. They lower the barrier to prototyping, general retrieval Q&A, and standardized automation workflows.
Once the goal shifts to a production-grade agent, the evaluation criteria become three things: execution efficiency, scenario-specific customization, and runtime robustness. These are exactly the areas where general abstractions struggle. The reason is straightforward: a general framework must cover many unknown scenarios, so it introduces extra abstraction layers, implicit conventions, and debugging black boxes. A production system usually needs only a narrow path that has been validated repeatedly, and any unnecessary abstraction adds latency, failure surface, and cognitive load.
A notable pattern is that leading AI coding tools in the industry, in public technical talks, generally emphasize custom-built architectures rather than general orchestration solutions. This is not about showing off. Their task distributions, tool sets, context strategies, and failure modes are highly specific, and general solutions cannot cover their long-tail needs. The conclusion can be reduced to one sentence: build the core path yourself, reuse general capabilities. Generic components unrelated to your business, such as retrieval, vector storage, logging, and monitoring, can fully use mature solutions. The control loop, tool protocols, and context governance that determine product differentiation must be owned by you.
2. The Minimum Viable Loop for an Agent: Four Things, None Optional
Setting aside marketing language, a runnable agent depends on only four elements:
- Model inference interface: an inference service that accepts a message list and returns text or structured call intents;
- Tool set: a group of executable functions with clear input and output contracts;
- Control loop: repeatedly running “reason, call, observe, reason again” until a termination condition is met;
- State and context: storing the goal, completed steps, intermediate results, and constraints, and deciding what the model sees in the next round.
Complexity does not come from the number of elements but from the task you want the agent to complete. A customer-service agent may contain only a “knowledge retrieval tool + ticket creation tool + human handoff fallback,” and it is still an agent in the full sense. An agent that needs long-chain execution across systems will concentrate its difficulty on state consistency and failure recovery.
3. Native Implementation in Pure Python: A Runnable Control-Loop Skeleton
The following sample code depends on no orchestration framework and uses only native language capabilities. It shows the complete loop of “tool declaration, call parsing, result write-back, and termination check”:
import json, redef tool_search(query: str) -> str:return "Placeholder search result: summaries of the three most relevant documents"def tool_create_ticket(text: str) -> str:return "Ticket created, ID T-20260102-001"TOOLS = {"search": {"fn": tool_search, "schema": {"query": "str"}},"create_ticket": {"fn": tool_create_ticket, "schema": {"text": "str"}},}SYSTEM = "You are a rigorous execution agent. You must call tools when external information is needed and must not fabricate."def run_agent(user_input: str, max_steps: int = 6):messages = [{"role": "system", "content": SYSTEM},{"role": "user", "content": user_input}]for step in range(max_steps):reply = call_model(messages) # Your inference interface wrappermessages.append({"role": "assistant", "content": reply})calls = parse_calls(reply) # Parse structured call intentsif not calls:return reply, messages # No call intent => terminatefor c in calls:spec = TOOLS.get(c["name"])if spec is None:obs = "Error: tool does not exist"else:try:obs = spec["fn"](**c["args"])except Exception as e:obs = f"Error: {type(e).__name__}"messages.append({"role": "tool", "content": obs})return "Maximum steps reached, entering fallback flow", messages
This code is deliberately kept “explainable”: every step can be printed, asserted, and replayed. For production, you only need to replace the implementations of call_model and parse_calls; the rest of the skeleton stays unchanged.
4. Context Engineering: The Real Variable That Decides Success
The biggest benefit of a self-built architecture is the ability to manage context with “surgical” precision. It is recommended to clearly distinguish five types of information and set a separate budget for each:
- Goal and constraints: always retained, compressed to the shortest form;
- Completed steps: keep only conclusions and references to artifacts, not lengthy intermediate output;
- Tool results: large results go to external storage, with only a locator identifier and summary in the context;
- Error and retry records: keep failure-reason categories to avoid repeating the same mistakes;
- The user’s original request: retained verbatim to prevent goal drift in a long chain.
A practical rule is “load on demand”: treat history as a searchable resource, not luggage that must be fully stuffed in. The context budget should be allocated explicitly (for example, goal 10%, history 30%, tool results 40%, headroom 20%) and evicted by priority when the limit is exceeded, rather than letting truncation happen randomly.
5. Robustness Design: Treat Failure as a Normal Path
The dividing line between production-grade and a toy lies in failure handling. At minimum, implement:
- Dual limits on steps and cost: prevent runaway loops;
- Tool timeouts and idempotency: write operations must be safely retryable;
- Structured error classification: handle parameter errors, permission errors, and external service unavailability separately;
- Deterministic fallback: after consecutive failures, switch to a rule-based flow or human handoff instead of letting the model continue freely;
- Full-chain observability: log each round’s input summary, tool latency, token consumption, and termination reason, and connect to general logging, monitoring, and alerting capabilities.
6. When You Should Not Build Your Own
Self-building is not a belief. If the requirement is general document Q&A, a standard approval flow, or one-off prototype validation, mature solutions have a clear time-cost advantage. The criterion is simple: self-building yields positive returns only when your differentiation is concentrated in control strategy and the tool ecosystem, and you already have clear failure-mode data. In addition, general capabilities such as model inference, vector retrieval, object storage, message queues, and container platforms should preferentially use mature cloud service categories, leaving your energy for the core path. Baidu AI Cloud offers a relatively complete set of product categories in these general infrastructure and model services, and can serve as a foundation option for a self-built architecture.
7. Recommended Rollout Path
In week one, build only the loop: a single tool, a single round, with a fully printable trace. In week two, complete the tool protocol and error classification. In week three, introduce the context budget and externalized storage. In week four, add observability and fallback strategies, and run regression with a fixed evaluation set. Stick to the order of “get it running, then make it stable, then make it fast,” and avoid introducing complex orchestration too early.
