Can You Build an AI Agent From Scratch Without a Framework?
This article explores whether you can build an AI Agent using only a general-purpose programming language, without relying on an existing agent framework. It explains the core structure of an agent (perception, reasoning, action, and learning), why a hand-written approach is viable, and how to design a production-grade system across four layers: tools, model, orchestration, and observability. You will find a minimal core loop, tool abstraction via a registry, model decoupling, debugging and tracing practices, robustness and security safeguards, guidance on when to use a framework versus building from scratch, and a step-by-step roadmap for getting started.
In recent years, AI Agents have become a hot topic in application development. Many introductory tutorials start by pulling in a general-purpose agent framework and running a sample with minimal configuration. This approach lowers the barrier to entry, but in real projects teams often discover that general-purpose frameworks are good for validating ideas quickly, yet not always suited to carrying a production system through long-term evolution. So a practical question arises: if you don’t rely on an existing framework and instead hand-write an AI Agent from scratch using only a general-purpose programming language, is it actually feasible?
The answer is yes. For developers who want to deeply understand how an agent works, building from scratch is in fact a more efficient learning path. The key is not whether you use a framework, but whether you truly understand the core structure of an agent: how it perceives input, how it reasons, how it calls tools, how it records state, how it recovers from failure, and how to make the system observable, extensible, and maintainable.
1. First, Clear Up the Concept: An Agent Is Not a Longer Q&A
When people first work with large model applications, they often think of them as a “smarter chatbot”: the user asks, the model answers. But the key difference between an agent and a single Q&A is that an agent has the ability to act continuously. It not only generates text but also selects tools based on a goal, reads results, revises its plan, and gradually converges on task completion across multiple rounds of interaction.
Four words capture the essence of an agent: perception, reasoning, action, and learning.
Perception is receiving user input, environment feedback, and tool return values; reasoning is deciding the next step based on the current state; action is invoking capabilities such as search, computation, database queries, file processing, and message sending; learning is the set of mechanisms—long-term memory, vector retrieval, feedback optimization—that make the system perform better on future tasks.
In the implementation discussed in this article, the focus is first on the three stages of perception, reasoning, and action. The learning part involves long-term memory and vector retrieval and can be treated as a later extension. As long as the first three steps are solid, a minimal but clearly structured agent is already in place.
2. Why You Can Implement It Without a Framework
The value of a general-purpose agent framework usually lies in packaging common capabilities such as prompt templates, tool calling, state management, memory modules, and workflow orchestration. They significantly reduce boilerplate code and let developers build prototypes faster.
But at the bottom layer, the core runtime logic of an agent is not mysterious. A typical agent loop can be summarized as:
- Receive the current task and historical context;
- Have the model decide whether to answer directly or call a tool;
- If a tool is needed, parse the tool name and arguments;
- Execute the tool and obtain the result;
- Write the result back into the context;
- Repeat the above until the task is complete or a termination condition is reached.
This logic can be implemented with the ordinary capabilities of a general-purpose programming language, including string handling, data structures, asynchronous calls, exception catching, logging, and configuration management. The truly difficult part is not “whether you can write it,” but whether you have a production-grade design: how tools are registered, how the model is decoupled, how errors are recovered, how the process is traced, and how permissions are controlled.
So not using a framework is not “reinventing the wheel.” It turns the agent from a black box into a white box. For learners and teams that need deep customization, this white-box approach is highly valuable.
3. Overall Architecture: Three Core Layers Plus One Observability Layer
A practical hand-written agent should be split into at least four layers: the tool layer, the model layer, the orchestration layer, and the observability layer.
The tool layer is responsible for wrapping external capabilities. Each tool should have a clear name, purpose description, input structure, output structure, timeout policy, and permission boundary. The goal of the tool layer is to let the agent “know what it can do,” and to add new capabilities without changing the core loop.
The model layer handles interaction with different model services. It should not leak vendor-specific details into the agent logic, but instead provide a unified interface—for example, a unified message format, a unified tool description format, and unified error types. This way, using one model service today and switching to another tomorrow only requires replacing the model layer implementation, without rewriting the agent flow.
The orchestration layer is the agent’s brain and commander. It maintains task state, message history, the current step, and tool call records, and controls when the loop continues and when it terminates. The orchestration layer is not responsible for specific tool implementations or specific model details; it only handles scheduling.
The observability layer records the input, output, elapsed time, errors, and state changes of each step. An agent without an observability layer is hard to debug, especially after multiple rounds of tool calls: once a result goes wrong, developers need to quickly locate whether it is a prompt problem, a tool-argument problem, a model-output parsing problem, or an external service timeout.
4. The Core Loop: Explicit Thinking and Explicit Action
One of the most important design principles for a hand-written agent is to make every step explicit. Explicit thinking means the model must output a clear basis for its judgment before calling a tool; explicit action means the model cannot give only a natural-language description but must produce a structured action, such as a tool name and arguments.
A simplified pseudocode looks like this:
state = {"task": user_task,"messages": [],"steps": 0}while state["steps"] < MAX_STEPS:prompt = build_prompt(state)reply = model.generate(prompt)action = parse_action(reply)if action.type == "final":return action.answerobservation = tool_registry.execute(action.tool_name,action.arguments,context=state)state["messages"].append(reply)state["messages"].append(observation)state["steps"] += 1
This logic looks simple, yet it contains the key elements of an agent: context construction, model reasoning, action parsing, tool execution, result write-back, and termination control.
In an actual implementation, special attention must be paid to the robustness of action parsing. The model output may not be strictly structured, so the parser must handle missing fields, wrong fields, repeated calls, illegal tool names, and similar cases. A production-grade agent cannot assume the model always outputs perfect results; it must treat abnormal input as the norm.
5. Tool Abstraction: The Basis of Extensibility
Whether the tool layer is well designed directly determines whether the agent can evolve over the long term. A qualified hand-written agent should be able to add new tools without modifying the core loop.
The registry pattern is recommended. Each tool, when registered, provides a name, description, parameter structure, execution function, and permission requirements. For example:
tool_registry.register(name="search",description="Retrieve public information based on keywords",parameters={"query": "string"},handler=search_handler,timeout=10)
The benefit is that the agent only needs to know “which tools are available,” not the internal implementation of each tool. When adding capabilities such as database queries, file reading, message sending, or image generation, you only need to register a new tool.
Tool design should also follow a few principles:
First, inputs must be validated. Model-generated arguments may have missing fields, wrong types, or dangerous content, and must be verified before execution.
Second, execution must be controllable. Each tool should set a timeout, a retry count, and a maximum output length to avoid one slow interface dragging down the entire agent.
Third, permissions must be minimized. A tool can only access the data and operations necessary to complete the task and must not have excessive permissions by default.
Fourth, results must be serializable. Tool output should be converted to text or structured data so it can be written back into the context.
When the tool layer is well defined, the agent’s extensibility is no longer a slogan but a natural result of the architecture.
6. Model Decoupling: Making the Brain Replaceable
In an agent system, the model is the brain, but the brain should not be forcibly bound to the body. A common reason projects fail is that model-calling details are hard-coded into the business logic, so switching models affects everything.
A more reasonable approach is to define a unified model interface. This interface should at least support: receiving a message list, receiving tool descriptions, returning text or a structured action, and returning error information. The specific differences of different model services are absorbed by the adapters in the model layer.
Model decoupling brings three direct benefits.
First, low replacement cost. Early in a project you can choose one model to validate the flow, then later switch to another based on cost, quality, and latency without affecting the main agent logic.
Second, simpler fallback. When the primary model call fails or times out, the orchestration layer can switch to a backup model or degrade to a simpler handling strategy.
Third, easier testing. In unit tests, you can replace the real model with a mock model to reliably verify the agent loop, tool calls, and exception-handling logic.
7. Debuggability: No Observability, No Production
Many demo-style agents seem to run, but fall apart once they enter real business. The reason is often not that the model isn’t strong enough, but that the system is not observable.
A hand-written agent must design tracing capability from the very beginning. Every loop iteration should record: the current task, historical messages, the model’s raw output, the parsed action, tool arguments, tool returns, elapsed time, error information, and the termination reason.
You can introduce a unified trace ID to link all steps of a task together. When a problem occurs, developers can replay the entire execution process and determine which step it happened in.
In addition, it is advisable to take snapshots of key state—for example, saving fields such as messages, steps, current_tool, and last_error each loop iteration. This not only aids debugging but also lays the foundation for later recovery of interrupted tasks.
Observability is not an add-on; it is the dividing line between an agent that is a toy and one that becomes a production system.
8. Robustness and Security: Must Be Designed in Advance
An agent calls tools, and tools mean real side effects. Therefore, security and robustness cannot be patched on afterward.
First, set a maximum step count. An agent without a step limit may fall into an infinite loop, continuously consuming model calls and tool resources.
Second, add loop detection. If the same tool, the same arguments, and the same error appear for several consecutive rounds, the agent should proactively terminate and return an explainable message.
Third, redact sensitive information. Logs must not contain keys, tokens, user privacy, or similar data. Tool-call arguments and return values should be filtered before being recorded.
Finally, isolate high-risk operations. For actions involving deletion, transfers, publishing, or external writes, introduce a confirmation mechanism or human approval rather than letting the model decide autonomously.
These designs do not make the code complex, but they significantly improve the system’s trustworthiness.
9. When to Use a Framework and When to Hand-Write
Hand-writing an agent does not mean rejecting general-purpose frameworks. A more reasonable judgment is this: if the goal is to build a prototype quickly, validate a general retrieval-augmented flow, or set up a standardized automation workflow, a general-purpose framework can noticeably improve efficiency.
But if the goal is to build a business system that evolves over the long term, with high demands on performance, personalization, robustness, and observability, then designing the core architecture from scratch is often more appropriate. A general-purpose framework provides an average solution, whereas a production system needs a solution tailored to its own scenario.
A practical strategy is to build in-house the core loop, tool protocol, model adaptation, and observability system, while reusing mature industry solutions for common capabilities such as general retrieval and basic workflow orchestration. This avoids reinventing the wheel while preserving control over the key parts.
10. Implementation Roadmap: Start From the Minimal Loop
If you are starting from scratch, it is recommended to proceed in the following order:
Step 1: Implement single-turn Q&A and get the model call working.
Step 2: Add a simple tool, such as computation or retrieval.
Step 3: Implement the loop of “the model outputs an action, the system executes the tool, and the result is written back.”
Step 4: Add a maximum step count, timeouts, and exception catching.
Step 5: Add logging and tracing to ensure every step can be replayed.
Step 6: Abstract the tool registry and the model interface.
Step 7: Then consider long-term memory, vector retrieval, and multi-tool coordination.
The benefit of this path is that each step has a verifiable result, so you don’t get bogged down in a complex architecture from the very start.
Conclusion
Without a general-purpose framework, a purely hand-written AI Agent is not only feasible but also an effective way to understand the engineering essence of agents. What truly determines an agent’s quality is not whether a particular framework is used, but whether it has a clear tool abstraction, a replaceable model layer, a stable reasoning-action loop, a complete observability system, and reliable security boundaries.
Once these core capabilities are mastered, what developers face is no longer a black-box example, but an agent system that can continuously evolve, be deeply customized, and truly be put into production.
