Building AI Agents in Pure Python Without a Framework: A Practical Guide
Can you build a production-grade AI Agent without any orchestration framework? This article breaks an agent down into three core elements—string processing, API calls, and loops—walks through a minimal working implementation in under 50 lines of pure Python, and covers the engineering capabilities you need to add for production, the boundary between framework and framework-free approaches, and common pitfalls to avoid.
Building AI Agents in Pure Python Without a Framework: A Practical Guide
Why This Topic Matters
With the rapid improvement of large language models, building AI Agents capable of autonomous decision-making and multi-step execution has become a popular direction for many teams. The market has responded with a large number of orchestration frameworks offering abstractions such as chained calls, state graphs, and multi-agent collaboration. Yet in real projects, more and more developers are reconsidering a basic question: are these frameworks really necessary?
One notable phenomenon: some major model vendors explicitly recommend in their official best-practice documentation that developers start by calling the model API directly. Most common patterns can be implemented with just a few lines of code, and introducing a framework too early tends to add unnecessary complexity when a simple solution would suffice. Meanwhile, some engineering teams have publicly shared their experience of using a framework in production for a while and then removing it entirely, citing that the abstraction layer increased debugging difficulty and migration cost.
This is not an absolute conclusion, however—official stances differ noticeably across vendors. Rather than getting drawn into the “frameworks: good or bad” debate, this article starts from the technical essence, rationally analyzes where each approach fits, and shows how to implement a pure Python solution.
The Essence of an Agent: Three Core Elements
Strip away the abstraction layers of various frameworks, and the behavioral logic of an AI Agent is remarkably simple. It boils down to three core elements:
- String processing: assembling user input, system prompts, conversation history, and tool results into request content that matches the model API format.
- API calls: sending requests to the LLM service and receiving generated text or structured tool-call instructions.
- Loops: parsing the model’s output, executing the corresponding action, feeding the result back to the model, and repeating until the task is complete.
These three things happen to be exactly what Python does best. String operations from the standard library, HTTP requests via requests/httpx, and a while loop—any developer can write these correctly. In a real sense, most of the “engineering secret” of LLM applications is hidden inside this perceive–decide–act loop.
A Minimal Working Agent
The following is a minimal Agent in under 50 lines, with no third-party framework. It provides a complete closed loop: system prompt, tool registration, model decision parsing, tool execution, and result feedback.
import jsonfrom openai import OpenAIclient = OpenAI()# 1. Define toolsdef get_weather(city: str) -> str:return f"{city}: sunny today, 15-25°C"def search_docs(keyword: str) -> str:return f"Retrieving document snippets related to '{keyword}'..."TOOLS = {"get_weather": (get_weather, "Query the weather of a given city", {"type": "object","properties": {"city": {"type": "string"}},"required": ["city"],}),"search_docs": (search_docs, "Search internal documents", {"type": "object","properties": {"keyword": {"type": "string"}},"required": ["keyword"],}),}# 2. Main loopdef run_agent(user_input: str, max_turns: int = 10):messages = [{"role": "system", "content": "You are an assistant with tools available. Call tools when necessary, then integrate the results into your answer."}]messages.append({"role": "user", "content": user_input})tool_schemas = [{"type": "function", "function": {"name": n, "description": d, "parameters": p}}for n, (f, d, p) in TOOLS.items()]for _ in range(max_turns):resp = client.chat.completions.create(model="model-name", messages=messages, tools=tool_schemas)msg = resp.choices[0].messageif msg.tool_calls:messages.append(msg)for tc in msg.tool_calls:fn, args = tc.function.name, json.loads(tc.function.arguments)try:result = TOOLS[fn][0](**args)except Exception as e:result = f"Tool execution failed: {e}"messages.append({"role": "tool","tool_call_id": tc.id,"content": str(result),})else:return msg.content # No tool calls; return the final answerreturn "Maximum reasoning turns reached; task not completed."print(run_agent("Is today good for an outdoor run in Beijing?"))
This code covers the core mechanics of an Agent:
- Tool registration and schema description: a dictionary maintains functions, descriptions, and parameter JSON Schemas, making it easy to add new tools.
- Decision parsing: if the model returns
tool_calls, execute the tools; otherwise, output the answer directly. - Result feedback: tool results are fed back according to the protocol, allowing the model to continue reasoning.
- Safety guardrails:
max_turnsprevents infinite loops, and exception handling prevents a tool crash from taking down the entire flow.
From Demo to Production: Engineering Capabilities to Fill In
A minimal implementation runs, but going to production requires building out the following capabilities yourself:
1. Context and state management
Long conversations quickly exhaust the context window. You need strategies such as history compression, key-information summarization, and sliding-window truncation. Compared with a framework’s built-in Memory abstractions, a homegrown solution lets you do more precise memory filtering tailored to your business data structures.
2. Checkpointing and recoverability
Long-running tasks may run for hours, and a mid-way crash shouldn’t force a restart from scratch. You can serialize the message list after each turn and persist it (to a database or file), then load the latest snapshot after a crash and continue. This is a core selling point of state-orchestration frameworks, but since message history is naturally serializable, implementing it yourself is not complicated.
3. Human-in-the-loop checkpoints
For high-risk actions (such as sending external emails or submitting approval requests), you can insert a confirmation step into the loop: pause when a specific tool is detected and wait for human approval before executing. This takes just a few dozen lines of code.
4. Observability
Log structured records of every turn’s model requests, tool calls, latency, and token consumption, and connect them to your logging service and monitoring/alerting system. This is the lifeline for troubleshooting abnormal Agent behavior. Key state changes of an Agent should be replayable—otherwise, when “weird output” appears, you have almost nothing to go on.
5. Concurrency and cost control
When multiple Agents run in parallel, you need unified rate limiting, retry with backoff, and budget circuit breakers to prevent one runaway loop from burning through your entire token budget.
Where Each Approach Fits
Based on practical experience, here is a relatively neutral decision framework:
When a pure Python approach fits:
- The Agent workflow is fairly linear with a limited number of tools (a dozen or fewer);
- The team needs strong customization of scheduling logic and wants full control over loop details;
- Troubleshooting efficiency matters, and you don’t want to dig through a framework’s abstraction stack;
- The service is sensitive to dependency size and startup speed.
When a framework fits:
- The workflow involves complex branching, loops, or multi-agent collaboration topologies;
- You frequently switch between multiple model providers and value a unified interface layer;
- Rapid prototyping takes priority over long-term maintenance;
- The team is small and framework experience is reusable.
A pragmatic piece of advice: if you’re unsure, first implement the core loop in pure Python—turn-based decisions, tool execution, and message management—clearly. Only when you genuinely need advanced capabilities such as state graphs, conditional edges, or checkpointing, and the cost of building them yourself is too high, should you evaluate introducing an orchestration layer. Migrating from a framework to bare code is far more expensive than going the other direction.
Common Pitfalls and Recommendations
- The prompt is the program: the robustness of an Agent’s behavior depends mainly on the quality of the prompts and tool descriptions, not the framework. Vague tool descriptions cause the model to call tools incorrectly, which is harder to debug than any code bug.
- Don’t blindly chase multi-agent architectures: multi-agent collaboration significantly amplifies uncertainty. Most business scenarios are well served by a single Agent with a clear tool set.
- Parse JSON defensively: structured parameters output by the model are not 100% valid. You must tolerate errors and guide retries.
- Test-driven development: prepare a regression test suite for typical task paths, and run it in bulk after every prompt or tool change to prevent unintended regressions.
Conclusion
The engineering core of LLM applications is not complicated: string processing, API calls, and loops—native Python capabilities cover it all. Frameworks provide “abstractions that someone else has already orchestrated.” They can accelerate your start, but they can also become a debugging nightmare and a constraint on flexibility. The real basis for your decision is not community hype, but the complexity of your task, your team’s need for control, and long-term maintenance cost. Teams that thoroughly understand every loop of their Agent are more likely to build reliable production systems—whichever route they choose.
