AI Agents = Model + Runtime Framework: Building Complete Intelligent Workflows
This article explores the architectural pattern of AI agents, defining them as a combination of a language model and a runtime framework (agent harness). It details the responsibilities of both components, best practices for context management, the standard tool-calling loop, security boundaries, observability, and evaluation methods for building stable, intelligent workflows in production environments.
1. Why a Runtime Framework is Required Beyond the Model
Large language models excel at language understanding, reasoning, and content generation, but they are fundamentally text-in, text-out functions. They cannot proactively read files, remember the results of previous operations, or directly invoke external systems. To enable a model to complete multi-step tasks such as querying data, analyzing results, modifying configurations, and verifying effects, an engineering layer is required to translate the model’s output into actual actions and feed the results back to the model.
The industry typically refers to this layer as the agent harness or runtime framework. It is responsible for organizing inputs, maintaining state, executing tools, and controlling loops. The model provides judgment, while the framework provides the execution environment. Together, they form an AI agent.
This perspective offers two direct benefits. First, teams can decouple the problem: if the model isn’t smart enough, optimize prompts or switch models; if execution is unstable, modify the framework. Second, system reliability no longer relies entirely on the stochastic behavior of the model, but is underpinned by deterministic engineering logic.
2. Formula Breakdown: What Models and Runtime Frameworks Do
2.1 Model Responsibilities
The model handles three types of judgments:
- Understanding task intent and translating natural language requirements into executable steps;
- Deciding the next step based on the current context—whether to answer, call a tool, or ask for clarification;
- Interpreting the results returned by tools to determine if the goal has been achieved.
Model outputs should be structured, such as explicit tool names and parameters, rather than a paragraph requiring human guesswork. Structured output is the contract between the framework and the model.
2.2 Runtime Framework Responsibilities
The runtime framework typically includes the following modules:
- Context Management: Determines the content fed to the model in each turn, including system instructions, task descriptions, conversation history, tool results, and retrieved materials.
- Tool Calling: Registers available tools, validates parameters, executes calls, and standardizes results before feeding them back.
- Loop Control: Sets maximum steps, timeouts, and termination conditions to prevent the agent from falling into ineffective loops.
- State and Logging: Records the input, output, and duration of each step for backtracking and debugging.
- Permissions and Security: Restricts tool scope, requires human confirmation for high-risk operations, and isolates execution environments.
2.3 The Boundary Between the Two
To determine whether a capability belongs to the model or the framework, follow a simple principle: leave anything requiring semantic understanding and open-ended reasoning to the model; assign anything requiring determinism, auditability, or constraints to the framework. For example, “What does this log indicate?” is a model task, while “Deleting the production directory requires confirmation” is a framework task.
3. Practical Tips for Context Management
Context windows are limited, and longer contexts make it easier for models to miss key information. Therefore, context management is the part of the runtime framework requiring the most meticulous design.
3.1 Layered Input Organization
It is recommended to divide the context into four layers:
- Stable Layer: Role definitions, behavioral constraints, and output format requirements, which remain unchanged across turns;
- Task Layer: Current goals, acceptance criteria, and confirmed prerequisites;
- Process Layer: Recent tool call records and intermediate conclusions;
- Material Layer: On-demand retrieved document fragments or data summaries.
The benefit of layering is that the framework can apply different truncation and retention strategies to each layer. The stable layer must be fully retained, while the process layer can be gradually compressed.
3.2 Controlling the Token Budget
Before each call, estimate the input length and reserve enough space for the output. When the budget approaches the limit, the framework can perform the following operations:
- Replace older tool outputs with summaries;
- Remove history turns irrelevant to the current goal;
- Retain only relevant paragraphs from excessively long file contents.
When compressing, it is crucial to retain key facts, such as modified file paths, confirmed error causes, and unfinished subtasks. Otherwise, subsequent steps may result in duplicated effort or contradictions.
3.3 Truncation and Standardization of Tool Results
Tool outputs may be very long or contain irrelevant information. The framework should standardize the result format, for example, including a status code, a summary, and a reference to the raw content. For excessively long outputs, only the key beginning and end should be fed back, noting that it has been truncated, while retaining the full content for manual review.
4. Standard Loop for Tool Calling
The core of tool calling is a loop: the model proposes an action, the framework executes it, the result returns to the model, and this continues until the task is complete. Below is a platform-agnostic skeleton representation:
def run_agent(task, model, tools, max_steps=20):context = build_initial_context(task)for _ in range(max_steps):reply = model.generate(context,tool_schemas=tools.schemas(),)if reply.is_final_answer:return reply.textfor call in reply.tool_calls:if not tools.is_allowed(call.name):result = {"status": "denied", "message": "Tool not authorized"}else:result = tools.execute(call.name, call.arguments)context.append_tool_result(call.id, truncate(result))context = compact_if_needed(context)raise RuntimeError("Maximum steps reached, task incomplete")
This code reflects several engineering points. First, the loop has a clear upper bound to prevent infinite execution. Second, permission checks are performed before tool calls, and authorization does not depend on the model. Third, tool results are truncated before being fed back to control context size. Fourth, the compaction step executes independently, rather than leaving the compaction decision to the model.
In a real system, parameter validation, timeout handling, and retry strategies should also be added. For tools with side effects, such as writing files or sending requests, the intent should be logged before execution, and a compensation or rollback plan should be provided upon failure.
5. Security Boundaries and Risk Control
Once an agent can execute actions, security concerns expand from “Is the answer correct?” to “Is the operation out of bounds?” The following measures are common minimal practices:
- Least Privilege: Open only the necessary tools and directories for each task, defaulting to read-only.
- Sandboxed Execution: Run code or commands in an isolated environment, restricting network and file access scope.
- High-Risk Operation Confirmation: Operations like deletion, overwriting, publishing, or modifying permissions must be executed only after human confirmation.
- Input as Data: File contents or web texts returned by tools should be treated strictly as material; the framework should not execute instructions within them as system commands.
- Key Management: Inject credentials via environment variables or secret management services; do not write them into prompts, code, or logs.
The commonality of these measures is placing critical judgments at the framework layer. Even if the model is misled, the framework can still prevent out-of-bounds operations.
6. User Interface and Observability
An agent’s interface can be a GUI, a web page, or a terminal. Terminal interfaces have the advantage of being close to developers’ working environments, making it easy to view file diffs, execution logs, and command outputs. Regardless of the format, the interface should clearly display: the current step, tools called, pending operations requiring confirmation, and the final result.
Observability is equally important. It is recommended to record the following data for each run:
- The size and truncation status of inputs for each turn;
- The name, parameter summary, duration, and status of tool calls;
- Whether the structure of the model output is valid;
- Whether the final result passes acceptance.
These data are used both for post-mortem troubleshooting and for continuously optimizing prompts, tool definitions, and looping strategies.
7. Evaluating Agents
Evaluation should not rely solely on a single demo. A more reliable approach is to establish a set of fixed tasks, run them regularly, and record the following metrics:
- Task Completion Rate: The proportion of tasks meeting acceptance criteria within the limited step count;
- Average Steps and Duration: Reflects efficiency and whether loop control is reasonable;
- Tool Error Rate: Differentiates between parameter errors, permission denials, and execution failures;
- Manual Intervention Count: Measures the balance between automation and risk control;
- Cost: Tracks the number of model calls and input/output lengths consumed per task.
Evaluation results should point to specific areas. If the completion rate is low, first check whether the context lost key information; if the tool error rate is high, check whether parameter definitions are clear; if there are too many steps, check whether the loop contains repetitive calls.
8. Implementation Recommendations
When introducing agents within a team, proceed in the following order: start with a small, clearly scoped, verifiable task, such as log analysis or document retrieval; then implement a minimal runtime framework that only opens necessary tools; subsequently, add logging, permissions, and confirmation mechanisms; finally, adjust context strategies and tool designs based on evaluation data.
The formula “Model + Runtime Framework = Agent” provides a division-of-labor approach. The model is responsible for understanding and decision-making, while the framework handles constraints and execution. Only when both parts do their jobs well can an agent play a stable role in real-world workflows.
