Can You Build an AI Agent in Pure Python Without a Framework?

    This article examines whether a working AI agent can be built in pure Python without an orchestration framework. It breaks an agent down to its minimal loop, shows a roughly forty-line skeleton using only the standard library, and then walks through the parts that actually take effort: context management, tool definitions with type constraints, self-built reliability and observability, and a layered evaluation system. It closes with clear signals for when adopting a framework makes sense.

    1. Ask the Right Question First: What Does a Framework Actually Solve

    Most debates about hand-writing agents without an orchestration framework are not about capability. They are about the level of abstraction. To judge feasibility, start by reducing an agent to its minimal loop: receive input, assemble context, call the model, parse structured output, execute tools, write results back into the context, decide whether to continue. Only three things in that loop are truly irreducible: string handling, API calls, and loop control. All three are native capabilities of any general-purpose language.

    The value of a framework is bundling those three things together with retries, state persistence, concurrency, and observability. When requirements are highly standardized, the bundle saves time. When requirements start to diverge, the bundling layer becomes an extra system you have to understand. Some teams have removed heavy orchestration after using it in production for a long time, and the feedback clusters around two points: longer debugging paths and slower iteration. A leading model vendor’s official guidance also recommends starting from direct calls to the model API and introducing abstractions only as needed. So the position here is not “frameworks are useless.” It is: start with a zero-dependency implementation by default, and treat the framework as a replaceable implementation detail rather than the architectural foundation.

    2. The Minimal Working Loop: A Skeleton Under Fifty Lines

    A runnable agent needs no third-party dependencies. The standard library plus one HTTP client is enough:

    1. import json, urllib.request
    2. def call_model(messages, tools):
    3. body = json.dumps({"messages": messages, "tools": tools}).encode()
    4. req = urllib.request.Request(API_URL, data=body,
    5. headers={"Content-Type": "application/json"})
    6. with urllib.request.urlopen(req, timeout=60) as r:
    7. return json.loads(r.read())
    8. def run_agent(goal, tools, max_steps=12):
    9. messages = [{"role": "user", "content": goal}]
    10. for _ in range(max_steps):
    11. resp = call_model(messages, tools)
    12. msg = resp["message"]
    13. messages.append(msg)
    14. if not msg.get("tool_calls"):
    15. return msg["content"]
    16. for call in msg["tool_calls"]:
    17. result = dispatch(call["name"], call["arguments"]) # local function table
    18. messages.append({"role": "tool", "content": str(result)})
    19. return "Step limit reached; returning current progress"

    This code already covers the full capability set: multi-turn tool calls, a termination condition, and a step-limit circuit breaker. All later engineering work adds to these forty lines rather than starting over.

    3. Context Management Is the Real Difficulty

    The cost of a hand-written approach is not “calling the model.” It is context governance. Four things must be handled explicitly. First, budget: estimate by characters or tokens and reserve room for output. Second, trimming strategy: usually keep the system instructions, the most recent turns, and facts explicitly marked as critical. Third, compression: replace long early tool results with summary entries. Fourth, externalize structured memory: put long-term facts in object storage or a database, then retrieve and backfill them by relevance when needed. Writing these as standalone functions means the strategy can be unit-tested, canary-released, and swapped per business case. Most frameworks hide trimming logic internally, which makes replacement expensive.

    4. The Tool Layer: Type Constraints Instead of Magic

    A tool description is essentially API documentation written for the model. The recommended practice is to declare parameters with type annotations and docstrings, then generate the structured description automatically, avoiding drift between the docs and the implementation:

    1. def query_order(order_id: str) -> dict:
    2. """Query order status and logistics milestones by order ID."""
    3. ...

    Also hold three lines of discipline: tool granularity should align with business actions rather than technical interfaces; all tool results should be a uniform serializable structure; write operations must carry an idempotency key and a human-confirmation flag. The more tools there are, the higher the wrong-selection rate, so tools should be grouped by scenario and loaded on demand rather than all exposed at once.

    5. A Self-Built Checklist for Reliability and Observability

    No framework means you fill in observability yourself, but this is also the part with the most control. Instrument every model call and tool execution, recording latency, token usage, and termination reason. Apply exponential backoff with an upper bound to API errors. When structured parsing of model output fails, do a second repair pass instead of throwing directly. Serialize session state and write it to a message queue or logging service to enable resume-from-breakpoint. In production, this self-built instrumentation usually fits business definitions better than a framework’s built-in dashboard.

    6. Evaluation: No Evaluation, No Iteration

    Build three layers of evaluation. The unit layer validates tool functions. The scenario layer uses a fixed case set to compare success rate and step count across different prompts and trimming strategies. The regression layer runs a baseline after every change to prevent experience regressions. Metrics should include at least task success rate, average step count, failure-type distribution, and cost per task. The evaluation set should be continuously supplemented with real failure cases, which drives quality more than any abstraction layer.

    7. When to Introduce a Framework

    When a team needs to validate quickly, scenarios are highly homogeneous, and the team is willing to accept a given abstraction, adopting a mature orchestration solution is rational. The signals are clear: if you find yourself repeatedly rewriting the same state machine, retry, and persistence logic, the abstraction is already paying off. Conversely, if the core logic is still changing frequently, zero-dependency hand-writing is faster.

    8. Conclusion

    Hand-writing an agent in pure Python is not only feasible; it has structural advantages in controllability, debugging efficiency, and cost transparency. The suggested path: first write the forty-line loop and get the business working, then add context governance, tool conventions, observability, and an evaluation system in order, and only then introduce external abstractions as needed. If you need to handle high concurrency and long-running tasks, general capabilities on Baidu AI Cloud such as container platforms, message queues, object storage, and monitoring and alerting can absorb the runtime and operational load, keeping business code thin.