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

    This article breaks down what an AI agent actually consists of and shows that its core loop requires only standard Python capabilities, not a framework. You will find a minimal working skeleton, the engineering essentials for structured output, context management, tool security, layered memory, and evaluation, plus guidance on when a hand-written agent is the better choice and when a mature framework pays off.

    1. Define the Problem First: What an Agent Actually Is

    Before asking whether you can skip a framework, you need to reduce the agent from a concept back to an engineering structure. An agent, as the industry generally understands it, is essentially a state machine with a loop: it receives external input, calls a model to reason, produces a structured decision, then executes an action when conditions are met, writes the result back into the context, and starts the next round of reasoning until a termination condition is hit.

    Break that loop apart and it contains only five things:

    1. Context assembly: combine system constraints, conversation history, retrieved material, and the tool list into a single request.
    2. Model reasoning: the large model outputs a structured decision (answer, call a tool, request clarification, or finish).
    3. Action execution: parse the decision, validate parameters, and call a local function or an external API.
    4. State write-back: trim and summarize the action result, then append it to the context.
    5. Termination check: exit the loop based on a step limit, confidence, a task-completion signal, or human intervention.

    The conclusion is straightforward: none of these five things is framework-exclusive at the language level. They map to string handling, JSON parsing, function calls, list operations, and conditionals, all of which are standard library capabilities. What a framework really provides is the engineering shell, such as node orchestration, state persistence, visual debugging, and multi-agent collaboration, not the source of the capability.

    2. The Minimal Working Skeleton: One Loop and One Tool Table

    The code below is illustrative. It strips away every dependency and keeps only the skeleton logic. Its value is not feature completeness but showing where the complexity really lands.

    1. import json, os
    2. from typing import Callable
    3. TOOLS: dict[str, Callable] = {}
    4. def tool(name: str):
    5. def deco(fn: Callable):
    6. TOOLS[name] = fn
    7. return fn
    8. return deco
    9. @tool("get_weather")
    10. def get_weather(city: str) -> str:
    11. return f"{city} sunny, 26C" # In a real project, replace with a controlled external call
    12. def run_agent(user_input: str, max_steps: int = 8) -> str:
    13. messages = [
    14. {"role": "system", "content": "You are an assistant. When external data is required, output JSON: "
    15. "{\"tool\":name,\"args\":{}}; otherwise output {\"answer\":text}."},
    16. {"role": "user", "content": user_input},
    17. ]
    18. for _ in range(max_steps):
    19. raw = call_model(messages) # one model request
    20. decision = json.loads(raw)
    21. if "answer" in decision:
    22. return decision["answer"]
    23. fn = TOOLS[decision["tool"]]
    24. result = fn(**decision["args"])
    25. messages.append({"role": "assistant", "content": raw})
    26. messages.append({"role": "user", "content": f"Tool returned: {result}"})
    27. return "Maximum steps reached; task not completed."

    This code exposes where the real work sits in a hand-written approach: model calls and retries, structured output parsing, tool registration and parameter validation, context trimming, and logging and tracing. None of it is hard, but you have to write all of it yourself, which is exactly what “feasible but not free” means.

    3. Engineering Essentials for the Five Core Modules

    3.1 Structured Output and Fault Tolerance

    Having the model output JSON is the mainstream approach, but in production you must assume it will fail. Reliable strategies include: state the field contract with a few examples in the prompt; retry once with the error message on a parse failure; validate tool names against a whitelist and validate parameters for type and range; return a readable error for an unknown tool instead of raising an exception. The validation failure message is itself a correction signal for the model, a point that is often overlooked.

    3.2 Context Management and Cost

    Context is a limited and billed resource. The usual engineering approach is layered: system constraints stay resident; recent conversation is kept in full; older history is compressed into summaries; retrieved material is injected on demand and labeled with its source. Set a step limit and a per-round token limit to keep the loop from running out of control. Caching the invariant prefix can significantly cut repeated cost, which is also a common billing dimension in the model inference category of general cloud services.

    3.3 Security Boundaries for the Tool Layer

    Tools are the only channel through which an agent truly affects the outside world, so permissions must be minimal: write operations require explicit confirmation or a second check; external requests set timeouts and retry limits; sensitive credentials are injected through environment variables or a key management service and never enter prompts or logs; all tool calls are recorded so they can be replayed and traced.

    3.4 Layered Memory Design

    Short-term memory is the context window; long-term memory usually lives in vector retrieval or a structured database. The key design questions are what to write and what to retrieve: deduplicate and summarize before writing, rank by a mix of relevance and recency at retrieval time, and truncate recalled content by length. More memory is not better; noisy memory noticeably degrades decision quality.

    3.5 Observability and Evaluation

    An agent without evaluation cannot be iterated. The minimal loop is: log the input, decisions, tool parameters, returns, and latency for every run; build a test set of 20 to 50 cases covering typical and boundary scenarios; run a regression pass after each prompt or tool change and compare task success rate and average steps. Prioritize success rate and step count over whether an answer “looks good.”

    4. When Not to Write It by Hand

    The cost of the hand-written approach is that you take on orchestration, retries, concurrency, state persistence, and visual debugging yourself. When requirements involve complex branching orchestration, multi-role collaboration, long-running task recovery, or collaborative debugging across a team, the marginal benefit of a mature framework quickly exceeds the cost of building your own. Conversely, when the chain is short, the number of tools is limited, latency and cost are sensitive, and you need deep customization of prompts and tracing fields, hand-writing is lighter, more transparent, and easier to pass a security review.

    A pragmatic middle ground: build the core loop yourself, hand logging, metrics, and distributed tracing to general logging services and monitoring and alerting capabilities, hand vector retrieval and file persistence to object storage and managed database categories, containerize and deploy on a container platform, and use a message queue to handle asynchronous long-running tasks. This keeps control while avoiding reinventing the wheel.

    5. Conclusion

    Building an agent in pure Python is not only feasible; it is the better choice in scenarios where the chain is controllable, dependencies are minimal, and cost is predictable. The real barrier is not whether you can write it, but whether you are willing to fill in the four pieces of engineering groundwork: fault tolerance, context governance, permission boundaries, and an evaluation loop. Get the loop working in a few dozen lines of code first, then bring in external capabilities step by step as pain points appear; that is the lowest-risk path forward.