Building Production-Ready AI Agents Without an Orchestration Framework
Building an AI agent directly with model APIs is straightforward; making it reliable in production requires explicit controls. This article explains how to structure a framework-free agent around models, tools, state, and a bounded execution loop, then add validation, authorization, idempotency, context management, security, recovery, and evaluation. It also examines when a custom implementation is appropriate and when an orchestration framework can reduce maintenance costs.
1. The Real Question Is Not Whether You Can Build It Yourself
You can build an AI agent with tool calling and multi-step execution by calling a large language model API directly from a general-purpose programming language. An agent orchestration framework is not a prerequisite.
But a working implementation is not necessarily ready for production.
A demo may take only a few dozen lines: receive a question, call the model, execute a tool, and return a result. A production system must also answer questions such as:
- Why did the model choose this tool?
- Are the arguments valid, and is the caller authorized?
- Should a timed-out external request be retried or terminated?
- Can a task resume if the process exits halfway through?
- Could repeating an action create duplicate orders or notifications?
- How do you determine whether an answer is reliable rather than merely fluent?
The main value of a custom agent is not minimizing code. It is keeping execution logic, risk boundaries, and runtime state explicit and controllable.
At the same time, an easy-to-build execution loop does not make every framework unnecessary. Frameworks often provide state orchestration, checkpoints, concurrent execution, and debugging support. The decision should depend on your requirements and your team’s maintenance capacity, not simply the number of abstraction layers.
2. Distinguish Fixed Workflows from Autonomous Agents
Many systems described as agents are better implemented as fixed workflows.
For example, a document-processing task might follow this sequence:
Read the document → Extract fields → Validate fields → Generate a summary → Save the result.
If the steps are already known and the model handles only text interpretation and generation, ordinary functions, conditional branches, and task queues can provide the orchestration. There is no need to ask the model to choose the next action on every iteration.
An autonomous agent works differently. The model can select its next operation based on the goal and current observations. When information is insufficient, for example, it might retrieve material, assess whether the results are adequate, search again if necessary, and then produce an answer.
The distinction is not whether the system uses an LLM, but who determines the execution path:
- Fixed workflow: The program determines the path; the model performs specific tasks.
- Autonomous agent: The model selects actions within boundaries defined by the program.
- Hybrid approach: The main workflow is fixed, with autonomous decisions allowed only at selected stages.
For many enterprise applications, a hybrid approach is easier to control. It preserves the model’s ability to handle complex language without handing the entire business process to unpredictable generated outputs.
3. A Minimal Architecture: Model, Tools, State, and Control Loop
A lightweight agent can be divided into four core components.
Model Integration Layer
The model integration layer constructs requests, receives responses, handles timeouts, and converts external API responses into a consistent internal representation.
Business logic should not depend directly on a provider’s response fields. An adapter can expose a normalized decision object instead:
Decision object:Kind: final answer or tool callAnswer text: optionalTool name: optionalTool arguments: optional
This is an application-level protocol, not a claim that any particular model provider exposes this interface.
The adapter separates business control logic from external API details. Switching providers will often require changes to the adapter and related tests rather than a rewrite of the execution loop. However, models differ in tool selection and instruction following, so any replacement must be evaluated again.
Tool Layer
Tools expose controlled capabilities, such as searching knowledge, reading business data, or submitting an approved operation.
A complete tool definition should include at least:
- A name and description of its purpose.
- Argument types and required fields.
- Input range and length limits.
- An output structure.
- Timeout requirements.
- Authorization requirements.
- Whether the tool produces external side effects.
Longer tool descriptions are not necessarily better. What matters is explaining when the tool should be used, what conditions its inputs must satisfy, and what questions its output can answer.
Do not let the model select arbitrary functions, evaluate arbitrary expressions, or run generated strings as system commands. It should select only approved tools from a registry.
State Layer
State includes more than conversation history. It should also track the task identifier, current stage, completed steps, tool results, budget consumption, and termination reason.
Keep two categories of data separate:
- Model context: Information sent to the model to help it understand the task.
- Trusted execution state: Information maintained by the program for authorization, budget enforcement, and recovery.
For example, a statement in a conversation that an operation “has been approved” is not valid authorization. Approval must come from a trusted business system and be verified by the program.
Control Loop
The control loop determines when to call the model, execute a tool, and stop.
A reliable loop needs explicit termination conditions. In addition to a final answer from the model, these should account for maximum steps, total runtime, call budgets, consecutive failures, and repeated actions.
Without such limits, a model may continue attempting an unsolvable task, creating request backlogs and uncontrolled costs.
4. Understanding the Core Logic with Illustrative Code
The following code illustrates the control flow only. The model adapter, argument validation, authorization checks, and logging components must be implemented for the application.
def run_task(task, model_adapter, tools, policy, max_steps=8):state = {"task": task,"observations": [],"status": "running",}for step in range(max_steps):policy.check_budget(state)decision = model_adapter.decide(state)validate_decision(decision)if decision["kind"] == "finish":answer = decision["answer"]validate_answer(answer, state)state["status"] = "finished"return answername = decision["tool"]tool = tools.get(name)if tool is None:state["observations"].append({"type": "tool_error","message": "The requested tool is unavailable",})continuearguments = tool.validate(decision["arguments"])policy.authorize(tool, arguments, state)result = tool.execute(arguments)state["observations"].append({"type": "tool_result","tool": name,"result": sanitize_result(result),})state["status"] = "step_limit_reached"raise RuntimeError("Task reached the execution step limit")
The step limit is an example configuration, not a universal recommendation. Its actual value should be determined through task evaluation and cost constraints.
More importantly, the code establishes three boundaries:
- The model proposes actions; the program validates and authorizes them.
- Tool results are processed before entering the context. Raw data should not be fed back without limits.
- Reaching an execution limit produces an explicit failure state. It should not prompt the model to invent an apparently successful answer.
A production implementation must also add exception handling, persistent state, and side-effect controls.
5. Reliable Tool Execution Matters More Than Prompt Wording
Validate Structured Outputs
Server-side validation remains necessary even when the model supports structured output.
Validation should check required fields, types, enum values, and business constraints. For example, a query’s time range must not expand without limits, page sizes must stay within permitted bounds, and target resources must be accessible to the current user.
Correct formatting does not imply a valid business operation. An argument object can satisfy its schema while containing a resource identifier the caller is not authorized to use.
Handle Errors by Category
Different errors require different responses:
- Invalid arguments: Return concise validation feedback and allow a limited number of corrections.
- Transient network failures: Use bounded retries only after confirming that retrying is safe.
- Authorization denial: Stop the relevant operation. Do not rewrite arguments to bypass the restriction.
- Business conflicts: Explain the failure according to business rules or route it to human review.
- Unknown exceptions: Save diagnostic information and return a status the user can understand.
Treating every exception as “try again” encourages repeated invalid actions and can amplify failures in external systems.
Make Write Operations Idempotent
Retrying a failed search is usually low risk. Sending notifications, updating records, or submitting transactions cannot be repeated blindly.
A common approach is to assign a unique identifier to a business operation so the tool service can recognize duplicate requests and avoid duplicate side effects. The identifier must represent the same logical operation across retries, rather than being regenerated for every attempt.
If an external system does not support idempotency and the outcome is uncertain, check the operation’s status first. Escalate to human confirmation when necessary instead of retrying blindly.
6. Context Management Is Not About Sending the Entire History
Long-running tasks accumulate user input, model responses, and tool results. Sending all of that material to the model increases cost and can bury important information beneath irrelevant details.
A layered approach is more manageable:
- Retain the current goal, constraints, and latest execution results.
- Summarize earlier steps.
- Store original materials externally and retrieve them by reference when needed.
- Limit the length and number of tool results.
- Preserve source identifiers for factual conclusions so they can be checked.
Summaries can omit information, so they should not replace all original records. Critical data—including permissions, approvals, amounts, and resource identifiers—must be read from trusted program state, not reconstructed from the model’s recollection of the conversation.
7. Security Controls Must Live Outside the Model
A typical agent risk is an instruction embedded in external material. Retrieved content might tell the model to ignore existing rules, disclose information, or call an unrelated tool.
Such content must be treated as data to analyze, not as a new system instruction. A prompt that says “ignore malicious instructions” is not sufficient; application-level controls are still required.
Useful defenses include:
- Least privilege: Give tools only the permissions needed for the current task.
- Source separation: Keep user requests, tool results, and system rules distinct through roles and source labels.
- Confirmation for sensitive actions: Require valid approval before deletion, payments, or bulk changes.
- Sensitive-data redaction: Avoid exposing secrets, personal information, and unnecessary internal data in logs or answers.
- Access-scope validation: Validate external addresses, file paths, and resource access in code.
- Audit records: Record the caller, operation target, argument summary, and final outcome.
Human approval should apply to a specific action, not every action the model might take afterward. If the target, amount, or scope changes after approval, obtain confirmation again.
8. Production Requires Recovery and Observability
Persist State
For long-running tasks, save state at key points: after a model decision, before and after tool execution, and when the task ends.
Persistence alone does not guarantee exactly-once execution. A tool might complete successfully, followed by a process crash before its result is saved. Recovery could then execute the same operation again.
Checkpointing must therefore be designed alongside idempotency and operation-status checks.
Make Execution Observable
Logs should connect the model requests, tool calls, durations, failure reasons, and budget consumption within a task.
Prioritize verifiable inputs, outputs, and decision outcomes. There is no need to require the model to expose its complete internal reasoning. For sensitive applications, logs also need redaction, access controls, and retention limits.
Use Offline Evaluation and Regression Tests
A few successful conversations are not enough to establish reliability.
Test cases should cover normal tasks, missing information, malicious input, insufficient permissions, tool failures, conflicting results, and exhausted execution budgets.
Evaluation metrics can include:
- Task completion rate.
- Tool-selection accuracy.
- Unauthorized actions.
- Average execution time.
- Resource consumption per task.
Run regression tests whenever the model, prompts, tool descriptions, or authorization policies change. Even a small wording adjustment can alter tool-selection behavior.
9. When to Build Your Own Agent—and When to Use a Framework
A custom implementation is often suitable when:
- There are relatively few tools and execution paths are reasonably clear.
- The team needs direct visibility and control over each call.
- Logging, storage, authentication, authorization, and task-management infrastructure already exist.
- Special permission or side-effect constraints require precise control.
- The team wants to validate the task’s value through a limited trial.
A mature orchestration solution may reduce implementation costs when the system needs many parallel branches, complex pause-and-resume behavior, multi-agent collaboration, visual orchestration, or unified runtime governance.
Do not compare the approaches only by lines of code. Consider learning, debugging, runtime, upgrade, and long-term maintenance costs.
A custom abstraction layer may gradually become an internal framework. It still needs clear interfaces, version management, and disciplined testing.
10. Lightweight Implementation Is Feasible; Reliability Still Takes Engineering
There is no fundamental technical barrier to building an agent without an orchestration framework. Its foundations are a model interface, controlled tools, explicit state, and a bounded execution loop—not an irreplaceable framework capability.
The right engineering goal is neither to let the model make every decision nor to produce a demo with the fewest lines of code. Deterministic business rules belong in the program; tasks that genuinely require semantic judgment belong with the model.
Start with a low-risk task that has clear boundaries and read-only tools. Establish logging, validation, and evaluation before expanding. Once the benefits are demonstrated, gradually add recovery, controlled write operations, and more complex orchestration.
Ultimately, maturity depends on whether the system can complete tasks consistently, explain failures, control costs, and preserve business boundaries when something goes wrong. A framework can help achieve those goals, but it cannot replace designing for them.
