Long Context and AI Agents: Engineering Paths for Production LLM Applications
This article explores two key engineering directions for large language models in production: long-context processing and AI agents. It covers three long-context strategies (full input, segmented summarization, and retrieval), context budget planning, chunking and retrieval parameters, the core components of an agent, security boundaries for tool calling, and a three-layer evaluation framework, with pseudocode examples throughout.
1. Background: The Engineering Value of Long Context and Agents
The input length a large language model can accept in a single request keeps growing, and application patterns have shifted from single-turn Q&A to multi-step tasks. Hundreds of pages of technical documentation, weeks of conversation history, or a code repository with dozens of interfaces can all be included in one request. Once inputs grow longer, engineering teams face two problems: whether the model can effectively use this information, and whether cost and latency can be kept within acceptable bounds.
Agents are the other main thread. An agent lets the model go beyond generating text: it decomposes goals, calls external tools, reads execution results, and decides the next action accordingly. The difficulty with agents usually lies not in a single call, but in state management, error recovery, and permission control across multiple steps.
Long context and agents share the same underlying question: how to place the right information into a limited context window so the model can make verifiable decisions based on it. The sections below proceed from input organization, to execution control, to quality assurance.
2. Three Strategies for Long Context
2.1 Full Input
Full input places all material into a single request. It is the simplest to implement, gives the model the complete context, and suits texts with tight cross-references between passages, such as comparing clauses across a contract. The costs are high token consumption, slow responses, and a greater chance that the model overlooks key details as information volume grows. Full input is therefore best for scenarios with manageable length and compact structure.
2.2 Segmented Summarization
Segmented summarization splits the material into sections, generates a summary for each, and then aggregates the summaries. It suits tasks that can tolerate some loss of detail, such as meeting notes or log archives. The summary template should follow a fixed format, preserving at least four types of fields: time, entity, numeric values, and conclusion. If summaries degrade into vague descriptions, downstream reasoning loses its reliable basis.
2.3 Retrieval
Retrieval builds an index over the material, recalls the most relevant passages for a given question, and concatenates them into the prompt. This is currently the most widely used approach. Its effectiveness depends on three factors: chunking granularity, recall count, and reranking quality. A failure in any of these stages means the model never receives the key evidence.
A comparison of the three strategies:
| Strategy | Suitable Scenarios | Main Risks |
|---|---|---|
| Full input | Tightly structured, manageable length | High cost, scattered attention |
| Segmented summarization | Archiving, overview tasks | Detail loss, numeric distortion |
| Retrieval | Knowledge Q&A, document search | Missed recall, semantic fragmentation from chunking |
2.4 Context Budget
Regardless of the strategy, the budget must be planned in advance. Subtracting the reserved output length and a safety margin from the model’s input limit yields the space actually available for material. A typical allocation priority looks like this:
Total budget = model input limit - reserved output length - safety marginAllocation order:System instructions Fixed overhead, kept first, never trimmedUser question Kept verbatimRetrieved passages Filled in descending relevance until budget is exhaustedConversation history Overflow compressed into a summary; keep the most recent turns verbatim
The point of this design is that trimming is predictable. When input exceeds the limit, the system compresses conversation history first rather than randomly truncating retrieval results, so the model always receives a structurally intact context.
3. Key Parameters for Chunking and Retrieval
The quality of chunking and retrieval directly determines retrieval effectiveness. Four parameters matter most.
Chunking granularity. Split along semantic boundaries first, such as headings, paragraphs, and code functions. Hard-splitting by a fixed character count can cut a concluding sentence in half, producing recalled fragments that are incomplete and unintelligible.
Overlap window. Keeping a small overlap between adjacent chunks reduces information breakage across segment boundaries. The overlap ratio should be chosen based on document type; too much overlap causes duplicate recall and wasted storage.
Recall count. Too few results miss evidence; too many dilute the model’s attention and drive up token cost. The right number should be determined through an evaluation set, not set by intuition.
Reranking. Vector similarity works well for coarse recall, but similar does not mean relevant. A finer ranking layer can be added after coarse recall, combining keyword hits, heading weight, and time freshness into a composite score.
Below is illustrative code that chunks by heading while preserving overlap:
def chunk_by_heading(document, max_chars, overlap_chars):sections = split_by_heading(document)chunks = []buffer = ""for section in sections:if len(section) > max_chars:# A section exceeding the limit needs secondary splitting (omitted here)section = secondary_split(section, max_chars)if len(buffer) + len(section) <= max_chars:buffer += sectionelse:chunks.append(buffer)buffer = buffer[-overlap_chars:] + sectionif buffer:chunks.append(buffer)return chunks
The code performs secondary splitting on oversized sections, a step that is easy to overlook. Without it, a single chunk can exceed the budget limit and the entire retrieval pipeline breaks down.
4. The Basic Structure of an Agent
A working agent typically consists of four components, each with distinct responsibilities.
Planning. The model decomposes the user’s goal into ordered steps. The plan should be structured, checkable content so the system can track progress.
Tools. Tools are the interfaces through which the agent interacts with the outside world, such as querying a database, calling internal services, or reading and writing files. Each tool needs a clear name, parameter description, and return format so the model can invoke it correctly.
Memory. Short-term memory holds intermediate results for the current task; long-term memory holds user preferences and historical conclusions. The two should be stored separately to prevent task state and long-term information from contaminating each other.
Feedback. After a tool returns a result, the model must judge whether the goal has been achieved and decide whether to continue or finish. The feedback loop is what distinguishes an agent from an ordinary pipeline.
Below is an execution loop with a step limit and permission checks:
def run_agent(goal, tools, max_steps):state = init_state(goal)for step in range(max_steps):action = model_decide(state, tools)if action.type == "finish":return action.answerif action.name not in tools:state.log("rejected_unknown_tool", action)continueif not is_allowed(action, tools):state.log("rejected_by_policy", action)continueresult = tools[action.name].run(action.args)state.append(action, result)return "Maximum steps exceeded; task unfinished; returning current progress"
This code reflects three design principles. First, the step count must have an upper bound, or the model may fall into repeated calls. Second, unknown tools and unauthorized operations must be intercepted and logged, not silently ignored. Third, even when a task fails, the system should return interpretable progress so the user can take over.
5. Security Boundaries for Tool Calling
Once an agent can execute actions, the blast radius of errors grows. Security controls should run through the entire design.
Least privilege. Each tool exposes only the operations necessary for the task. Read-only tools are preferred; write and delete tools require separate authorization. Permissions should be configured per task scenario rather than granting the same capabilities to every task.
Parameter validation. Parameters generated by the model should be treated as untrusted input. Before execution, check types, value ranges, and formats, and reject requests that fall outside the contract. This prevents the model from hallucinating invalid paths or out-of-bounds values.
Human confirmation. Irreversible operations such as deleting data, publishing content, or modifying permissions must go through a human confirmation step. The system should display the action to be executed and its scope of impact, and proceed only after explicit user consent.
Injection defense. External content such as web pages, documents, and emails may contain text disguised as instructions. The system should treat such content as data, not as instructions to execute. The prompt should explicitly declare the boundary between data and instructions.
Audit logs. The input, output, and decision rationale of every step should be recorded. Logs serve both post-hoc traceability and future policy improvement. They can be stored in a logging service with a defined retention period.
6. The Evaluation System
Without evaluation, there is no way to tell whether a change is truly effective. Evaluation should cover three layers.
Offline evaluation set. The set should include typical questions, edge cases, and historical failure cases. Every change to prompts, chunking rules, or model versions should trigger a full regression run. The evaluation set must be continuously expanded as the business evolves, or it gradually loses representativeness.
Metrics. Common metrics include answer accuracy, citation correctness, tool-call success rate, average execution steps, and average latency. Metrics can conflict with each other; for example, increasing recall count usually improves accuracy but adds latency and cost, so trade-offs should follow business priorities.
Online feedback. User behaviors such as adoption, modification, and abandonment are the most authentic quality signals. This data can be used to identify difficult samples and feed them back into the offline evaluation set.
Below is illustrative code for the evaluation workflow:
```
def evalu
