Evolving Agent Runtime Frameworks: Plugins, Memory, and Token Cost Reduction

    As LLM applications move from single-turn Q&A to long-horizon tasks, the runtime framework around the model becomes as important as model capability. This article examines a four-layer agent runtime design, plugin architecture, runtime adaptation, inference caching and token cost control, spatiotemporal composability, long-term memory evaluation, and a practical implementation checklist for teams building or upgrading agent runtimes.

    1. Background: Agents Move from Single-Turn Q&A to Long-Horizon Tasks

    Over the past year, the focus of LLM applications has shifted from “answering a question” to “completing a task.” An agent needs to break down goals, call tools, read and write files, save intermediate state, and remain aligned across dozens or even hundreds of steps. The longer the task, the more the model’s own capability becomes only one factor; the surrounding system that hosts the model also determines the final result.

    This surrounding system is usually called the agent runtime framework. It organizes prompts and context, schedules tool calls, manages session state, handles errors and timeouts, and records execution traces. With a well-designed framework, the model can perform consistently. With a poor design, even a strong model may lose information midway, call tools repeatedly, or incur high token overhead.

    As a result, industry discussion is shifting from “Is the model strong enough?” to “How should the framework work with the model?” The following sections examine this question from several angles.

    2. Four Core Layers of a Runtime Framework

    A maintainable runtime framework can usually be divided into four layers:

    1. Model access layer: Uniformly encapsulates the calling protocols of different models and handles authentication, retries, rate limiting, and streaming output. Upper-layer business logic should not depend directly on private parameters of a specific model.
    2. Runtime scheduling layer: Handles the task state machine, step orchestration, concurrency control, and timeout handling. It determines when a task continues, pauses, or rolls back.
    3. Tool and plugin layer: Encapsulates capabilities such as file operations, network requests, and database queries as registrable and replaceable units.
    4. Memory and state layer: Manages short-term context, long-term memory, and task artifacts, and provides retrieval and eviction policies.

    The value of layering lies in clear boundaries. When a model is updated, only the access layer needs to change. When a new tool is added, only a plugin needs to be registered. When memory policies are adjusted, they do not affect scheduling logic. Below is a simplified plugin interface example, intended only to illustrate the design approach:

    1. from typing import Protocol, Optional
    2. class Event:
    3. def __init__(self, kind: str, payload: dict):
    4. self.kind = kind
    5. self.payload = payload
    6. class Plugin(Protocol):
    7. name: str
    8. def setup(self, runtime: "Runtime") -> None:
    9. """Run once when the plugin is loaded, to register event handlers or request resources."""
    10. ...
    11. def handle(self, event: Event) -> Optional[Event]:
    12. """Handle an event and return a follow-up event; return None to stop here."""
    13. ...
    14. class Runtime:
    15. def __init__(self):
    16. self._plugins: dict[str, Plugin] = {}
    17. def register(self, plugin: Plugin) -> None:
    18. if plugin.name in self._plugins:
    19. raise ValueError(f"Duplicate plugin registration: {plugin.name}")
    20. self._plugins[plugin.name] = plugin
    21. plugin.setup(self)
    22. def dispatch(self, event: Event) -> None:
    23. for plugin in self._plugins.values():
    24. result = plugin.handle(event)
    25. if result is not None:
    26. self.dispatch(result)

    This code illustrates three principles: a minimal interface, duplicate-name detection before registration, and traceable event dispatch. In a real system, the dispatch process also needs a depth limit to prevent plugins from forming circular calls.

    3. Plugin Architecture Design Considerations

    A plugin architecture keeps the framework’s core stable while allowing extensions to meet different scenarios. Several design points deserve attention.

    First, define clear permission boundaries for plugins. By default, a plugin should only access the resources it has declared. For example, a file plugin should only read and write specified directories, and a network plugin should only access whitelisted domains. This least-privilege strategy can significantly reduce the risk of accidental operations and data leakage.

    Second, unify plugin input and output formats. If different plugins return different structures, the scheduling layer needs adapter code for each plugin, and maintenance cost rises quickly. It is better to standardize on structured objects with type tags and version numbers.

    Third, support hot loading and version isolation. In production, tool logic changes frequently. The framework should allow plugins to be replaced without restarting the main process, while retaining execution records of old versions for troubleshooting.

    Fourth, preserve observability interfaces. Every plugin call should record start time, duration, input summary, and output status. This data supports troubleshooting and also provides a basis for optimizing cost and latency later.

    4. Runtime Adaptation: Adjusting Strategy Based on Execution Results

    “Runtime adaptation” means the framework can adjust subsequent policy parameters based on historical execution data. This is not the model modifying code by itself; rather, the engineering team defines a tunable policy space in advance, and the runtime selects within it.

    Common tunable items include:

    • Context window truncation and summarization policies;
    • Retry counts and backoff intervals after tool call failures;
    • Routing rules that assign different subtasks to models of different sizes;
    • Checkpoint save frequency for long tasks.

    Adaptation mechanisms must have boundaries. Policy adjustments should have upper and lower limits, every change should record its reason, and manual rollback should be supported. Otherwise, a single incorrect policy drift may cause an entire task chain to lose control. It is recommended to separate policy configuration from code, manage it through a configuration center or versioned files, and review and canary-test every change.

    5. Model-Framework Collaboration: Inference Caching and Token Cost

    In agent scenarios, the same system prompt and historical context are repeatedly sent to the model. If the framework does not optimize this, token consumption grows approximately linearly with the number of steps, and cost pressure quickly becomes visible. Collaborative optimization usually starts from the following directions.

    Prefix caching. Place stable, unchanging parts at the beginning of the prompt, such as system instructions, tool definitions, and fixed knowledge snippets, so the unchanged prefix can be reused by the model service. Put variable content at the end. This arrangement can improve cache hit rates.

    Context compression. Apply tiered summaries to historical steps. Keep recent steps in full text and compress earlier steps into structured key points, such as “confirmed facts,” “open questions,” and “tools called and results.” Compression should preserve key constraints so that summaries do not lose the user’s original requirements.

    Result reuse. For deterministic tool calls, such as reading the same configuration file, the framework can cache results at the framework layer and set invalidation conditions. Cache keys should include input parameters and data version to prevent reading stale content.

    Tiered routing. Assign simple format conversion and field extraction to smaller models or rule engines, and leave complex reasoning to more capable models. Routing rules need to be validated with evaluation sets to ensure quality degradation remains acceptable.

    Optimization results must be measured with data. At minimum, monitor three metrics: average tokens per task, cache hit rate, and final task success rate. Looking only at cost while ignoring success rate can easily lead to a “cheap but not useful” conclusion.

    6. Spatiotemporal Composability: A Programming Abstraction Perspective

    Agent tasks often involve two dimensions at the same time: “when to execute” and “where to execute.” For example, a data processing pipeline may need to be triggered in different time windows and also run on local machines, edge nodes, or the cloud. How to describe such tasks with a unified programming abstraction has recently drawn attention from both academia and engineering.

    The core idea of composability is to define each step as a unit with explicit inputs, outputs, and side-effect declarations, and then assemble complete workflows through composition rules. On the time dimension, it is necessary to describe step dependencies, retry windows, and timeout boundaries. On the space dimension, it is necessary to describe resource locations, data residency requirements, and network constraints.

    In engineering practice, this abstraction can be implemented through three things:

    1. Declare the side-effect type for each step, such as read-only, idempotent write, or irreversible operation. The scheduler uses this to decide whether a retry is safe.
    2. Build a directed acyclic graph for dependencies between steps to avoid circular waits.
    3. Pass the execution location as a scheduling parameter instead of hard-coding it in business logic.

    The benefit of this approach is improved testability. Developers can run the complete workflow locally with simulated resources, then switch to the real environment, reducing the cost of online trial and error.

    7. Long-Term Memory: Evaluation First to Avoid Distorted Metrics

    Long-term memory is a key capability that enables an agent to move from a “one-off tool” to a “continuous collaborator.” It includes saving user preferences, tracing historical decisions, and accumulating knowledge across sessions. However, industry evaluation standards for long-term memory are still taking shape, and a single metric can hardly reflect the full picture.

    When introducing long-term memory, engineering teams should pay attention to the following issues:

    • Recall accuracy: Can the system find the right historical information when needed?
    • Conflict handling: When new and old information conflict, can the system identify this and apply a reasonable update policy?
    • Forgetting mechanism: Can expired or low-value memories be evicted to avoid continuously increasing retrieval noise?
    • Privacy compliance: Can memories involving personal information be viewed and deleted, and do they meet data protection requirements?

    Evaluation sets should cover typical scenarios in real business rather than relying only on generic Q&A data. Whenever the memory storage solution or retrieval algorithm changes, results should be compared on the same evaluation set, and version information should be recorded.

    8. Implementation Recommendations and Checklist

    If a team plans to build or upgrade an agent runtime framework, it can follow these steps:

    1. Map task types: Distinguish single-step Q&A, multi-step tool calls, and long-horizon autonomous tasks, and evaluate the required state management capability for each.
    2. Define layer boundaries: First define interfaces for model access, scheduling, tools, and memory, then implement each layer.
    3. Establish plugin specifications: Standardize registration methods, permission declarations, input/output formats, and version management rules.
    4. Set up observability: Record duration, token usage, and result status for every model call and tool call, and configure alert thresholds.
    5. Introduce caching and compression: Start with prefix arrangement and result reuse, then gradually add context summaries, validating each step with evaluation sets.
    6. Design rollback mechanisms: Any policy change should be quickly reversible, with comparison data from before and after the change retained.

    At the infrastructure level, teams can use general container platforms for runtime environment isolation, message queues to decouple long-task submission from execution, object storage to save checkpoints and execution artifacts, and logging and monitoring services to track anomalies. These capabilities are common cloud-native components, and selection should be based on team size, compliance requirements, and cost budget.

    Overall, agent runtime frameworks are moving from “running a single demo” to “reliably completing long-horizon tasks.” Plugin architectures make systems extensible, runtime adaptation makes them tunable, model-framework collaboration makes cost controllable, and a clear memory and evaluation system determines whether the system can truly be used over the long term. Teams should build around these directions in phases and always use verifiable metrics as the standard for judgment.