Skip to main content
Back to all articles
AI Engineering 6 min readUpdated August 31, 2026

Stop Putting Entire Tool Results Back Into the Prompt

Large logs, SQL results, API payloads, and documents should not automatically become model context. This pattern stores artifacts outside the prompt and returns a bounded preview plus a secure handle for targeted read-back.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#ai-agents#tool-calling#context-engineering#artifact-storage#llm-cost#typescript#python
On this page

A tool can return the correct result and still damage the next agent step by returning far too much of it.

The classic example is a log-search tool. The agent asks for errors around a deployment and gets 18,000 lines. The tool technically succeeded. The next model call now pays for a huge payload, important instructions are pushed farther away, and the model has to search a wall of text for the few lines that matter.

The same thing happens with SQL query results, repository files, web pages, JSON APIs, test output, CSV exports, and monitoring traces.

I do not think the right default is “put the tool result into the conversation.” The right default is “decide what representation the next reasoning step needs.”

For small results, inline them. For large results, store the full artifact outside the context window and return a bounded preview plus a handle the agent can use to inspect specific parts later.

The example here is an operations assistant that searches service logs and inspects large diagnostic bundles.

Make size a tool-boundary concern

The model should not have to notice that a payload is enormous after it has already been inserted into the prompt.

I intercept tool output before it becomes an observation.

TypeScript
type InlineToolResult = {  kind: "inline";  content: string;};​type ArtifactToolResult = {  kind: "artifact";  artifactId: string;  mediaType: string;  byteLength: number;  preview: string;  expiresAt: string;};​type PreparedToolResult = InlineToolResult | ArtifactToolResult;

A small serializer can decide which path to use:

TypeScript
interface ArtifactStore {  put(input: {    tenantId: string;    runId: string;    mediaType: string;    content: Buffer;    expiresAt: Date;  }): Promise<{ artifactId: string }>;}​async function prepareToolResult(  raw: unknown,  context: { tenantId: string; runId: string },  store: ArtifactStore,): Promise<PreparedToolResult> {  const text = typeof raw === "string" ? raw : JSON.stringify(raw, null, 2);  const bytes = Buffer.byteLength(text, "utf8");​  if (bytes <= 24_000) {    return { kind: "inline", content: text };  }​  const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1_000);  const { artifactId } = await store.put({    tenantId: context.tenantId,    runId: context.runId,    mediaType: "text/plain",    content: Buffer.from(text, "utf8"),    expiresAt,  });​  return {    kind: "artifact",    artifactId,    mediaType: "text/plain",    byteLength: bytes,    preview: buildPreview(text, 4_000),    expiresAt: expiresAt.toISOString(),  };}

The byte thresholds above are examples. In a real system I would choose them from model context budgets and traces rather than treat bytes as a perfect proxy for tokens.

The important design is the interception point: the full result never enters model context by accident.

A preview should help choose the next read

Returning only artifactId=123 is too little information. The agent needs enough context to decide whether the artifact is worth opening and what part to request.

For logs, a good preview might contain:

  • time range;
  • total matching lines;
  • service names;
  • counts by level or error signature;
  • the first few representative lines;
  • available read operations.

For a SQL result:

  • columns;
  • row count;
  • a few rows;
  • ordering;
  • truncation notice.

For a source file:

  • path;
  • byte/line count;
  • language;
  • a small opening section;
  • symbol index if available.

The preview is not just truncation. It is a navigation aid.

A simple log preview can still be deterministic:

TypeScript
function buildPreview(text: string, maxChars: number): string {  if (text.length <= maxChars) return text;​  const head = text.slice(0, Math.floor(maxChars * 0.7));  const tail = text.slice(-Math.floor(maxChars * 0.3));​  return `${head}\n\n[...content stored externally...]\n\n${tail}`;}

For structured result types I prefer domain-specific previews over this generic fallback.

Give the agent targeted read tools

Offloading only works if the agent can retrieve the detail it later discovers it needs.

I expose narrow read operations instead of one “dump artifact” tool.

TypeScript
type ReadArtifactInput = {  artifactId: string;  offset: number;  limit: number;};​type SearchArtifactInput = {  artifactId: string;  query: string;  maxMatches: number;};

For logs, line-oriented reads are often easier:

TypeScript
async function readArtifactLines(input: {  artifactId: string;  startLine: number;  lineCount: number;}, actor: ActorContext): Promise<string> {  const artifact = await artifactStore.getAuthorized({    artifactId: input.artifactId,    tenantId: actor.tenantId,    runId: actor.runId,  });​  return readLineRange(    artifact.path,    input.startLine,    Math.min(input.lineCount, 500),  );}

The hard maximum matters. A model should not be able to defeat the entire design by calling lineCount: 1000000.

Artifact handles are capabilities, so scope them

A random ID is not an authorization system.

Every read must verify that the current actor/run may access the artifact. I normally store ownership metadata with the object:

TypeScript
type ArtifactMetadata = {  id: string;  tenantId: string;  runId: string;  createdByUserId: string;  mediaType: string;  byteLength: number;  expiresAt: Date;};

If artifacts contain data from user-scoped tools, I may scope them to the user as well as the tenant.

Presigned object-storage URLs can be useful for browser downloads, but I would not place a long-lived public URL into the prompt and call that a secure handle. Tool-mediated access gives the application a chance to enforce authorization, range limits, expiry, and audit logging on every read.

Python implementation

The same boundary is straightforward with Python.

Python
from dataclasses import dataclassfrom datetime import UTC, datetime, timedeltafrom typing import Protocol​@dataclass(frozen=True)class ArtifactRef:    artifact_id: str    media_type: str    byte_length: int    preview: str    expires_at: datetime​class ArtifactStore(Protocol):    async def put(        self,        *,        tenant_id: str,        run_id: str,        media_type: str,        content: bytes,        expires_at: datetime,    ) -> str: ...​async def prepare_tool_result(    raw: str,    *,    tenant_id: str,    run_id: str,    store: ArtifactStore,    inline_limit: int = 24_000,) -> str | ArtifactRef:    encoded = raw.encode("utf-8")​    if len(encoded) <= inline_limit:        return raw​    expires_at = datetime.now(UTC) + timedelta(hours=24)    artifact_id = await store.put(        tenant_id=tenant_id,        run_id=run_id,        media_type="text/plain",        content=encoded,        expires_at=expires_at,    )​    return ArtifactRef(        artifact_id=artifact_id,        media_type="text/plain",        byte_length=len(encoded),        preview=build_preview(raw, 4_000),        expires_at=expires_at,    )

Again, byte limits are a coarse operational guard. If exact prompt budgeting matters, estimate or count tokens for the representation that will actually be sent.

Structured artifacts deserve structured queries

If a tool returns 100,000 database rows, turning those rows into a text artifact and asking the model to search them line by line is usually the wrong abstraction.

Keep the data queryable.

A query tool might return:

JSON
{  "resultSetId": "rs_7Jp2",  "columns": ["customer_id", "plan", "monthly_spend"],  "rowCount": 18432,  "previewRows": [    ["c_12", "pro", 12900],    ["c_18", "starter", 2900]  ]}

Then provide operations such as:

  • filter result set;
  • sort;
  • aggregate;
  • select columns;
  • fetch a bounded page.

The model reasons over the result it needs rather than using its context window as a database engine.

That is particularly valuable for coding agents too. Instead of loading an entire repository, expose symbol search, file slices, reference lookup, and git diff operations.

Do not summarize away evidence you may need to cite

A common compromise is to replace a large result with an LLM-generated summary.

Summaries are useful, but they are lossy. If the final answer needs to cite exact log lines, document clauses, or rows, keep the underlying artifact available and preserve stable offsets or identifiers.

For a document-analysis system, I may store:

TypeScript
type DocumentSlice = {  artifactId: string;  startOffset: number;  endOffset: number;  sourcePage?: number;};

The model can reason over a summary and retrieve the original slice before making a high-confidence claim.

That is much safer than treating a generated summary as the new source of truth.

Artifact lifetime is part of workflow lifetime

A durable agent may pause for human approval and resume tomorrow. If every offloaded tool result expires after one hour, replaying the workflow may fail because its referenced artifacts disappeared.

I align retention with the run lifecycle:

  • ephemeral artifacts can expire shortly after a completed run;
  • artifacts referenced by a paused run need to survive the pause;
  • legally or operationally sensitive data may require shorter retention or explicit deletion;
  • reproducibility may justify content-addressed storage for selected artifacts.

An artifact reference stored in a checkpoint is only useful if the underlying object has compatible retention.

Avoid turning the artifact store into a data leak

Large tool output often contains the messiest data in the system: logs, stack traces, customer payloads, headers, document bodies, and query exports.

I would apply the same controls I expect from other application storage:

  • tenant/user authorization;
  • encryption at rest where appropriate;
  • secret/PII redaction when the use case allows it;
  • bounded retention;
  • audit logs for sensitive reads;
  • no guessable public object paths;
  • deletion propagation.

Do not solve token cost by quietly creating an ungoverned dump bucket.

Measure what offloading actually saves

Useful telemetry includes:

  • raw tool-result bytes/tokens;
  • inline bytes/tokens;
  • artifact count per run;
  • read-back frequency;
  • average number of targeted reads;
  • artifacts never read again;
  • latency added by storage;
  • context tokens saved.

If nearly every artifact is immediately read back in full, the preview or tool interface may be poor. If most artifacts are never reopened, offloading is doing exactly what you want: keeping irrelevant bulk out of the context window.

When inline output is better

I would not offload a six-line API response. Handles add indirection and another storage dependency.

Small, high-value results are easier for both developers and models when they remain inline.

The pattern pays off when tools can return data whose size is unpredictable or routinely much larger than the reasoning value it contains.

The broader lesson is that a model context window is not an object store, log archive, SQL client, or repository checkout. Give the agent a compact representation of what happened and a safe way to ask for more. Once tool output is treated as an artifact with navigation instead of an automatic chat message, long agent runs get cheaper and much easier to control.

KEEP READING

Related engineering notes