AI agents

Fit the passages in a context budget

Measure the characters that a search tool returns, set each passage's cap from the text that it has to include, and keep the total within a budget.

Picture a technician up a wind turbine who asks the maintenance AI agent what torque to use on the blade root bolts. The agent can answer 2400 newton metres, which is the figure for the tower flange bolts. The blade root section contains the right figure, 1100 newton metres, at character 361 of a 704-character passage; however, the snippet that the tool returns stops at character 240.

The tool cuts the passage because the application keeps the agent's context within a budget. The authors of a 2026 paper on long-horizon search agents describe how memory, latency, and cost limit the size of an AI agent's context in deployment, so the agent has to choose between keeping the information from earlier steps and staying under that limit (arXiv 2604.01664). Shorter passages save room in the context; however, when you cut them to a length that somebody guesses, a technician can receive the wrong torque.

Each result panel below holds the output of the file above it. The model is a mock that scans the passages in its input and returns the first torque figure that it finds, so when the second step prints a wrong answer, the tool's output is the cause. Each code block below holds one whole file.

Measure what the tool sends back

reply.steps holds one entry for each turn of the loop, while each toolResults entry in a step holds the value that the tool returns. When you serialise those values, their length is the number of characters that the loop adds to the next prompt, which is the figure to measure before you cut anything.

Two of the four manual sections match the query, so the tool returns two whole stored bodies.

import { createNarsil } from '@delali/narsil'
import { ToolLoopAgent, tool } from 'ai'
import { z } from 'zod'
import { type ManualPassage, QUESTION, technicianModel } from './mock-model.ts'
 
const narsil = await createNarsil()
 
await narsil.createIndex('turbine_manual', {
  schema: { turbine: 'enum', section: 'string', body: 'string' },
  language: 'english',
})
 
await narsil.insertBatch('turbine_manual', [
  {
    id: 'v90-blade-root',
    turbine: 'v90-2mw',
    section: 'Blade root bolt inspection',
    body: 'Inspect the blade root bolts at every 12-month service and after any lightning strike on the blade. Sound each bolt with a test hammer before you apply a wrench, because a bolt that rings dull has already lost its preload and takes replacement rather than retightening. Tighten each bolt in the crossing sequence printed on the hub casting, in three passes, to 1100 newton metres at the final pass. Record the final reading for every bolt against its position number, and stamp the hub log with the date and your technician number. A bolt that fails to hold the final figure across two consecutive passes goes on the replacement list, and the turbine stays out of service until the whole set is replaced.',
  },
  {
    id: 'v90-yaw-brake',
    turbine: 'v90-2mw',
    section: 'Yaw brake calipers',
    body: 'Measure the pad thickness on all six yaw brake calipers at every 12-month service, and replace the full set once any pad falls below 8 millimetres. Check the hydraulic pressure at the manifold against the nameplate figure before you release the brake, since a caliper that drags heats the yaw ring and scores the friction surface. Grease the yaw ring teeth through the four ports on the deck plate, and turn the nacelle a quarter circle between ports so that the grease reaches the whole ring. Log the pad measurements and the pressure reading in the maintenance record, and raise a repair order for any caliper that leaks at the piston seal.',
  },
  {
    id: 'v90-gearbox-oil',
    turbine: 'v90-2mw',
    section: 'Gearbox oil sampling',
    body: 'Draw the gearbox oil sample from the running loop rather than the sump, with the turbine at a steady output above 500 kilowatts, so that the sample carries the particles that circulate in service. Fill the bottle to the shoulder, cap it at once, and label it with the turbine number, the date, and the running hours. Send the sample to the laboratory within five working days, because the iron count reads high once water has had time to settle out. Replace the breather filter at every sample, and check the sight glass for the milky tint that tells you water has entered the housing.',
  },
  {
    id: 'v90-tower-bolts',
    turbine: 'v90-2mw',
    section: 'Tower flange bolts',
    body: 'Check the tower flange bolts at the first 3-month service after commissioning and at every 24 months afterwards. Retighten to 2400 newton metres at the lower flange and 1800 newton metres at the upper flange, in the sequence on the flange drawing. Replace any bolt whose shank shows a witness mark of movement against the flange face, together with its nut and both washers. Record the readings against the flange drawing positions, and report any flange gap above 0.5 millimetres to the site engineer before you leave the tower.',
  },
])
 
const technicianTools = {
  searchManual: tool({
    description: 'Search the turbine service manual by what its text says.',
    inputSchema: z.object({ text: z.string() }),
    execute: async ({ text }: { text: string }): Promise<ManualPassage[]> => {
      const found = await narsil.query<{ section: string; body: string }>('turbine_manual', { term: text, limit: 4 })
      return found.hits.map((hit) => ({ section: hit.document.section, text: hit.document.body }))
    },
  }),
}
 
let charactersReturned = 0
 
const askTechnicianAgent = async (): Promise<string> => {
  const agent = new ToolLoopAgent({
    model: technicianModel(),
    instructions: 'Answer the technician from the turbine service manual.',
    tools: technicianTools,
  })
  const reply = await agent.generate({ prompt: QUESTION })
  for (const step of reply.steps) {
    for (const result of step.toolResults) charactersReturned += JSON.stringify(result.output).length
  }
  return reply.text
}
 
console.log(
  JSON.stringify({ question: QUESTION, agentAnswered: await askTechnicianAgent(), charactersReturned }, null, 2)
)
 
await narsil.shutdown()
{
  "question": "What torque do the blade root bolts take?",
  "agentAnswered": "1100 newton metres, from 'Blade root bolt inspection'.",
  "charactersReturned": 1328
}

The answer is right; however, the tool output for this one question totals 1,328 characters. Those characters include the lightning-strike rule, the hammer test, the hub log, and the replacement list, although the technician asks about none of them. This page counts characters, because a count of tokens needs the model's tokeniser.

Cap each passage, and watch where the cap falls

With highlight set, the engine cuts each highlighted field to maxSnippetLength characters around the densest run of matches, and it marks the cut with three dots. With document.include, the engine returns only the section title from each stored document, so the two options together bring the tool output down from 1,328 characters to 581.

import { createNarsil } from '@delali/narsil'
import { ToolLoopAgent, tool } from 'ai'
import { z } from 'zod'
import { type ManualPassage, QUESTION, technicianModel } from './mock-model.ts'
 
const narsil = await createNarsil()
 
await narsil.createIndex('turbine_manual', {
  schema: { turbine: 'enum', section: 'string', body: 'string' },
  language: 'english',
})
 
await narsil.insertBatch('turbine_manual', [
  {
    id: 'v90-blade-root',
    turbine: 'v90-2mw',
    section: 'Blade root bolt inspection',
    body: 'Inspect the blade root bolts at every 12-month service and after any lightning strike on the blade. Sound each bolt with a test hammer before you apply a wrench, because a bolt that rings dull has already lost its preload and takes replacement rather than retightening. Tighten each bolt in the crossing sequence printed on the hub casting, in three passes, to 1100 newton metres at the final pass. Record the final reading for every bolt against its position number, and stamp the hub log with the date and your technician number. A bolt that fails to hold the final figure across two consecutive passes goes on the replacement list, and the turbine stays out of service until the whole set is replaced.',
  },
  {
    id: 'v90-yaw-brake',
    turbine: 'v90-2mw',
    section: 'Yaw brake calipers',
    body: 'Measure the pad thickness on all six yaw brake calipers at every 12-month service, and replace the full set once any pad falls below 8 millimetres. Check the hydraulic pressure at the manifold against the nameplate figure before you release the brake, since a caliper that drags heats the yaw ring and scores the friction surface. Grease the yaw ring teeth through the four ports on the deck plate, and turn the nacelle a quarter circle between ports so that the grease reaches the whole ring. Log the pad measurements and the pressure reading in the maintenance record, and raise a repair order for any caliper that leaks at the piston seal.',
  },
  {
    id: 'v90-gearbox-oil',
    turbine: 'v90-2mw',
    section: 'Gearbox oil sampling',
    body: 'Draw the gearbox oil sample from the running loop rather than the sump, with the turbine at a steady output above 500 kilowatts, so that the sample carries the particles that circulate in service. Fill the bottle to the shoulder, cap it at once, and label it with the turbine number, the date, and the running hours. Send the sample to the laboratory within five working days, because the iron count reads high once water has had time to settle out. Replace the breather filter at every sample, and check the sight glass for the milky tint that tells you water has entered the housing.',
  },
  {
    id: 'v90-tower-bolts',
    turbine: 'v90-2mw',
    section: 'Tower flange bolts',
    body: 'Check the tower flange bolts at the first 3-month service after commissioning and at every 24 months afterwards. Retighten to 2400 newton metres at the lower flange and 1800 newton metres at the upper flange, in the sequence on the flange drawing. Replace any bolt whose shank shows a witness mark of movement against the flange face, together with its nut and both washers. Record the readings against the flange drawing positions, and report any flange gap above 0.5 millimetres to the site engineer before you leave the tower.',
  },
])
 
const technicianTools = {
  searchManual: tool({
    description: 'Search the turbine service manual by what its text says.',
    inputSchema: z.object({ text: z.string() }),
    execute: async ({ text }: { text: string }): Promise<ManualPassage[]> => {
      const found = await narsil.query<{ section: string; body: string }>('turbine_manual', { term: text, limit: 4 }) 
      return found.hits.map((hit) => ({ section: hit.document.section, text: hit.document.body })) 
      const found = await narsil.query<{ section: string }>('turbine_manual', { 
        term: text,
        highlight: { fields: ['body'], preTag: '', postTag: '', maxSnippetLength: 240 },
        document: { include: ['section'] },
        limit: 4,
      })
      return found.hits.map((hit) => ({
        section: hit.document.section,
        text: hit.highlights?.body?.snippet ?? '',
      }))
    },
  }),
}
 
let charactersReturned = 0
 
const askTechnicianAgent = async (): Promise<string> => {
  const agent = new ToolLoopAgent({
    model: technicianModel(),
    instructions: 'Answer the technician from the turbine service manual.',
    tools: technicianTools,
  })
  const reply = await agent.generate({ prompt: QUESTION })
  for (const step of reply.steps) {
    for (const result of step.toolResults) charactersReturned += JSON.stringify(result.output).length
  }
  return reply.text
}
 
console.log(
  JSON.stringify({ question: QUESTION, agentAnswered: await askTechnicianAgent(), charactersReturned }, null, 2)
)
 
await narsil.shutdown()
{
  "question": "What torque do the blade root bolts take?",
  "agentAnswered": "2400 newton metres, from 'Tower flange bolts'.",
  "charactersReturned": 581
}

The tool returns 56% fewer characters; however, the answer is wrong. The query matches nine words in the blade root section, and the densest run of them is in its first 176 characters, which hold six of the nine. The engine therefore starts the snippet at the opening and ends it at character 240, which is 121 characters before the torque figure at character 361. The tower flange snippet contains 2400 newton metres, which is the figure for a different set of bolts, so the model returns that figure as the first one in its input.

turbine_manual / v90-blade-root / body, 704 characters

  • cap 240
  • cap 320
  • cap 400
The shaded band covers the densest run of matched words, which holds six of the nine, while each dashed line marks where a snippet of that length ends. Only the 400-character snippet extends past the torque figure at character 361.

Choose the cap from the passage, and the count from the budget

Read the field before you choose the cap. Of the three caps in the diagram above, 400 characters is the only one long enough to include the blade root figure. At that cap, two passages come to 901 characters of tool output.

RETRIEVAL_BUDGET_CHARACTERS is the retrieval allowance for one question in this application. withinBudget adds the passages one at a time and stops before the first one that takes the serialised total past that allowance, so the budget sets the number of passages without any arithmetic for you to redo when a section grows. Here the query matches two passages, which total 901 characters, so both fit within the 1,200 allowance. When a query matches a third passage of about 450 characters, the total will pass 1,200, so withinBudget will leave that passage out.

import { createNarsil } from '@delali/narsil'
import { ToolLoopAgent, tool } from 'ai'
import { z } from 'zod'
import { type ManualPassage, QUESTION, technicianModel } from './mock-model.ts'
 
const narsil = await createNarsil()
 
await narsil.createIndex('turbine_manual', {
  schema: { turbine: 'enum', section: 'string', body: 'string' },
  language: 'english',
})
 
await narsil.insertBatch('turbine_manual', [
  {
    id: 'v90-blade-root',
    turbine: 'v90-2mw',
    section: 'Blade root bolt inspection',
    body: 'Inspect the blade root bolts at every 12-month service and after any lightning strike on the blade. Sound each bolt with a test hammer before you apply a wrench, because a bolt that rings dull has already lost its preload and takes replacement rather than retightening. Tighten each bolt in the crossing sequence printed on the hub casting, in three passes, to 1100 newton metres at the final pass. Record the final reading for every bolt against its position number, and stamp the hub log with the date and your technician number. A bolt that fails to hold the final figure across two consecutive passes goes on the replacement list, and the turbine stays out of service until the whole set is replaced.',
  },
  {
    id: 'v90-yaw-brake',
    turbine: 'v90-2mw',
    section: 'Yaw brake calipers',
    body: 'Measure the pad thickness on all six yaw brake calipers at every 12-month service, and replace the full set once any pad falls below 8 millimetres. Check the hydraulic pressure at the manifold against the nameplate figure before you release the brake, since a caliper that drags heats the yaw ring and scores the friction surface. Grease the yaw ring teeth through the four ports on the deck plate, and turn the nacelle a quarter circle between ports so that the grease reaches the whole ring. Log the pad measurements and the pressure reading in the maintenance record, and raise a repair order for any caliper that leaks at the piston seal.',
  },
  {
    id: 'v90-gearbox-oil',
    turbine: 'v90-2mw',
    section: 'Gearbox oil sampling',
    body: 'Draw the gearbox oil sample from the running loop rather than the sump, with the turbine at a steady output above 500 kilowatts, so that the sample carries the particles that circulate in service. Fill the bottle to the shoulder, cap it at once, and label it with the turbine number, the date, and the running hours. Send the sample to the laboratory within five working days, because the iron count reads high once water has had time to settle out. Replace the breather filter at every sample, and check the sight glass for the milky tint that tells you water has entered the housing.',
  },
  {
    id: 'v90-tower-bolts',
    turbine: 'v90-2mw',
    section: 'Tower flange bolts',
    body: 'Check the tower flange bolts at the first 3-month service after commissioning and at every 24 months afterwards. Retighten to 2400 newton metres at the lower flange and 1800 newton metres at the upper flange, in the sequence on the flange drawing. Replace any bolt whose shank shows a witness mark of movement against the flange face, together with its nut and both washers. Record the readings against the flange drawing positions, and report any flange gap above 0.5 millimetres to the site engineer before you leave the tower.',
  },
])
 
const RETRIEVAL_BUDGET_CHARACTERS = 1200
const SHORTEST_PASSAGE_HOLDING_A_FIGURE = 400
 
const withinBudget = (passages: ManualPassage[]): ManualPassage[] => {
  const kept: ManualPassage[] = []
  for (const passage of passages) {
    if (JSON.stringify([...kept, passage]).length > RETRIEVAL_BUDGET_CHARACTERS) break
    kept.push(passage)
  }
  return kept
}
 
const technicianTools = {
  searchManual: tool({
    description: 'Search the turbine service manual by what its text says.',
    inputSchema: z.object({ text: z.string() }),
    execute: async ({ text }: { text: string }): Promise<ManualPassage[]> => {
      const found = await narsil.query<{ section: string }>('turbine_manual', {
        term: text,
        highlight: { fields: ['body'], preTag: '', postTag: '', maxSnippetLength: 240 }, 
        highlight: { 
          fields: ['body'],
          preTag: '',
          postTag: '',
          maxSnippetLength: SHORTEST_PASSAGE_HOLDING_A_FIGURE,
        },
        document: { include: ['section'] },
        limit: 4,
      })
      return found.hits.map((hit) => ({ 
        section: hit.document.section, 
        text: hit.highlights?.body?.snippet ?? '', 
      })) 
      return withinBudget( 
        found.hits.map((hit) => ({ section: hit.document.section, text: hit.highlights?.body?.snippet ?? '' }))
      )
    },
  }),
}
 
let charactersReturned = 0
 
const askTechnicianAgent = async (): Promise<string> => {
  const agent = new ToolLoopAgent({
    model: technicianModel(),
    instructions: 'Answer the technician from the turbine service manual.',
    tools: technicianTools,
  })
  const reply = await agent.generate({ prompt: QUESTION })
  for (const step of reply.steps) {
    for (const result of step.toolResults) charactersReturned += JSON.stringify(result.output).length
  }
  return reply.text
}
 
console.log(
  JSON.stringify({ question: QUESTION, agentAnswered: await askTechnicianAgent(), charactersReturned }, null, 2)
)
 
await narsil.shutdown()
{
  "question": "What torque do the blade root bolts take?",
  "agentAnswered": "1100 newton metres, from 'Blade root bolt inspection'.",
  "charactersReturned": 901
}

The technician hears 1100 newton metres from the blade root section, while the tool output comes to 901 characters, which is 32% below the 1,328 characters of the whole documents. This saving is smaller than the 56% from the guessed cap; however, with this cap, the answer is right.

When the passages that contain the answer need more room than the budget allows, you can keep the answer right in two ways. You can split the stored text into shorter sections before you index it, or you can set document to false and give the model a second tool that fetches the one passage that the model chooses. Read Indexes and documents for how to store each shorter section as a document with a separate id.

Where to go next