Agent Runtime Framework Design and Implementation
This article explains how an agent runtime turns raw LLM capabilities into controllable, deliverable task execution. It covers the core "everything is a plugin" design philosophy, four execution modes and how to choose among them, layered context and memory governance, permission and sandbox controls, observability and evaluation practices, common anti-patterns, and a phased adoption roadmap. Readers will gain a practical blueprint for building an agent runtime that is replaceable, composable, and auditable while keeping cost and risk under control.
1. Why You Need a Runtime Layer
An LLM is essentially a function that takes text in and produces text out. It has no inherent ability to execute tasks. To turn model capability into a deliverable business outcome, you need an engineering layer in between that is responsible for assembling context, exposing tools, driving multi-step loops, enforcing permissions, recording traces, and handling failures and retries. This layer is commonly called the agent runtime.
A simplified formula captures the idea:
Agent = Model + Harness
The model provides reasoning and generation, while the harness provides the “shell capabilities”: tool registration and invocation, context assembly, loop control, state persistence, policy constraints, and observability. Without a harness, a model can only offer suggestions. With a harness, the model can actually finish the work.
The runtime layer must address four core sources of uncertainty: capability uncertainty (model output may be invalid), environment uncertainty (tools may time out, get rate limited, or return dirty data), cost uncertainty (token usage and call counts across multi-step loops are hard to predict), and safety uncertainty (tools have real side effects). For this reason, the first principle of runtime design is not “smarter” but “more controllable.”
2. Core Design Philosophy: Everything Is a Plugin
An approach that the industry is gradually validating is to build the runtime as an assemblable container, where models, tools, skills (reusable task templates), interfaces, storage, and policy validators all exist as plugins. They register with a plugin system through a unified contract, and the runtime assembles them according to configuration.
2.1 Benefits of a Unified Contract
- Replaceable: switching model vendors or inference deployment only requires swapping the model plugin; business orchestration stays unchanged.
- Composable: the same tool plugins can be reused across multiple agents, avoiding duplicate implementation.
- Testable: clear plugin boundaries let you contract-test a single tool without running the entire chain end to end.
- Evolvable: new capabilities ship incrementally as plugins, reducing regression risk.
2.2 The Cost and Boundaries of Pluginization
Pluginization is not free. It introduces dependency resolution, lifecycle management, version compatibility, and isolation problems. In practice, it helps to enforce three boundaries: each plugin does one thing; plugins do not call each other directly but communicate through the runtime bus; and each plugin must declare the permissions and resource limits it requires. Otherwise, “everything is a plugin” degrades into “everything is coupled.”
An illustrative plugin description (pseudocode, expressing only the contract elements):
plugin:name: tool.search_docsversion: 0.3.1permissions: [network.read]limits: { timeout_ms: 8000, max_calls: 20 }schema:input: { query: string, top_k: int<=10 }output: { items: array<doc> }
3. Engineering Implications and Selection of Four Execution Modes
A runtime typically offers multiple execution modes to match scenarios ranging from low to high task determinism. You can choose among them along two dimensions: task determinism and controllability requirements.
3.1 Standard Mode
The runtime drives a multi-step loop of “think — call tools — observe results.” It suits open-ended questions, cross-system queries, and moderately complex workflows. The engineering focus is on loop termination conditions and a maximum step count, to avoid runaway self-loops that blow up cost.
3.2 Programmatic Tool-Calling Mode
Which tools to call, and in what order, is delegated to a piece of deterministic code, while the model only makes decisions or generates arguments at key points. It fits scenarios with stable flows that still need semantic capability, such as ticket routing, reconciliation checks, and report generation. The payoff is significantly reduced uncertainty, plus easier unit testing and replay.
# Illustration: deterministic orchestration + localized model decisionsplan = load_plan("monthly_report")for step in plan.steps:if step.type == "model":args = model.decide(step.prompt, context=ctx)else:args = step.fixed_argsresult = runtime.call(step.tool, args, limits=step.limits)ctx.append(result)
3.3 Minimal Mode
This keeps only the smallest closed loop: a single turn or a few turns, very few tools, and no complex memory. It suits latency-sensitive, cost-sensitive, high-concurrency short tasks such as format conversion, extraction, and classification. Its value is pushing the cost of an “agent” close to that of a single model call.
3.4 Creative Mode
This emphasizes exploration and generation, allowing freer tool combinations and longer chains. It suits prototype validation, solution drafting, and code scaffolding. It must be paired with stricter resource limits and human confirmation points; otherwise it easily produces high consumption with low output.
Selection guidance: start with minimal mode to establish a baseline and a cost anchor; migrate deterministic flows to programmatic tool calling; use standard mode for open-ended scenarios with step and budget caps; and reserve creative mode for offline or sandbox environments.
4. Context and Memory Governance
Most failures in multi-step tasks are not caused by a weak model but by poor context management. A layered context is recommended:
- System layer: role, compliance constraints, output format;
- Task layer: goal, acceptance criteria, current plan;
- Evidence layer: structured tool results, with source and timestamp attached;
- Memory layer: long-term facts across sessions, which must be updatable and expirable.
Key practices include: structuring and trimming tool results to keep only fields relevant to the current subgoal; summarizing and compressing long histories while preserving the decision chain; and setting confidence and expiration policies for memory to avoid “wrong facts polluting the context over the long term.”
5. Permissions, Sandboxing, and Risk Control
When tools have real side effects, the runtime must become the permission boundary. A minimal, actionable rule set:
- Default deny; grant least privilege according to each plugin’s declaration;
- Force human confirmation for write operations, delete operations, and actions involving funds or external publishing;
- Run code execution inside an isolated sandbox that restricts network, filesystem, and runtime duration;
- Audit the full chain: record input summaries, tool call arguments, return status, and elapsed time;
- Desensitize or tokenize sensitive data before it enters the model, and never write raw text into logs.
6. Observability and Evaluation
An agent is a probabilistic system and must be iterated on with data. It is recommended to collect three categories of metrics: effectiveness (task success rate, human rework rate), efficiency (average steps, end-to-end latency), and cost (token consumption, number of tool calls). Also build an offline evaluation set and a regression baseline, and replay it whenever the prompt, model, or plugin version changes, to prevent “local optimization, overall regression.”
When deploying in the cloud, you can combine general-purpose capabilities: a container platform to host the runtime and sandboxes, object storage to hold evaluation sets and traces, a message queue to smooth out task spikes, and logging and monitoring/alerting services for observability. Baidu AI Cloud can serve as the underlying infrastructure for this kind of stack, and the specific selection should be based on compliance and cost evaluation.
7. Common Anti-Patterns
- Cramming all logic into one giant prompt, making it untestable and non-reusable;
- Tools with too coarse a granularity, returning massive irrelevant information that crowds out context;
- No step or budget caps, leading to “self-looping that burns money”;
- Plugins calling each other directly, forming a hidden web of dependencies;
- Judging only by demo results without building an evaluation set, so iteration relies on gut feeling.
8. Implementation Roadmap
Phase one: pick a high-value, verifiable narrow scenario, connect the closed loop with minimal mode, and establish a cost baseline. Phase two: extract 3 to 5 stable tool plugins and a unified contract, and fill in auditing and permissions. Phase three: migrate stable flows to programmatic tool-calling mode, and introduce an evaluation set and regression testing. Phase four: then open up standard mode and creative mode, with supporting budget, sandbox, and human confirmation policies. Following this order lets you gradually expand agent coverage at controllable cost, forming a long-term evolvable architecture that is replaceable, composable, and auditable.
