LLM API Evolution: From Message Primitives to Agent Runtimes

    This article explains how large language model APIs have evolved from simple text generation endpoints into layered architectures for building agent applications. It breaks LLM APIs into three layers—message primitives, agent runtimes, and hosted platforms—covers tool calling loops, context compression, long-term memory, permission design, and security practices, and provides a practical selection framework with engineering recommendations for choosing the right integration depth based on control requirements, team capabilities, and compliance constraints.

    1. Background: From Single Calls to Continuous Task Execution

    Early LLM APIs focused on text generation: the caller submitted input, the model returned output, and the request ended. As use cases expanded, developers needed models to invoke external tools, perform multi-step reasoning, maintain conversation state, and process information far beyond a single context window. The role of the API shifted from “generating text” to “driving task execution.”

    Two evolutionary approaches emerged in the industry. One keeps the original API stable and adds capabilities on top, so existing integrations continue to work. The other introduces new high-level interfaces that move orchestration logic to the server side. Both share the same goal: reducing the engineering cost of building agent applications. Understanding their differences is a prerequisite for making sound technology choices.

    2. The Layered Model: How Three Capability Layers Compose

    Modern LLM APIs can be organized into three layers:

    1. Message primitives layer: Provides stable input/output structures for expressing conversation content, tool call requests, and tool execution results.
    2. Agent runtime layer: Encapsulates the execution loop, handling tool scheduling, permission control, session management, and context compression.
    3. Hosted platform layer: Provides cloud execution environments, state persistence, observability, and security isolation.

    The layers stack: upper layers depend on lower-layer protocols, while lower layers are unaware of upper layers. Developers can use only the bottom layer or integrate progressively deeper. The deeper the integration, the more control developers delegate—and the more engineering convenience they gain.

    3. Message Primitives Layer: The Capability Boundary of the Stable Core

    At the core of the message primitives layer is the “content block.” A single model response may simultaneously contain plain text, tool call requests, and reasoning summaries. Callers process each block by type rather than parsing an unstructured string.

    A typical tool calling flow works as follows:

    1. The caller sends the user message along with tool definitions to the model.
    2. The model decides whether a tool call is needed. If so, it returns a tool call block containing the tool name and structured parameters.
    3. The caller executes the tool locally or remotely, wraps the result in a tool result block, appends it to the message list, and requests the model again.
    4. When the model no longer requests tools, the loop ends and the final answer is returned.

    The following sample code shows the basic structure of this loop:

    1. def run_agent_loop(client, messages, tools, max_steps=10):
    2. for _ in range(max_steps):
    3. response = client.create_message(messages=messages, tools=tools)
    4. messages.append({"role": "assistant", "content": response.content})
    5. tool_calls = [b for b in response.content if b.type == "tool_call"]
    6. if not tool_calls:
    7. return response
    8. results = []
    9. for call in tool_calls:
    10. output = execute_tool(call.name, call.input)
    11. results.append({
    12. "type": "tool_result",
    13. "tool_call_id": call.id,
    14. "content": output,
    15. })
    16. messages.append({"role": "user", "content": results})
    17. raise RuntimeError("Maximum steps exceeded; loop terminated")

    This layer also includes several common capabilities with different engineering values:

    • Structured output: Constrains response formats via JSON Schema, reducing defensive parsing code downstream.
    • Reasoning content return: The model’s intermediate reasoning is returned as separate blocks for debugging and auditing. In some scenarios, reasoning blocks must be passed back in subsequent turns to preserve reasoning continuity.
    • Prompt caching: Repeated prefix content is cached. The cached portion is typically billed at a significantly lower rate, so a stable prompt prefix directly reduces cost.
    • Server-side tools: Capabilities such as web search, web fetching, and code execution run on the server; the caller only declares the tools and receives results.

    The advantage of the message primitives layer is the finest-grained control. Developers own the entire execution loop, context assembly, and tool execution logic, and can precisely control every step. The cost is equally clear: multi-step tool calling, subtask dispatch, session state persistence, and context compression must all be implemented by the developer, and the effort grows linearly with business complexity.

    4. Agent Runtime Layer: Handing the Execution Loop to a Framework

    The agent runtime layer packages the loop from the previous section into reusable components. It typically offers two integration modes.

    Single-task mode suits stateless scenarios. The caller provides a task description and a set of tools, and the runtime completes the entire loop automatically, returning the final result. This mode integrates quickly and fits batch processing, offline analysis, and one-off scripts.

    Stateful session mode suits multi-turn interaction. The runtime maintains conversation history internally and provides callback hooks so developers can insert auditing, rate limiting, or human confirmation before and after tool calls.

    1. session = AgentSession(
    2. model="your-model-id",
    3. tools=[read_file, write_file, run_shell],
    4. permission_policy=ask_before_write,
    5. )
    6. session.on("before_tool_call", audit_logger.record)
    7. session.on("after_tool_call", metrics.observe)
    8. reply = session.send("Inspect the config files in the src directory and fix obvious syntax errors")
    9. print(reply.text)

    Runtimes typically ship with a set of built-in tools covering file read/write, command execution, code search, and network access. Built-in tools unify parameter validation and error formats, reducing duplicate work. At the same time, they enlarge the attack surface. File writing and command execution capabilities, if improperly triggered, can cause data corruption or unauthorized operations. Permission policy in the runtime layer must therefore be designed as a first-class concern.

    Basic principles of permission design include:

    • Authorize at the granularity of tools and paths, following the principle of least privilege.
    • Require confirmation for write operations and external network requests.
    • Stay cautious about tool outputs. Web pages or file contents returned by tools may contain instructions attempting to alter the model’s behavior; the runtime should treat them as data, not execute them as instructions.

    5. Context Management: Compression and Long-Term Memory

    Multi-step tasks continuously accumulate message history, eventually approaching the context window limit. Runtimes typically provide two mechanisms to address this.

    Context compression replaces earlier history with a structured summary when approaching the limit. Effective compression should preserve three kinds of information: the user’s original goal, key decisions already made, and outstanding to-do items. Compression quality directly determines the accuracy of subsequent reasoning, so it is advisable to keep uncompressed original records at critical points for traceability.

    The following sample shows the basic logic for triggering compression:

    1. def maybe_compact(history, token_count, limit, summarizer):
    2. if token_count < limit * 0.8:
    3. return history
    4. head, tail = history[:-10], history[-10:]
    5. summary = summarizer.summarize(
    6. head,
    7. keep=["user goal", "confirmed decisions", "pending items"],
    8. )
    9. return [{"role": "system", "content": summary}] + tail

    Long-term memory addresses information retention across sessions. Unlike context compression, long-term memory lives in external storage and is retrieved and injected on demand. Three questions must be settled in the design: the write conditions (save only preferences explicitly stated by the user, or allow the model to extract them automatically), the expiration policy, and the redaction rules for sensitive information. Without constraints, memory mechanisms tend to accumulate stale or incorrect information that interferes with later judgment.

    6. Hosted Platform Layer: Handing the Execution Environment to the Platform

    The hosted platform layer goes further by delegating the execution environment itself to the provider. Typical capabilities include:

    • Isolated execution environments: Code execution and file operations run in sandboxes, isolated from the host system.
    • Session persistence: State for long-running tasks is saved by the platform, supporting checkpoint recovery.
    • Observability: Every model call, tool call, and latency is recorded for troubleshooting and cost analysis.
    • Integration capabilities: Combination with general infrastructure such as object storage, message queues, logging services, and monitoring/alerting.

    The benefit of a hosted platform is a significantly lower operational burden; the cost is deeper dependency. Developers should evaluate the following factors: whether data residency requirements allow data to leave the local environment, whether the platform’s availability and latency meet business needs, and the cost of migrating to other solutions in the future.

    7. A Selection Framework: Choose Integration Depth by Control Granularity

    The table below compares the three approaches across key dimensions:

    Dimension Message Primitives Layer Agent Runtime Layer Hosted Platform Layer
    Control granularity Finest, fully custom Medium, configurable policies and hooks Coarser, depends on platform capabilities
    Initial development cost High Medium Low
    Multi-step task implementation Write your own loops and state management Provided by the runtime Provided by the platform
    Portability High Medium Lower
    Operational burden Fully self-managed Partially self-managed Mostly handled by the platform
    Typical scenarios Customized workflows, deep integration, existing mature orchestration systems Coding assistants, document processing, data analysis applications Rapid validation, limited team resources, need for a managed execution environment

    When selecting, answer these questions in order:

    1. Is the business process highly customized, requiring complex business rules inserted into the execution loop? If so, prefer the message primitives layer.
    2. Does the team already have reusable orchestration and state management components? If so, integration with the message primitives layer is cheaper.
    3. Do you need to deliver a working agent feature quickly, with execution logic that can accept the framework’s defaults? If so, the runtime layer is a better fit.
    4. Do tasks involve long-running execution, code execution, or file operations, while the team lacks security isolation and operational capacity? If so, consider the hosted platform layer.
    5. Do data compliance requirements restrict the use of external services? If strictly limited, implement at a locally controlled layer first.

    Layered selection is not a one-time decision. A common approach is to validate the prototype on the runtime layer first, then sink critical paths down to the message primitives layer for finer control.

    8. Engineering Practice Recommendations

    Security: Set minimum permissions for each tool, apply whitelist restrictions on file paths, and use sandboxes for command execution. Tool parameters must be validated before execution; never trust model-generated parameters blindly.

    Observability: Record each round’s input summary, tool names, parameter hashes, execution time, and error codes. This data is the primary basis for answering “why did the model make this decision at this step.”

    Cost control: Place stable content such as system instructions and tool definitions at the prompt prefix to improve cache hit rates. Cache repeated subtask results to avoid redundant calls.

    Fault tolerance and idempotency: Tool calls may be retried due to network interruptions. Write operations should be idempotent, or record an operation identifier before execution to prevent duplicate writes. The loop’s maximum step count must be capped to prevent the model from falling into unproductive tool calls.

    Evaluation: Build a fixed test set for representative tasks and rerun it whenever the model version, prompts, or tool definitions change. Judging an agent’s reliability from a single demo is usually unreliable.

    9. Conclusion

    The evolution of LLM APIs can be summarized as “a stable core plus layered extensions.” The message primitives layer guarantees long-term interface compatibility, the runtime layer distills common execution logic into a framework, and the hosted platform layer further lowers the operational barrier. Developers do not have to choose only one layer. The steadier engineering strategy is to pick the appropriate integration depth based on task complexity, team capability, and compliance requirements—and to adjust as the business evolves.