Building Reliable AI Agents from Scratch Without an Orchestration Framework
You can build a production-grade agent with a general-purpose language and an LLM API, but the hard part is reliability: validation, permissions, idempotency, budgets, and evaluation—not the agent loop itself. This article covers when you actually need an agent, a five-module architecture, a bounded control loop, tool-safety design, failure recovery, context and cost control, and testing.
1. Building an agent from scratch is feasible—engineering cost is not optional
Can you ship a usable agent without a dedicated agent framework, using only a general-purpose language and an LLM API?
Yes. More precisely: the core control loop is simple; reliability in production is the real difficulty.
An agent typically closes a loop: accept a goal, understand context, choose the next action, call tools, read results, and decide whether the task is done. That can be ordinary functions, loops, branches, and state—not a framework.
Writing it yourself is not only about fewer dependencies. When task boundaries are clear, tools are few, and business constraints are strict, explicit control logic is easier to review and debug, and it keeps permissions and rules in the application where they belong.
That does not mean “hand-rolled is always better.” If you need framework-style state machines, debugging, and persistence, you still have to provide them. Choosing a custom implementation means owning that infrastructure.
2. First: does the business need an agent?
Before you write a loop, distinguish three kinds of system.
1. A single model call
If the job is summarization, classification, or extraction with no external systems, one call is enough. An agent loop adds latency, cost, and failure modes without benefit.
2. A fixed workflow
If the order is known—“read material, extract fields, validate format, generate a report”—use a deterministic workflow. The model can participate in a step without owning the whole flow. Fixed steps are predictable, testable, and easier to cover for errors.
3. A dynamic agent
An agent pays off when the next action depends on previous results. For example, diagnosing a business incident may mean querying records, filling missing fields with extra retrieval, then assembling evidence. The model must choose the next action from current information, not follow a preset script.
Use deterministic logic wherever you can; open agent choice only where dynamic selection is required.
3. Minimal architecture: five modules
A maintainable implementation splits into five parts.
1. Model adapter
The adapter sends requests, receives responses, and maps vendor payloads into internal types. Business code should not depend on raw API shapes. Internally, distinguish three outcomes: final answer, tool request, and call error. Swapping providers then mostly changes the adapter.
The adapter should handle timeouts, malformed responses, and usage accounting. For streaming, parse a complete tool request before executing tools; do not apply side effects from partial fields.
2. Tool registry and execution
Tools are business capabilities: query records, search documents, compute aggregates, submit items for approval.
Each tool should describe at least:
- purpose and scope
- required parameters and types
- result shape
- possible errors
- whether it mutates external state
- permissions and execution limits
The model may only request a call. Lookup, validation, auth, and execution belong to the application.
3. State management
State is more than chat history: task id, stage, steps taken, tool results, remaining budget, approval status.
Prototypes can keep state in memory; long-running or cross-process work needs persistence. Design for resume after recovery, not just “we stored all the text.” Distinguish not started, in flight, and completed but not yet written back.
4. Control loop
The loop decides when to call the model, run tools, stop, and handle failures. It is the core of a custom agent, but it need not be large. Keep business rules in separate modules; do not pile model calls, permission checks, retries, and logging into one loop.
5. Observability and audit
Record each step: time, input summary, tool name, result, error type, resource use. Use this for debugging, security audit, and incident tracing. In production, redact logs and restrict access and retention.
4. Express the agent as a bounded loop
Illustrative pseudocode for control flow, not a real API:
initialize task stateset max steps, deadline, and resource budgetloop:if steps, deadline, or budget exceeded:return a controlled terminationbuild model input from current stateget and parse model outputif output is a final answer:check required evidence and completion conditionsreturn the answer or enter follow-up handlingif output is a tool request:check the tool is on the allowlistvalidate parameter types and business constraintsverify the current user may execute itif the operation needs approval:persist statereturn pending-approvalexecute the toolpersist the resultupdate task stateelse:record a format errorattempt correction within a limited number of tries
Two properties matter. First, model output must be parsed and validated; it is not a program instruction. Second, every loop needs bounds. Prompting the model to “finish soon” does not stop repeated tool calls or unbounded spend.
A final answer also does not prove the task is done. For evidence-backed queries, check that key records were fetched; for mutating work, trust tool execution status.
5. Tool design sets the safety ceiling
1. Prefer narrow interfaces
A tool that runs arbitrary commands is hard to authorize and audit. Prefer scoped functions: “get status by record id,” not “run any query”; “create an approval request,” not “mutate business data arbitrarily.” Narrow APIs shrink misuse and make validation, audit, and tests direct.
2. Separate read and write
Reads and writes need different permission policies. Read-only queries may run automatically but still need data-scope checks. Notifications, updates, and deletes may need user confirmation, approval, or extra business checks. Do not skip real authorization because the model claims the user already agreed.
3. Treat external content as untrusted
Documents, retrieval hits, and tool text can try to change model behavior. Keep system rules, user goals, and external data separate. External text must not change tool permissions, replace execution rules, or demand secrets.
Prompts reduce some risk; they do not replace server-side isolation. If the model is misled, the tool layer must still block unauthorized actions.
6. Failure recovery: not every error is a retry
Different failures need different handling.
Timeouts and transient outages can retry within limits. Missing or malformed parameters can be returned to the model. Permission failures should deny or enter an auth flow. Impossible tasks should state the limit clearly.
Side-effecting operations need extra care. A timed-out write does not prove it never ran. Blind retry can duplicate records or notifications. Use business idempotency keys, or query the outcome before resending.
Persisting agent state does not by itself make external operations exactly-once. There is a failure window between state writes and external changes; close it with idempotency, transactions, or result reconciliation.
For long tasks, checkpoint after critical steps so a restart resumes from the last reliable state instead of the beginning.
7. Context and cost: more text is not always better
The naive approach resends all history and tool results. That grows tokens, latency, and cost, and can bury what matters.
Layer information:
- keep the current goal, constraints, and key facts
- store large raw results externally
- put summaries, citations, and required fields in context
- load raw data by reference when you need to verify
Summaries can drop facts; do not replace critical evidence with summaries. Fields that affect money, permissions, time, or the final conclusion should keep verifiable original values.
Cost control is more than a step cap. Set budgets for model calls, per-tool timeouts, total duration, and result size. If you allow parallel queries, ensure independence and that fan-out will not overwhelm downstream systems.
8. Evaluation: fluency is not quality
Judge agents on at least four axes:
Task completion: Did it solve the user’s problem, or only sound complete?
Tool use: Right tool, accurate parameters, no missing required steps.
Safety and permissions: Does it refuse unauthorized requests and resist prompt injection from external content?
Efficiency: Repeated queries, empty loops, or unnecessary model calls.
Cover happy paths, missing information, tool failure, insufficient permission, and malicious input. Do not rely on exact string match for stochastic output; check business constraints, evidence completeness, and allowed execution paths.
In development, mock model responses and tool results to test deterministic control logic, then evaluate end-to-end with real calls. That separates implementation bugs from model judgment errors.
9. When to build it yourself vs. use orchestration
Custom implementations fit few tools, concentrated flows, strict dependency control, or high bars for permissions, audit, and API stability.
Generic orchestration is more useful with complex branching, long waits, multiple collaborating actors, and heavy needs for visual debugging and state recovery.
The criterion is long-term total cost, not line count. A short prototype without logs, recovery, tests, and permission control is far from production. A modular custom build with more code can still be easier to maintain.
10. Conclusion: separate intelligence from control
Building an agent without a dedicated framework is technically feasible. The minimal loop needs a model adapter, tool execution, state, and a bounded cycle.
Production systems still need parameter validation, permission control, idempotency, checkpoints, budgets, and evaluation around that loop.
The principle worth keeping: the model understands goals and proposes actions; the program validates conditions and enforces constraints.
Frameworks reduce some boilerplate; they do not replace business-boundary design. Custom code gives tighter control; it does not skip reliability engineering. Choose by task complexity, team skill, and maintenance cost—not by preference for a particular stack.
