Building an AI Agent from Scratch in Pure Python: Is It Possible Without a Framework?

    This article explains why building a production-grade AI agent without any orchestration framework is not only feasible but often a better choice. It breaks down the four core components of an agent (state, tool set, loop control, and budget/termination), walks through a minimal ~100-line Python implementation using only the standard library, and identifies six engineering areas you must address to make it production-ready: context management, tool isolation and idempotency, structured output validation, memory and retrieval, observability, and cost and stability. It also covers when not to build from scratch and common pitfalls to avoid.

    1. The Verdict Up Front

    In real engineering projects, building an AI agent without any agent orchestration framework—using only the Python standard library, async capabilities, and a raw LLM API—is not just feasible; in many scenarios it is the better option. The reason is not mysterious: the core abstractions of mainstream agent frameworks have converged. An agent is essentially a loop of “model inference → tool call → result feedback,” plus readable, writable, and prunable state. Frameworks mainly provide scaffolding and ecosystem integrations, but they also introduce abstraction leaks, version drift, and debugging black boxes that often become liabilities once your requirements deviate even slightly from the defaults.

    To be clear, this is not an argument against frameworks. When a team needs to validate ideas quickly, requires many off-the-shelf integrations, or has high member turnover, the convergence benefits of a mature framework are significant. This article describes a different path: when you have higher requirements for behavioral control, observability, and long-term maintainability, how the returns of a hand-rolled core pay off—and what engineering costs you must accept to get there.

    2. Strip the Agent Down to Its Essence

    Setting aside all the marketing talk, a usable agent consists of only four things:

    1. State: a continuously appended message history, plus optional externalized working memory.
    2. Tool set: a group of functions with machine-readable descriptions (usually JSON Schema). The model expresses “I want to call this one, with these arguments” through structured output.
    3. Loop control: parse the model output as either a natural-language reply or a tool call; execute the latter and feed the result back as a new message, repeating until a termination condition is met.
    4. Budget and termination: maximum rounds, maximum tokens, maximum wall-clock time, and maximum tool calls. Hitting any cap forces convergence.

    With these four pieces in place, the agent runs. Everything frameworks do can be mapped onto enhancements of these categories: more complex state machines, richer tool ecosystems, more automatic context compression, and stronger tracing. Understanding this turns “reinventing the wheel” into “implementing only the subset you need.”

    3. A Minimal Viable Kernel: About 100 Lines

    Below is a skeleton with no third-party dependencies. chat_completion is your own wrapper around the LLM API (handling authentication, retries, and timeouts).

    1. import json, uuid
    2. from dataclasses import dataclass, field
    3. @dataclass
    4. class State:
    5. messages: list = field(default_factory=list)
    6. budget: int = 8 # Maximum loop rounds
    7. trace: list = field(default_factory=list)
    8. def register_tools(state, tools: dict):
    9. """tools: name -> (schema, callable)"""
    10. state.tools = tools
    11. def run(state: State, user_input: str) -> str:
    12. state.messages.append({"role": "user", "content": user_input})
    13. for step in range(state.budget):
    14. resp = chat_completion(
    15. messages=state.messages,
    16. tools=[s for s, _ in state.tools.values()],
    17. )
    18. state.trace.append({"step": step, "raw": resp})
    19. calls = resp.get("tool_calls") or []
    20. if not calls:
    21. state.messages.append({"role": "assistant", "content": resp["content"]})
    22. return resp["content"]
    23. state.messages.append({
    24. "role": "assistant", "content": resp.get("content") or "",
    25. "tool_calls": calls,
    26. })
    27. for c in calls:
    28. name = c["function"]["name"]
    29. schema, fn = state.tools[name]
    30. try:
    31. args = json.loads(c["function"]["arguments"] or "{}")
    32. result = fn(**args)
    33. payload = {"ok": True, "data": result}
    34. except Exception as e: # Tool failures must be fed back, not thrown
    35. payload = {"ok": False, "error": str(e)}
    36. state.messages.append({
    37. "role": "tool",
    38. "tool_call_id": c["id"],
    39. "content": json.dumps(payload, ensure_ascii=False),
    40. })
    41. return "Maximum reasoning rounds reached; task not completed."

    This code is worth writing by hand because it makes three things explicit that frameworks often hide: tool exceptions must be fed back as messages (otherwise the model cannot self-correct), the tool_calls in an assistant message must be preserved verbatim (otherwise the API raises a protocol error), and budget exhaustion must converge deterministically.

    4. From Toy to Production: Six Things You Must Add

    The minimal kernel can demo, but it cannot ship. The real work is in the areas below—and they are required regardless of whether you use a framework.

    1. Context Management

    Context is the agent’s scarcest resource. You need a layered strategy: keep recent conversation turns in full; summarize mid-range history (compressing older tool calls and results into a structured summary); retain only conclusive facts for the distant past. Tool results must be truncated. For oversized payloads, use “summary + addressable reference”: store the original payload in object storage and give the model only the address and summary. The criterion is simple: the input size of each request should be predictable, not growing linearly with task duration.

    2. Tool Isolation and Idempotency

    Tools are the agent’s only channel to the outside world, and therefore where risk concentrates. At minimum: give each tool its own timeout and concurrency limit; require idempotency keys for write operations; route high-risk actions (deletion, payments, external publication) through human confirmation or secondary approval; perform parameter whitelisting on the tool side, and never splice model-provided arguments directly into commands or queries. Permission models should follow least privilege, with tool credentials issued per session and revoked promptly.

    3. Structured Output and Self-Validation

    Never trust the model to produce valid parameters on the first try. The approach: when parsing or schema validation fails, feed the validation error back as a tool result and let the model retry, with a retry cap; apply business-level validation to key fields (enums, ranges, cross-field constraints). This turns “format problems” into a feedback loop the model can repair, instead of a hard failure.

    4. Memory and Retrieval

    Short-term memory is the message list; long-term memory needs externalization. In practice: extract facts as entries written to a vector search service or relational storage; at retrieval time, recall by relevance and recency, then inject them as context. Distinguish between “retrievable knowledge” and “facts that must be exact”—the latter belongs in structured queries, not similarity matching.

    5. Observability

    This is the biggest relative advantage of building from scratch: you get access to the full raw data of every step. Generate a trace_id per run and log each round’s prompts, outputs, tool inputs/outputs, latency, and token usage to structured logging, with metrics wired into monitoring and alerting. For evaluation, build an offline test suite covering four scenarios: normal paths, tool failures, invalid parameters, and budget exhaustion. This turns “did my prompt change cause behavioral drift?” into a quantifiable regression.

    6. Cost and Stability

    Include per-request timeouts and an overall budget, exponential backoff for retries, concurrency rate limiting, and model fallback paths (switch to a backup model or return a cached conclusion when the primary model is unavailable). Cache deterministic subtasks, but do not cache reasoning that involves randomness.

    5. When You Should NOT Build from Scratch

    Here is an actionable checklist. If any of the following apply, prefer a mature framework or a platform solution:

    • You need to deliver within days and the integration surface is broad.
    • Your team lacks the willingness or capacity to maintain foundational libraries.
    • Requirements are mainly standard Q&A and document retrieval, with almost no custom loop logic.
    • Compliance requires components audited by a third party.

    Conversely, if the agent’s behavioral logic is the core of your product’s competitiveness, if you need deep customization of loops and state, or if you have hard observability requirements, the marginal returns of building from scratch keep growing.

    6. Common Pitfalls

    • Treating prompts as architecture: stretching behavior control through ever-longer prompts is unsustainable. Behavioral constraints should live in code: budgets, validation, and permissions.
    • Unbounded loops: missing budgets and termination conditions are a leading cause of production incidents.
    • Overly fine-grained tools: tools that are too granular increase round counts and error rates. Divide tools by business action, not by function.
    • Ignoring the feedback protocol: if tool results are not correctly fed back, the model will repeatedly call the same tool in a dead loop.
    • No evaluation set: without one, you cannot tell whether a change is an improvement or a regression, and iteration quickly spirals out of control.

    7. Implementation Roadmap

    Proceed in four steps: first, implement the minimal loop and get two read-only tools working; second, add budgets, validation retries, exception feedback, and logging/tracing; third, integrate memory retrieval and permission control, and build an offline evaluation set; fourth, run load tests and fallback drills before gradually opening up write operations. None of this requires an orchestration framework. The dependency surface stays small, upgrade risk stays low, and the path to root cause when something breaks is as short as possible.

    The feasibility of a hand-rolled agent was never in question. The real question is whether your team is willing to take on the six engineering workstreams above. If you are, you get a transparent, controllable, and long-term evolvable core. If not, a framework remains the more rational choice.