跳到正文
OpenRouter:Announcements·精选AI 评分74

OpenRouter 实测如何降低 AI Agent 的 token 用量

How to Reduce Token Usage in AI Agents (Measured)

AI 导读

OpenRouter 在其 API 上重放一个 40 步、约 260K token 的编码 agent 会话,在六种上下文设置下实测 token、缓存命中、成本与准确率。

推荐理由

OpenRouter 用同一 40 步会话在六种上下文设置下实测 token 与成本,给出了可复用的缓存保持与压缩做法。

正文 · 原文
How to Reduce Token Usage in AI Agents (Measured)

An AI agent resends its whole conversation to the model on every step, so a long session’s token count and its bill grow with every call. This guide shows you how to bring both down, using measurements instead of guesswork.

We replayed one 40-step coding session through the OpenRouter API under six context setups, including one failed first attempt at compaction, and measured the tokens, cache hits, cost and accuracy of each. The most expensive run sent exactly the same tokens as a much cheaper one, and the difference came down to one line in the system prompt.

Tl;dr

  • Keep the start of your prompt identical and send a constant session_id. A timestamp at the top of the system prompt broke prompt caching and made the same session cost 7.8 times more ($0.658 vs $0.084).
  • Cap each tool result once, when it enters the history. This was the cheapest setup at $0.054, with input down 36% and 95% of it still cached.
  • Don’t trim old tool outputs on every step. It cut input tokens by 60% but cost 3.1 times more, because editing old messages broke the cache.
  • Compact long sessions in chunks, and never summarize an earlier summary. Compaction shrank the final prompt from 260K to 63K tokens, while re-summarizing dropped accuracy to 1 of 4.
  • Lower reasoning.effort on routine steps instead of switching reasoning off.

Why do AI agents use so many tokens?

An agent calls the model once per step, and each call carries the system prompt, the tool definitions, every earlier message and every tool result. Tool results often take up much of that history. A file read or a failing test log can add thousands of tokens, and it stays in the prompt for every later step.

Prompt caching is what keeps this affordable. Providers charge far less for input they’ve already seen, but only for an identical prefix, meaning the same tokens in the same order from the very start of the prompt. If anything near the start changes, such as a timestamp in the system prompt or an edited old message, everything after it is billed as new input.

Reasoning tokens add to the bill as well, since they’re billed as output (see Step 4).

How we measured it

We wrote a small replay script on top of the session generator from our context-rot test. It produced a synthetic coding-agent session of about 1 million characters (260K tokens), with hundreds of tool calls returning TypeScript files, grep output, .env files and test logs.

We replayed that history as 40 requests at evenly spaced points, each sending the conversation up to that point the way an agent would. We capped output at 200 tokens per request because we were measuring input. A final request asked four questions with exact answers:

  • a ticket ID mentioned once
  • the latest value of a setting that changed four times
  • an early rule from the user
  • how many test runs failed (three)

Every request used openai/gpt-6-luna with reasoning.effort: "low" and one session_id per session. On October 22, 2026, the model cost $0.10 per million input tokens, $0.01 per million cached input tokens and $0.50 per million output tokens. Uncached input was billed as a cache write at $0.125 per million. We ran three sessions (seeds) per setup.

What actually reduced cost?

We compared five setups, plus a sixth that started as a mistake:

  1. Changing prefix. The system prompt started with Current time: <timestamp>, different on every request.
  2. Stable prefix. Nothing changed at the start. The setups below all build on this one.
  3. Re-trimmed old tool outputs. Before each request, every tool result except the four most recent was cut to its first and last 400 characters, so earlier messages changed on every request.
  4. Capped tool outputs. Each tool result was cut once, when added, to its first and last 800 characters with a note of how much was removed.
  5. Compaction. Whenever the history since the last compaction passed 300,000 characters, everything except the last eight messages was summarized in 16,000-character chunks by scaledown/summarize. Earlier summaries were kept unchanged, and the new one went after them.
  6. Re-summarized. This was our first attempt at compaction, run on one session. It summarized the previous summary again along with the new turns.
SetupInput tokens per sessionInput cachedCost per sessionFinal promptCorrect answers
Changing prefix5.25M0%$0.658260K tokens10 of 12
Stable prefix5.25M95%$0.084260K9 of 12
Re-trimmed old tool outputs2.09M0%$0.263101K10 of 12
Capped tool outputs3.35M95%$0.054165K10 of 12
Compaction2.08M85%$0.068($0.057 + $0.011 for 61 summarize calls)63K9 of 12
Re-summarized1.93M84%$0.067($0.055 + $0.012 for the summarize calls)43K1 of 4

Correct answers are totals across three sessions of four questions each. The re-summarized setup ran on one session.

The timestamp cost far more than the lost discount. The changing-prefix and stable-prefix runs sent the same 5.25M input tokens, but one line at the top of the system prompt took the cached share from 95% to zero. Every request then paid $0.125 per million tokens to write a prefix the next request couldn’t use, instead of $0.01 to read one. The uncached run was also the slowest, at 170 seconds for 40 requests against 149 for the stable prefix.

Fewer tokens isn’t the same as lower cost. Re-trimming old tool outputs cut input from 5.25M to 2.09M tokens. It still cost $0.263, because each step edited messages the previous step had cached.

Capping once was the cheapest setup. It cut input by 36% and kept 95% of it cached, for $0.054. That’s 36% less than the stable prefix alone.

Compaction made the smallest prompt. The final request was 63K tokens instead of 260K, and the 40 requests finished in 111 seconds. Counting the summarize calls, it still cost a little more than capping.

Accuracy barely moved, except in one setup. The five main setups scored 9 or 10 out of 12. A one-question gap is noise here, since the two prefix runs sent identical text and still differed by one. Most misses were the count of failed test runs, the kind of question that gets harder in long contexts. The re-summarized session scored 1 of 4, and Step 3 explains why.

We ran this test on one model with OpenAI’s automatic caching, so your savings will differ on providers with different caching prices.

Step 1: Keep the start of the prompt identical

Take timestamps, request IDs and any other changing values out of the system prompt, and keep your tool definitions in a fixed order. If the model needs the current date or time, put it in the latest user message at the end of the prompt, where it doesn’t touch anything already cached.

Then send the same session_id on every request in the session, either in the request body or as an x-session-id header. OpenRouter uses it as the sticky routing key, so each step goes to the provider that already holds your cache. Without a session_id, sticky routing only starts after we detect a cache hit. With one, it starts from the first successful request.

Sticky routing sessions expire after 60 minutes without a request, separate from the provider’s own prompt-cache lifetime. The provider’s cache can expire sooner, so an agent that waits a long time for a human may still come back to a cold cache. The Provider Sticky Routing section of the prompt caching guide covers the details, and our tutorial on prompt caching and sticky routing walks through a full example.

Step 2: Cap tool results once; never edit old messages

When a tool returns a large result, cut it before you add it to the message list, then leave it alone. We kept the first and last 800 characters, with a note in the middle saying how much was removed:

const HEAD = 800;
const TAIL = 800;

function capToolResult(text: string): string {
  if (text.length <= HEAD + TAIL) return text;
  const removed = text.length - HEAD - TAIL;
  return `${text.slice(0, HEAD)}\n[... ${removed} characters removed ...]\n${text.slice(-TAIL)}`;
}

// Cap once, when the result enters the history. Never edit it again.
messages.push({
  role: "tool",
  tool_call_id: call.id,
  content: capToolResult(output),
});

The note tells the model the output is incomplete, so it doesn’t treat the cut version as the whole file.

Don’t trim on a sliding window, where every tool result older than the last few is shortened before each request. The window moves on every step, so a message cached on step 12 is edited on step 13, and the cache is lost from that message onward. That’s why our re-trimmed setup cost 3.1 times more than doing nothing.

Step 3: Compact long sessions (and don’t summarize summaries)

Capping keeps each result small, but the history still grows. When a session runs long, summarize the older turns, keep the recent ones word for word, and leave every earlier summary exactly as it was. We followed our cookbook to compact long agent sessions with ScaleDown Summarize, with the settings listed above. Because earlier summaries never change, they stay cacheable after each compaction, which is why 85% of input was still cached.

On a model with cheap cache reads, compaction saves less money than capping. Reach for it when prompt size is the problem, such as when you’re close to the context window, when latency matters or when the model has no cheap caching. In our context-rot test, compaction also improved accuracy on long sessions, with 54 of 60 correct against 49 of 60 with the full history.

Our first version of compaction got this wrong. It fed the previous summary back into the summarizer along with the new turns, so each pass compressed the early details again. In the one session we ran this way, the summary lost both the ticket ID and the user’s early rule, and the model answered 1 of 4 correctly. We think repeated summarizing caused the loss, but we didn’t test that on its own.

Step 4: Set a reasoning budget

On routine agent steps, a model can spend more output tokens on reasoning than the step needs. In our token cost test, deepseek/deepseek-v4.1-flash used its whole 4,000-token output budget reasoning about a simple triage request and returned an empty reply, which was still billed. Setting reasoning.effort: "low" fixed it. This replay didn’t measure the effort setting, since every request in it already used low effort.

Use low effort for routine steps, and save higher effort for the steps that need real planning.

Don’t try to switch reasoning off with "reasoning": {"enabled": false} on models that require it. Those endpoints reject the request with Reasoning is mandatory for this endpoint and cannot be disabled., and they reject effort: "none" as well. Lowering reasoning.effort works on them. The reasoning tokens guide lists the options.

How to check your agent’s token usage

Log usage.prompt_tokens, usage.prompt_tokens_details.cached_tokens and usage.cost from every response to see your cache hits and spend per step. Here’s a request with the settings from this guide:

const res = await fetch("https://openrouter.ai/api/v1/chat/completions", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "openai/gpt-6-luna",
    session_id: sessionId, // same value on every step of this run
    reasoning: { effort: "low" },
    tools, // keep the same tool definitions on every step
    messages,
  }),
});

const { usage } = await res.json();
console.log({
  step,
  prompt: usage.prompt_tokens,
  cached: usage.prompt_tokens_details?.cached_tokens ?? 0,
  cost: usage.cost,
});

Look at step 2 first. Step 1 has nothing to read from the cache. On a model with automatic caching and a prompt of at least 1,024 tokens, most of the prompt should show as cached by step 2. On Anthropic models you also need to add cache_control breakpoints.

Next steps

Check cached_tokens on step 2 of your agent, using the usage accounting cookbook. If it’s low, fix the prefix and add a session_id with the prompt caching guide. When your sessions get long enough to crowd the context window, add chunked compaction with the ScaleDown Summarize cookbook.

Frequently asked questions

Why does my agent use so many tokens?

An agent resends the full conversation on every step, including the system prompt, tool definitions, every earlier message and every tool result. Input grows with each step, so a 40-step session pays for its early messages and large tool outputs dozens of times. Prompt caching makes that repeated input much cheaper, as long as the start of the prompt doesn’t change.

Does prompt caching work with agents?

Yes. Each agent step adds new messages to the end of the history and leaves the earlier ones unchanged, which gives caching the identical prefix it needs. In our 40-step test on openai/gpt-6-luna, a stable prompt and a constant session_id kept 95% of input cached. The session cost $0.084, compared with $0.658 when a timestamp at the top of the system prompt broke the cache.

Is trimming context worth it?

Yes, if you trim each tool result once when you add it, or compact old turns in occasional chunks. In our test, capping tool results once was the cheapest setup at $0.054 per session. Re-trimming old tool outputs on every step backfired. It cut input tokens by 60% but broke the cache on every request, raising the cost to $0.263 compared with $0.084 for leaving them alone.

来源:OpenRouter:Announcements · openrouter.ai