From Chatbots to AI Agents: Token Efficiency and Long Context in Large Language Models

    This article examines the two foundational technical capabilities that AI agents demand from large language models: token efficiency and long context. It breaks down token efficiency across training data, inference, and in-context information density, provides metrics and budget-control code for measuring agent efficiency, and analyzes the challenges and engineering approaches for long-context state maintenance—including retrieval augmentation, rolling summaries, structured memory, and prefix caching. It also presents a five-layer agent system architecture and offers practical deployment recommendations covering evaluation, least privilege, execution tracing, and stopping conditions.

    1. New Requirements That the Agent Era Places on Models

    The typical interaction pattern of a traditional large model is “input a prompt, output a piece of text.” The model completes understanding and generation within a single turn, and the task stops when it ends. An agent, by contrast, is goal-driven: the model must complete perception, planning, tool invocation, observation of results, and strategy adjustment within a loop. This process can be summarized as the following cycle:

    1. Perception: read the user’s goal, environment state, and historical information.
    2. Planning: decompose the goal into executable subtasks.
    3. Action: invoke tools such as retrieval, code execution, and file reading/writing.
    4. Observation: read the results returned by tools and update the internal state.
    5. Reflection: determine whether the goal has been completed, and decide whether to continue, roll back, or request human confirmation.

    Long-horizon tasks introduce three direct challenges.

    The first is error accumulation. A small-probability error at each step is amplified in subsequent steps. For example, a single incorrect field assumption can cause an entire data-processing pipeline to fail.

    The second is state maintenance. A task may span dozens or even hundreds of interaction rounds, and early constraints must remain continuously available throughout the entire process.

    The third is cost control. Each round of invocation consumes inference resources, and an agent lacking budget constraints may exhaust its quota in invalid loops.

    Therefore, agent capability is usually reduced to two foundational metrics: inference efficiency within a unit of compute budget, and the ability to keep information available across long histories. These two points correspond respectively to token efficiency and long context, discussed below.

    2. Token Efficiency: Achieving Higher Task Completion Rates with Limited Resources

    Token efficiency refers to the effective work a model can complete per unit of token consumption. It is not a single metric and can be understood at three levels.

    2.1 Training Data Efficiency

    During training, data quality often determines the capability ceiling more than quantity does. Common practices include deduplication, filtering low-quality text, arranging training order by difficulty, and using synthetic data to supplement scarce reasoning samples. The core objective is to make each training token carry more effective information.

    2.2 Inference Process Efficiency

    During inference, a model may generate long intermediate reasoning processes. Excessively long reasoning does not necessarily produce better results; instead, it increases latency and cost. From an engineering perspective, this can be controlled in the following ways:

    • Set a reasoning length budget; once exceeded, require the model to produce a conclusion;
    • Use shorter reasoning modes for simple subtasks, and enable deep reasoning only for complex problems;
    • Use general acceleration techniques such as speculative decoding to reduce the cost per unit of generation.

    2.3 Information Density Within the Context

    Every token in the context window consumes attention computation and storage resources. Compressing lengthy tool-returned results into structured summaries can significantly increase the proportion of effective information.

    When measuring the overall efficiency of an agent, the following metric can be used:

    Efficiency = number of successful tasks / cumulative tokens consumed (usually normalized per thousand tokens)

    Illustrative code is as follows:

    1. def token_efficiency(results):
    2. """results: a dictionary for each task, containing success(bool) and tokens(int)."""
    3. total_success = sum(1 for r in results if r["success"])
    4. total_tokens = sum(r["tokens"] for r in results)
    5. if total_tokens == 0:
    6. return 0.0
    7. # Number of successful tasks per thousand tokens, facilitating comparison across batches
    8. return total_success / total_tokens * 1000

    This metric accounts for both success rate and cost, avoiding the pursuit of a high success rate while ignoring resource consumption.

    At the loop execution level, budget constraints are also needed. The illustrative code below shows an execution framework with a budget and a step limit, where step_fn and summarize need to be replaced with actual implementations:

    1. def run_agent(goal, budget_tokens, step_fn, summarize, max_steps=50):
    2. used = 0
    3. state = {"goal": goal, "notes": [], "done": False}
    4. for _ in range(max_steps):
    5. output, cost = step_fn(state) # Invoke the model and execute one step
    6. used += cost
    7. state["notes"].append(summarize(output))
    8. if state["done"]:
    9. return {"status": "success", "used": used}
    10. if used >= budget_tokens:
    11. return {"status": "budget_exhausted", "used": used}
    12. return {"status": "max_steps", "used": used}

    The budget check should be placed after each step, rather than only being counted at the end of the task. This allows timely stopping before costs spiral out of control.

    3. Long Context: Enabling the Model to Remember the State of Long-Horizon Tasks

    3.1 Main Difficulties of Long Context

    The computation of the standard attention mechanism scales quadratically with sequence length; the longer the context, the faster memory and computation overhead grow. In addition, the generalization ability of positional encoding is limited when exceeding the training length. In practice, another phenomenon has been observed: the model’s recall rate for information located in the middle of long text is significantly lower than for information at the beginning and end, often referred to in the research literature as “lost in the middle.”

    3.2 Common Engineering Approaches

    • Retrieval augmentation: store historical records in external storage and recall relevant fragments according to the current question.
    • Rolling summaries: when the context exceeds a threshold, compress early conversations into summaries while retaining constraints and key decisions.
    • Structured memory: store task goals, completed steps, and to-do items as fields rather than mixing them in free text.
    • Prefix caching: cache fixed parts (system instructions, tool descriptions) to reduce repeated computation.

    Below is a simple working memory example that demonstrates the idea of “key facts are always retained, and historical records are compressed on demand”:

    1. class WorkingMemory:
    2. def __init__(self, max_chars=8000):
    3. self.max_chars = max_chars
    4. self.facts = {} # Key constraints and decisions, always retained
    5. self.log = [] # Execution records in chronological order
    6. def add(self, entry: str):
    7. self.log.append(entry)
    8. if sum(len(x) for x in self.log) > self.max_chars:
    9. self._compress()
    10. def _compress(self):
    11. # Keep the most recent 5 entries verbatim; earlier records are passed to an external summarization function
    12. keep, old = self.log[-5:], self.log[:-5]
    13. self.log = [summarize_text(old)] + keep # summarize_text is an illustrative function
    14. def build_prompt(self, task: str) -> str:
    15. return (
    16. f"Constraints: {self.facts}\n"
    17. f"Task: {task}\n"
    18. "Recent records:\n" + "\n".join(self.log)
    19. )

    3.3 Evaluation Methods for Long-Context Capability

    Evaluation should not only look at the length of the context window. Tests should be designed by position: insert key information at the beginning, middle, and end of the text, and measure how recall rate changes with position. Cross-paragraph reasoning should also be tested, that is, cases where the model needs to synthesize information from multiple locations to reach a conclusion. Evaluations that only test retrieval often overestimate the actual capability for long-horizon tasks.

    4. Engineering Architecture of an Agent System

    A usable agent system is usually divided into five layers:

    • Model layer: responsible for understanding, planning, and generation, and should support switching between models of different scales according to task complexity.
    • Orchestration layer: manages the execution loop, retries, timeouts, and concurrency; it is the main location for controlling cost and stability.
    • Tool layer: encapsulates capabilities such as retrieval, code execution, and database queries through a unified interface; each tool needs to declare its input and output structures.
    • Memory layer: short-term working memory and long-term knowledge bases are separated, and long-term data can be stored in object storage or databases.
    • Security and monitoring layer: responsible for permission checks and operation audits, and for detecting anomalies through logging services and monitoring alerts.

    For deployment, asynchronous tasks can be handled by message queues, and code-execution tools should run in isolated environments on a container platform to avoid affecting the host system.

    5. Practical Recommendations for Implementation

    1. Start with narrow tasks. Prioritize processes with clear boundaries and verifiable results, such as report reconciliation or log analysis, rather than open-ended end-to-end automation.
    2. Follow the principle of least privilege. Tools should expose only necessary operations, and actions involving writing, deletion, or sending should require human confirmation by default.
    3. Establish an evaluation set. Record the task success rate, average token consumption, average number of steps, and failure reasons for each version, and use the same set of tasks for horizontal comparison.
    4. Preserve complete execution traces. The input, output, and tool calls of each step should be replayable; this is the basis for locating errors and optimizing prompts.
    5. Define stopping conditions clearly. Set a maximum number of steps, a budget cap, and a timeout at the same time; none of the three can be omitted.

    6. Risks and Boundaries

    Once an agent gains the ability to act, the cost of errors rises accordingly. The model may misunderstand instructions, invoke the wrong tools, or unintentionally expose sensitive data. The training process itself also reflects developers’ choices regarding model behavior and value orientation, so alignment and safety evaluation need to run throughout the entire development cycle.

    High-risk operations should be placed in isolated environments, with human review checkpoints retained. Efficiency improvements and long-context expansion need to be validated in tandem. If only capability metrics are pursued, cost and risk