コンテンツへスキップ
16/30第16章 / 全30章

Context Window、token、請求額を実測する

40ターンの会話は本文の22倍の入力tokenとして課金されます。cachingで68%減り、置き場所の悪いタイムスタンプで20%増えます。

このページの内容

ここに、40ターンのサポート会話があります。ターンごとに課金したものです。内容はごく普通です。開発者がAPIについて質問し、assistantが1、2段落で答えています。やり取り全体は5,090 tokenのテキスト、約8ページ分です。

ターンprompt tokens新規テキストoutputこのターンのcost累計
121318183$0.002622$0.002622
589214123$0.003260$0.014354
101,65619114$0.004680$0.035530
202,86818103$0.006972$0.094426
303,9412099$0.009070$0.174170
404,94717142$0.011598$0.274386

2列目と3列目を合わせて見てください。40ターン目でユーザーが入力したのは17 tokenですが、課金されたのは4,947 tokenです。質問が最初より難しくなったわけではありません。むしろ短くなっています。変わったのは、そのリクエストが会話全体を載せて、40回目として、また送られたことです。

この40回の呼び出しで課金された入力tokenの合計は 112,617。会話自体の長さは5,090 tokenです。あなたはそれに 22回分 支払ったことになります。

この章では、なぜそうなるのか、各providerの請求書でそれが何と呼ばれるのか、そして課金対象になる5つの要素のうち、どれに手を打てるのかを扱います。

詳細を表示

この章がPart IIから必要とするもの。

  • Chapter 7 ではtokenizerを作りました。ここでも単位はtokenです。同じ単位に、今度は価格が付きます。
  • Chapter 9 ではself-attentionとその O(n2)O(n^2) costを、漸近記法のボックスで導出しました。そのcostこそが上限が存在する理由なので、ここでは再説明せずリンクします。
  • Chapter 13 ではprefillとdecodeを測定し、KV cacheが占める容量を計算しました。上の入力列とoutput列が実際に買っているのは、この2つのphaseです。

それ以外はTypeScriptです。これはremote callの会計であって、modelの数学ではないからです。

この業界で最も高くつく誤解は、modelが会話を覚えているというものです。

覚えていません。そしてChapter 13の仕組みが、その理由を正確に説明しています。生成中のtransformerのstateはKV cacheです。sequence内のすべてのtokenについて計算されたkeyとvalueです。このcacheは1つのrequestの間だけ存在します。requestが終わると、それを保持していたprocessは別の誰かに使われ、cacheは消えます。向こう側にユーザーごとのstoreはなく、sessionもありません。

したがって次のrequestは、modelに知っていてほしいことをすべて載せて届かなければなりません。そしてmodelは、新しいtokenを1つemitする前に、prompt全体にforward passを走らせてそのstateを作り直します。Chapter 15 ではpromptを「state全体」と呼びました。物理的な理由はこれです。promptが完全なstateなのは、呼び出しをまたいで生き残るものが他にないからです。

context window は、そのpromptと回答を足した最大長です。どれだけのstateを再構築できるかの上限であり、request間で何かを保持する容器ではありません。それを「modelのmemory」と呼ぶと、因果の向きを逆に見ています。memoryを満たしているのではなく、memoryを再確立するために支払っているのです。

22倍はここから来ます。ターン nn はそれ以前の n1n-1 ターンすべてを運ぶため、nn ターンの会話全体の入力は、増え続ける級数の和になり、二次になります。

total input  =  i=1n(s+hi)  =  Θ(n2)\text{total input} \;=\; \sum_{i=1}^{n} \big(s + h_i\big) \;=\; \Theta(n^2)

ここで ss はsystem prompt、hih_i はターン ii のhistoryです。40ターンにわたる実測の累積入力を an2+bnan^2 + bn に当てはめると 60.22n2+432.25n60.22\,n^2 + 432.25\,n となり、40ターン目で113,645 tokenを予測します。実測は112,617 tokenです。二次項が支配的で、線形項がユーザーが実際に入力した分です。

この章から持ち帰るべき結論はこれです。請求額は最後の質問ではなく、会話の二乗に比例して増えます。 同じ40個の質問をhistoryなしで投げると $0.066036 です。historyを保持すると $0.274386 です。historyは請求額を4.2倍にしました。そして会話長そのものが倍率なので、これからも増やし続けます。

windowが有限なのは、同じ方向に働く2つの理由があるからです。1つ目はChapter 9の理由です。attentionはすべてのtokenを他のすべてのtokenと比較するため、そのlayerの仕事量はsequence lengthの二乗で増えます。2つ目はmemoryです。KV cacheはsequence lengthに対して線形に増えます。Chapter 13でその計算をしました。長いsequenceでは、weightsよりも大きくなります。

どちらの制約にも対策は打たれてきましたが、どちらも消えたわけではありません。FlashAttention1 は計算を組み替え、高帯域memoryへのread/writeを大幅に減らします。これにより、漸近的なcostを変えずに長いsequenceを実用的にします。Position Interpolation2 とYaRN3 は、再trainingではなくChapter 9のpositional encodingを再スケーリングすることで、training済みmodelの使えるwindowを拡張します。これらが合わさって、windowは5年で2Kから1Mになりました。

ただし、それらはlong contextを無料にしたわけではありません。天井を高くし、傾きを緩やかにしただけです。傾きはまだ残っています。そしてこの章の後半で出てくるprice tierが測っているのは、その傾きです。

インターネット上のほぼすべてのcost calculatorは、API callを「input tokens × input price + output tokens × output price」としてmodel化します。2023年には正しかった式です。今では間違っており、請求額が上下どちらにも2倍以上ずれることがあります。

課金対象のtoken categoryは 5つ あります。

bucket何か入力に対する典型的な価格
uncached inputmodelが新たに処理する必要があったprompt tokens
cache read保存済みprefixから提供されたprompt tokens0.1×
cache writeこのcallでcacheに保存されたprompt tokens1.25×〜2×
outputmodelが生成し、あなたに送ったtokens5×〜6×
reasoningmodelが生成したが、あなたには送らなかったtokensoutput rate

この5つのうち3つは2年前には個別の行として存在していませんでした。そして人が間違えるのは2つのcache行です。cache writeは通常のinputより高いのであって、安いのではありません。何かを保存するためにpremiumを払い、それを読み戻すときにdiscountを受けます。その取引が得かどうかは、何回読むかだけで決まります。

reasoning bucketは Chapter 12 のものに価格が付いたものです。ここには明示しておく価値のある細部があります。Googleのdocumentationには、pricingは「APIから出力されるのがsummaryだけであっても、modelが生成する必要のあるfull thought tokensに基づく」とあります。4 あなたに送信されないtokensにも課金されます。これは、中身を数えることも、検査することも、検証することもできない唯一のbucketです。

ここからは単なる掛け算ではなく、normalisationの問題になります。providerごとにこれらのbucketを別の名前で報告し、しかもここが罠ですが、2つのproviderが同じ単語を別の量に使っています。

1つのcallを考えます。cacheから読まれた4,837 token、新規の110 token、可視output tokenが142、reasoning tokenが300です。

three usage payloads, one callJSON
// OpenAI-compatible
{ "usage": { "prompt_tokens": 4947,
             "prompt_tokens_details": { "cached_tokens": 4837 },
             "completion_tokens": 442,
             "completion_tokens_details": { "reasoning_tokens": 300 } } }

// Anthropic
{ "usage": { "input_tokens": 110,
             "cache_read_input_tokens": 4837,
             "cache_creation_input_tokens": 0,
             "output_tokens": 442 } }

// Gemini
{ "usageMetadata": { "promptTokenCount": 4947,
                     "cachedContentTokenCount": 4837,
                     "candidatesTokenCount": 142,
                     "thoughtsTokenCount": 300 } }

prompt_tokens: 4947input_tokens: 110 を見てください。どちらのfieldも、同じ promptの入力token数です。OpenAIのものはcached tokensを含みます。Anthropicのものは含みません。documentationは恒等式 total_input_tokens = cache_read_input_tokens + cache_creation_input_tokens + input_tokens を明示しています。5 Anthropicの input_tokens は「最後のcache breakpoint以降のtokens」を意味します。

そしてoutputを見てください。OpenAIとAnthropicはいずれも442を報告します。これはすでに300のreasoning tokensを含んでいます。Geminiは142を報告し、300は独自のfieldに入れます。Chapter 12では、同じ仕事を数える2つの方法の非互換性としてこれを指摘しました。ここではそれにいくらかかるかを見ています。

normalizerは30行で、任意ではありません。

normalise.tsTS
export interface Usage {
  promptTokens?: number;        // input, NOT cached
  cachedInputTokens?: number;   // read from cache
  cacheWriteTokens?: number;    // written to cache on this call
  completionTokens?: number;    // output
  reasoningTokens?: number;     // billed apart from output (Gemini only)
}

const num = (v: unknown) => (typeof v === "number" && isFinite(v) ? v : 0);

export const fromOpenAI = (raw: any): Usage => {
  const u = raw.usage ?? {}, d = u.prompt_tokens_details ?? {};
  const cached = num(d.cached_tokens), write = num(d.cache_write_tokens);
  return {
    promptTokens: Math.max(0, num(u.prompt_tokens) - cached - write), 
    cachedInputTokens: cached,
    cacheWriteTokens: write,
    completionTokens: num(u.completion_tokens),   // reasoning already inside
    reasoningTokens: 0,
  };
};

export const fromAnthropic = (raw: any): Usage => {
  const u = raw.usage ?? {};
  return {
    promptTokens: num(u.input_tokens),            // already excludes cache
    cachedInputTokens: num(u.cache_read_input_tokens),
    cacheWriteTokens: num(u.cache_creation_input_tokens),
    completionTokens: num(u.output_tokens),
    reasoningTokens: 0,
  };
};

export const fromGemini = (raw: any): Usage => {
  const m = raw.usageMetadata ?? {}, cached = num(m.cachedContentTokenCount);
  return {
    promptTokens: Math.max(0, num(m.promptTokenCount) - cached),
    cachedInputTokens: cached,
    cacheWriteTokens: 0,
    completionTokens: num(m.candidatesTokenCount), // EXCLUDES thinking
    reasoningTokens: num(m.thoughtsTokenCount),    // billed at output rate
  };
};

上の3つのpayloadを3つのreaderに通すと、3つとも同じ Usage を生成し、したがって同じ数値になります。$0.006491 です。この一致こそが、そのlayerを書く理由です。

間違えると、同じcallでこうなります。

間違いbillederror
cached_tokensprompt_tokens に対する追加分として扱う$0.0161652.49× — promptを二重に請求する
cache readを0.1×ではなく無料として扱う$0.0055240.85× — 15%を自腹で飲む
candidatesTokenCount を読み、thoughtsTokenCount を無視する$0.002891callの55%が消える

3つ目が危険です。良いニュースの方向に静かに失敗するからです。dashboard上ではreasoning modelのcostが実際の半分未満に見え、どこにもerrorは出ません。

bucketをnormaliseできれば、cost functionは短くなります。自明でないのはtier lookupだけで、次のsectionで説明します。

cost.tsTS
export interface Tier { maxPromptTokens: number | null; price: number }
export interface Pricing {
  input: Tier[]; output: Tier[];
  cachedInput?: Tier[]; cacheWrite?: Tier[]; reasoning?: Tier[];
}

const tierPrice = (tiers: Tier[] | undefined, contextSize: number, fallback?: Tier[]) => {
  const table = tiers ?? fallback;
  if (!table?.length) return 0;
  const sorted = [...table].sort(
    (a, b) => (a.maxPromptTokens ?? Infinity) - (b.maxPromptTokens ?? Infinity));
  for (const t of sorted)
    if (t.maxPromptTokens === null || contextSize <= t.maxPromptTokens) return t.price;
  return sorted[sorted.length - 1].price;
};

export function computeCost(pricing: Pricing, usage: Usage): number {
  const fresh = usage.promptTokens ?? 0;
  const read  = usage.cachedInputTokens ?? 0;
  const write = usage.cacheWriteTokens ?? 0;
  const out   = usage.completionTokens ?? 0;
  const think = usage.reasoningTokens ?? 0;
  const contextSize = fresh + read + write;   // the tier depends on the WHOLE prompt
  return fresh * tierPrice(pricing.input, contextSize)
       + read  * tierPrice(pricing.cachedInput, contextSize, pricing.input)
       + write * tierPrice(pricing.cacheWrite,  contextSize, pricing.input)
       + out   * tierPrice(pricing.output, contextSize)
       + think * tierPrice(pricing.reasoning, contextSize, pricing.output);
}

ここには擁護する価値のある設計判断が2つあります。fallback、つまりcache priceはinputへ、reasoningはoutputへfallbackするという点は、tableが欠けていることの意味をencodeしています。Geminiのreasoning tokensはoutput rateで課金されるので、reasoning priceがないことはzeroではなく、output priceを意味します。そして contextSize はfresh分だけでなく3つすべてのinput bucketを合計します。tierは、どれだけがfull priceで課金されたかではなく、promptの長さで選ばれるからです。

prompt cacheは、promptのprefixについてmodelが計算済みのstateを保存し、後続requestで同じprefixが来たときに再計算をskipします。「prefix」という言葉から4つの性質が出てきます。そして4つとも人を驚かせます。

cacheはrender済みpromptの先頭から前方に向かって一致を確認し、最初に異なるbyteで止まります。後ろの方に同じcontentが別の順序で現れても、部分点はありません。OpenAIは端的に述べています。「cache reuse requires the entire rendered prefix to match」。6

それ未満では何もcacheされず、errorも返りません。OpenAIでは、最小長はGPT-5.6以降で1,024 token、古いmodelでは2,048です。Anthropicではmodelによって512から4,096まで幅があります。Claude Sonnet 4.5では1,024、Claude Haiku 4.5では4,096です。cache fieldが2つともzeroで返ってきたら、たいてい理由はこれです。

OpenAIとAnthropicでは、短命cacheへのcache writeはuncached input rateの1.25×で、Anthropicの1時間cacheは2×です。readは0.1×です。Googleはwriteには課金しませんが、storageを賃貸します。Gemini 2.5 Proでは100万token・時間あたり $4.50 です。

Anthropicのdefault entryは5分間生き、hitするたびに無料でrefreshされます。OpenAIでは、最後のwriteまたはreuseから少なくとも30分です。またOpenAIは、cached stateが個々のmachine上に存在するため、requestがそのentryを保持するmachineにrouteされた場合だけhitすると述べています。prompt_cache_key が影響するのはここですが、保証はしません。

break-evenは頭に入れておけるほど小さく、OpenAIのdocumentationが計算しています。prefixを一度writeして一度reuseすると、通常input costの1.35×になります。uncachedで2回処理する場合は2×です。10 requestでは、1回のwriteと9回のreadで2.15×、対してuncachedは10×です。1回reuseすればwriteの元が取れます。 Anthropicでも同じ地点に落ちます。5分cacheなら1 read、1時間cacheなら2 readです。

では40ターンの会話をもう一度見ます。cachingを有効にし、prefixが安定している場合です。

uncached inputcache readscache writestotal
no cache112,617$0.274386
caching2,887104,7834,947$0.088250

68%安くなります。そしてこの表の3つの数値は注意に値します。

cacheはターン6まで効きません。 promptはそこまで1,024 tokenに届かないため、最初の5ターンは以前とまったく同じように課金されます。そして6ターン目は、cacheを満たすターンなので1.25×のwrite premiumにより、むしろ悪く課金されます。最初のreadはターン7です。表の2,887 uncached tokensはその算術です。6ターン分ではなく、5ターン分です。cachingは長いpromptへのdiscountであり、短い会話は何も得ません。

write premiumは $0.002474 で、cached billの2.8%です。各ターンが新しいtailをwriteし、40回行われます。それでもwrite premium全体は、readが節約した額に比べれば丸め誤差です。write chargeは、心配をやめるためにこそ正確に理解する価値があります。

112,617 tokenのうち、full input priceで課金されたのは2,887 tokenだけ でした。これがうまく動くcacheの形です。ほとんどすべてがreadになります。

実際にお金を失うfailureは、1行のbugです。

毎回変わるものをpromptの前方に置いてください。timestamp、request id、ユーザー名、「today is」行、新しくretrievedされたdocumentなどです。するとprefixはbyte 1から異なります。何も一致しません。すべてのcallがmissになります。そしてすべてのcallが新しいprefixを提示するため、すべてのcallがwriteもします。

同じ会話、同じ40ターン、caching有効、ただしsystem promptの先頭にcallごとのtimestampを置いた場合です。

totalversus
cachingなし$0.274386
caching、安定prefix$0.088250−67.8%
caching、揮発prefix$0.329251+20.0%

prompt cachingを有効にした結果、会話は有効にしない場合より20%高くなりました。109,730 tokenに1.25×のwrite premiumを払い、読み戻しはzeroです。errorもwarningもなく、featureはonです。

したがってrule、prompt cachingの全体を1行で言うと、こうです。安定contentを前に、可変contentを後ろに。 system instructions、tool definitions、reference materialを先に置き、timestamps、user identity、current questionを最後に置く。Anthropicは階層を明示しています。cacheは toolssystemmessages に従い、どのlevelで変更があっても、そのlevelとそれ以降すべてがinvalidateされます。つまり1つのtool descriptionを編集するだけでcache全体がinvalidateされます。5

人がつまずく帰結が2つあります。enabled になっているtoolを変えるとtool definitionsが変わるため、一部ユーザーにtoolを追加するfeature flagはcacheを2つに分割します。またAnthropicでは、web searchやcitationsをtoggleするとsystem promptが変更され、自分のtextを一行も触っていなくてもsystem cacheとmessage cacheがinvalidateされます。

二次に増えるbillへの明らかな反応は、history全体を送るのをやめることです。直近12 messageだけ残し、残りを落とす。確かにbillは下がりますが、たいてい誤った手です。測定がその理由を示します。

strategytotalversus full history + cache
full history, no cache$0.274386+211%
full history, caching$0.088250
last 12 messages, no cache$0.118712+35%
last 12 messages, caching on$0.122546+39%

12 message windowへのtruncateは、すべてをuncachedで送るより57%安いです。誰もがする比較であり、このtechniqueがpopularな理由です。しかし、うまく動くcacheと一緒に全historyを送る場合より39%高く、truncationと同時にcachingをonにすると、良くなるどころか少し悪くなります。

mechanismはまたprefixです。sliding windowは各ターンで最古のmessageを落とすため、promptは前回と同じところから始まらなくなり、毎ターン新しいprefixを提示します。OpenAIのguidanceはまさにこう言っています。「summarisation, compaction, or context truncation can change the prefix and reset cache reuse」。6 40ターン目にはwindowed promptは813 tokenで、1,024-token minimumを下回るため、そもそもcacheできません。

そしてお金はcostの安い半分です。落としたものは、ターン40でmodelが必要とした、ターン2のユーザー指示です。truncationは、見えるbillと見えないfailureを交換します。それを適切に行う、つまりcompaction、window外に保持するstructured notes、必要時のhistory retrievalは、Chapter 24 の主題です。

long contextは、長いから高いだけではありません。thresholdを超えると、tokenあたりも高くなります。そしてthresholdはprompt全体に遡及的に適用されます。

gpt-5.6-terra のOpenAI model pageは、それを一文で述べています。「Prompts with >272K input tokens are priced at 2x input and 1.5x output for the full request」。7 超過分ではありません。全体です。

the most expensive token you will ever sendTEXT
prompt 271,999 + 500 output  ->  $0.5500
prompt 272,000 + 500 output  ->  $0.5500
prompt 272,001 + 500 output  ->  $1.0970

1 tokenで55セントです。retrieved documentsからpromptを組み立て、そのサイズをcontrolできないserviceなら、誰もteam内で書き留めていない境界にcost modelの崖があります。

Googleのpricingも同じ仕組みで、thresholdは200,000 tokenです。Gemini 2.5 Proは200Kまでのpromptで100万input tokenあたり $1.25、超えると $2.50 です。outputは $10.00 から $15.00 になります。8 Anthropicは反対の方向に進みました。2026年9月6日時点のdocumentationでは、Claude 4.6以降は100万token window全体をstandard pricingに含むため、「900k-token request is billed at the same per-token rate as a 9k-token request」とされています。9 以前のmodelにはsurchargeが残っていました。

だからpriceは1つの数値ではありません。priceはprompt lengthをkeyにしたtier tableです。それがcost function内の Tier[] の役割であり、computeCost がbucketごとではなくprompt全体でtierを選ぶ理由です。

5つのbucketはChapter 13の2つのphaseに対応します。その対応が見えると、price ratioは恣意的に見えなくなります。

Input tokensはprefillです。 prompt全体が1回のpassでmodelに通され、並列に処理されます。大きなmatrix multiplicationで、compute-boundです。tokenあたりcostは低く、このphaseが time to first token を決めます。4,947-token promptでは、最初の単語が現れる前に4,947 token分のprefillを行う必要があります。

Output tokensはdecodeです。 1つずつ生成され、それぞれがKV cache全体を読むfull forward passです。GPUは計算よりmemory待ちをしていることが多くなります。このphaseが tokens per second を決め、1つのresponse内ではparalleliseできません。そして、ここで価格を付けたmodelでoutputがinputの約6倍かかる理由でもあります。100万tokenあたり $12.00 対 $2.00 です。

3つの帰結が直接出てきます。cache readはprefill workを置き換えるため、latencyとお金を同時に買います。同じdiscountが、低いbillとfirst tokenまでの短い待ち時間として現れます。Reasoning tokensはあなたに見えないdecode です。reasoning modelが数秒間何もstreamせず、その後すばやく答える理由です。Chapter 12はinterface上の帰結を警告しましたが、これはinvoice上の帰結です。そして streamをabortしてもgenerationは止まりませんChapter 14 はcancellationを作り、価格はこの章に残しました。その価格はfull output countです。誰かがlistenしているかどうかに関係なく、tokensは生成され課金されるからです。誰も保持しないanswerにも同じことが言えます。ターン40のanswerを5回regenerateすると、画面に残った1つに対して $0.057990 かかります。

Chapter 7のtokenizerはPythonで、そのままそこに留まりました。budgetingはrequestを構築するserverで起きるので、ここで行う必要があります。そして利用できるaccuracy levelは正確に3つです。

Level one: locally countする。 js-tiktoken はPythonの tiktoken と同じBPE merge tableを同梱しているため、OpenAI encodingではnetwork callなしにbyte-for-byteで同一のcountが得られます。

count.tsTS
import { getEncoding } from "js-tiktoken";

const enc = getEncoding("o200k_base");
const PER_MESSAGE = 4;   // role and delimiters added by the chat template
const PER_REPLY = 3;     // priming for the assistant turn

export function promptTokens(messages: { role: string; content: string }[]) {
  return messages.reduce(
    (sum, m) => sum + enc.encode(m.content).length + PER_MESSAGE, PER_REPLY);
}

2つのconstantが重要で、local countがずれる場所でもあります。tokenizeされるのはあなたのtextそのものではありません。Chapter 11 のchat templateが、まず各messageをrole markerでwrapし、それらにも料金がかかります。OpenAI chat modelsでは、messageあたり4 token、reply primingに3 tokenというのが慣用的な近似です。上の会話の81 messageでは合計324 tokenになり、会話長の6.4%です。ここでのcountは、Chapter 7のPython tiktoken と全81 stringsでcross-checkされ、完全に一致しています。

Level two: providerに聞く。 Anthropicは /v1/messages/count_tokens を、Googleは count_tokens を公開しており、どちらも実callと同じrequest shapeを受け取り、input token countを無料で返します。locally countできない場合に使ってください。そしてAnthropicではlocally countできません。tokenizerが公開されていないからです。Anthropicのdocumentationは、それが何を返しているかについて慎重です。countは「estimate」であり、「Anthropicがsystem optimizationsのために自動追加するtokensを含む場合がある」が、それらには「課金されない」としています。10

Level three: responseの usage を読む。 それが真実であり、お金を使った後に届きます。だからこそ最初の2つのlevelが存在します。請求するためではなく、requestを送るべきか判断するためです。

line itemとしては現れない4つのline itemです。

system prompt、毎callで支払い。 上のものはtemplate overhead込みで192 tokenです。40 callでは7,680 token、この会話のbill全体の5.6%です。8行を一度書いただけのものに、です。同時に、安定していて先頭にあるため、最良のcache candidateでもあります。

Tool definitions。 すべてのtoolのname、description、JSON schemaは毎requestで送られ、providerはその上にscaffoldingを追加します。Anthropicはその数値を公開しています。toolを有効にするだけで、Claude Sonnet 4.5では tool_choiceauto に設定した場合に496 tokenのhidden system promptが追加され、any またはnamed toolでは588になります。9 これは自分のschemaの前です。Chapter 18 はcatalogueを作ります。Chapter 24はそれが何を食うかを測ります。

破棄したものを含む、すべてのgeneration。 5回regenerateすれば5倍かかります。chatに表示されるのは1つです。

表示されないthoughts。 課金は、summaryだけが返る場合でもfull thought tokensに基づきます。そしてあなた側のaccountingでは、その数値をauditできません。

最後に1つ警告しておきます。自然な次の発想ですが、答えは見かけほど明らかではありません。

100万token windowは、100万のusable tokensを意味しません。retrieval accuracyはpositionによって低下します。Liu et al.は、modelがlong inputの先頭と末尾では情報を比較的確実に見つける一方、中央ではかなり不安定になることを見いだしました。11 より大きなwindowが買うのは、より多く送れる能力であって、読まれる確実性ではありません。

この現象は、このcourseでは一度だけ測定します。同じ853-token prompt内の9つのpositionでのretrieval rateです。そしてそれはChapter 24に属します。agentの動作を変えるからです。ここで引用しているのは、何を買うべきかを変えるからです。最も安いtokenは、送らなかったtokenです。

これで、callする前にいくらかかるかを予測し、後で実際に何がかかったかを読み、その2つの違いを見分けられます。requestについては、まだ触っていない部分を除き、すべてを扱いました。その残りがknobsです。

Chapter 17 はsamplingです。temperature、top-p、top-k、penalties、そして存在しないdeterminismを扱います。まずこの分野で最も広く見られる誤り、temperatureはcreativity dialだという考えを解体します。そうではありません。temperatureは Chapter 4 のlogitsをsoftmaxの前で割るものであり、それを上げてもmodelが想像力豊かになるわけではありません。model自身がより悪いとscoreしたtokensのprobabilityを上げるだけです。そこから、なぜgreedy decodingがsamplingより測定可能に悪いtextを生むのか、なぜtop-kとtop-pがdistributionの反対の形で失敗するのか、そして章末の実験へ進みます。temperature 0で20回の同一forward passを行うと、modelが単独で走る場合はbit-for-bitで同一の結果が返ります。しかし同じpromptを他人のrequestと同じbatchに入れると、そのlogitsの97%が動きます。

すべてが一致するわけではありません。その理由は Chapter 2 のfloating-point boxから始まります。


この章のすべてのprices、thresholds、multipliersは、2026年9月6日 にprovider自身のpageから読んだものです。変わるため、その日付とともに記載しています。数字よりmethodが重要です。bucket、prefix rule、tier arithmeticは2年間安定していましたが、その中の数値はすべて動いてきました。

Stanford CS336 lecture 2、Resource accounting は、このmaterialに最も近いacademic treatmentであり、次に読むべきものです。この章がinference側で行ったのと同じ算術を、training側で行っています。ここでのtoken countsは、js-tiktoken 1.0.21を使い、o200k_basecl100k_base encodingsで、5,090 tokenの40ターン会話に対して生成しました。per-message template overheadは慣用的なfour-plus-three approximationであり、含める箇所では明記しています。cache、tier、truncationの数値は、これらの実測token countにdocumented pricing rulesを適用したものであり、live API responseの観測ではありません。この章を作るために有料callは行っていません。それが、latency claimがqualitativeで、cost claimがそうでない正直な理由でもあります。

  1. Dao, T., Fu, D. Y., Ermon, S., Rudra, A. and Ré, C. FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. arXiv:2205.14135 (2022)。漸近的costを変えずにceilingが動いた理由。

  2. Chen, S., Wong, S., Chen, L. and Tian, Y. Extending Context Window of Large Language Models via Positional Interpolation. arXiv:2306.15595 (2023)。

  3. Peng, B., Quesnelle, J., Fan, H. and Shippole, E. YaRN: Efficient Context Window Extension of Large Language Models. arXiv:2309.00071 (2023)。

  4. Google、Thinkingai.google.dev/gemini-api/docs/thinking、および Token countingai.google.dev/gemini-api/docs/tokens、いずれも2026-09-06 accessed。「Pricing is based on the full thought tokens the model needs to generate, despite only the summary being output from the API」。usage objectは total_input_tokenstotal_output_tokenstotal_thought_tokenstotal_cached_tokenstotal_tool_use_tokenstotal_tokens を報告する。6つのbucketで、thoughtsとtool useはoutput countの外にある。同じ量の以前のfield nameで、generateContent surfaceから今も返るものは thoughtsTokenCount であり、3つ目のpage ai.google.dev/gemini-api/docs/generate-content/thinking にdocumentされている。

  5. Anthropic、Prompt cachingdocs.anthropic.com/en/docs/build-with-claude/prompt-caching、2026-09-06 accessed。toolssystemmessages invalidation hierarchyとそのtable、modelごとのcache可能最小長、恒等式 total_input_tokens = cache_read_input_tokens + cache_creation_input_tokens + input_tokens、そして各hitで無料refreshされる5-minute default lifetimeのsource。 2

  6. OpenAI、Prompt cachingplatform.openai.com/docs/guides/prompt-caching、2026-09-06 accessed。以下のsourceです。entire-rendered-prefix rule、cache可能な最小prefix(GPT-5.6以降で1,024 visible input tokens、それ以前で2,048)、1.25× write multiplierと0.1× read multiplier、GPT-5.5以前でwrite chargeがないこと、30-minute lifetime、requestあたり4 writeと50 breakpointのlimit、machine-affinity noteと prompt_cache_key、1.35×、2.15×、10×のbreak-even worked examples、そしてsummarisation、compaction、truncationがcache reuseをresetするという記述。 2

  7. OpenAI、Pricingplatform.openai.com/docs/pricing)および gpt-5.6-terra のmodel page、いずれも2026-09-06 accessed。gpt-5.6-terra、standard service tier、100万tokenあたり: input $2.00、cached input $0.20、cache writes $2.50、output $12.00。long context input $4.00、cached $0.40、writes $5.00、output $18.00。「prompts with >272K input tokens are priced at 2x input and 1.5x output for the full request」。context windowは1,050,000 tokens、maximum input tokensは922,000。同じtableは gpt-6-astra を $10.00/$1.00/$12.50/$50.00、gpt-5.6-luna を $0.20/$0.02/$0.25/$1.20 としている。この章のworked costはすべて、gpt-5.6-terra standard short-context ratesを使用。

  8. Google、Gemini Developer API pricingai.google.dev/gemini-api/docs/pricing、2026-09-06 accessed。Gemini 2.5 Pro、100万tokenあたり: inputは200Kまでのpromptで $1.25、超過で $2.50。outputは $10.00 と $15.00、いずれも「including thinking tokens」とlabelされている。context cachingは $0.125 と $0.25、加えてstorage chargeが100万token・hourあたり $4.50。Gemini 3.1 Pro Previewは同じ200K thresholdを使い、input $2.00/$4.00、output $12.00/$18.00。

  9. Anthropic、Pricingdocs.anthropic.com/en/docs/about-claude/pricing、2026-09-06 accessed。100万tokenあたり、base input / 5-minute cache write / 1-hour cache write / cache read / output: Claude Sonnet 4.5 $3 / $3.75 / $6 / $0.30 / $15、Claude Haiku 4.5 $1 / $1.25 / $2 / $0.10 / $5、Claude Opus 5 $5 / $6.25 / $10 / $0.50 / $25。multipliers: 5-minute writeは1.25×、1-hour writeは2×、readは0.1×。long-context statement(「Claude 4.6 and later models... include the full 1M token context window at standard pricing」)、tool-use system prompt token counts(Claude Sonnet 4.5で tool_choiceauto または none の場合496 tokens、any またはnamed toolの場合588)、そしてClaude 4.7以降が「approximately 30 % more tokens for the same text」を生成するnewer tokenizerを使うというnoteのsourceでもある。 2 3

  10. Anthropic、Token countingdocs.anthropic.com/en/docs/build-with-claude/token-counting、2026-09-06 accessed。/v1/messages/count_tokens endpointはmessageと同じinputsを取り、input token countを返す。documentationは、そのcountがestimateであること、Anthropicがsystem optimisationsのために追加するtokensを含む場合があること、そしてそれらには課金されないことを述べている。

  11. Liu, N. F., Lin, K., Hewitt, J., Paranjape, A., Bevilacqua, M., Petroni, F. and Liang, P. Lost in the Middle: How Language Models Use Long Contexts. arXiv:2307.03172 (2023)。ここで引用し、Chapter 24で測定する。


作成者

David Vicente Campos

NeuraLIA Labs創業者、MyRealFood共同創業者

レオン大学出身のコンピューターエンジニアです。MyRealFoodを共同創業し、CTOとして、何百万人もの人がより良い食生活のために使ってきたアプリを開発しました。また、NeuraLIA Labsを創業し、そこでAIプロダクトを開発しています。ここでは、私がその過程で理解する必要があったことを、誰かにこう説明してほしかったと思う形で書いています。

著者について詳しく

NeuraLIA Labsが公開しています。

新着記事を受信トレイにお届け

AIニュース、ガイド、プロダクトアップデートを、読む価値のある記事を公開したときだけ短いメールでお送りします。

コース目次

Abstract software decision engine with branching paths, probability nodes, and glowing gates.
jev読了15分

Jev AIモデルは文章ではなく意思決定のために作られている

TypeSafe AIのJevが注目されているのは、ソフトウェアの知能を確率の問題として扱うからです。適切な分岐を選び、信頼度を添え、コードが必要としているのが意思決定であるときに、LLMに文章を書かせるためのコストを避けます。

Abstract legal research workspace with documents, search nodes and governance controls.
openai読了14分

OpenAIのAstra for Lawは新モデルではなく、法律AIシステム

OpenAIの法律分野での発表の本質は、新しい基盤モデルそのものではなく、その周辺にあるシステムです。ドメイン検索、信頼できるツール、権限、ベンチマーク、レビュー経路が重要になります。

Abstract agent runtime sorting documents, memory blocks and pointer nodes inside a bounded context frame.
context-engineering読了12分

Context engineering for long-horizon AI agents

Long-running agents do not fail only because the window is small. They fail when files, tool outputs and stale history crowd out the task the agent was supposed to finish.

モデル選びは、LIAにおまかせ。

すべてのAIモデルをひとつの場所で。今日から無料で。