مواد پر جائیں
16/30باب 16 از 30

context window، tokens اور بل: ناپ تول کے ساتھ

40-turn گفتگو input tokens میں اپنی لمبائی سے 22 گنا مہنگی پڑتی ہے۔ caching اسے 68٪ کم کرتی ہے؛ غلط جگہ timestamp 20٪ بڑھا دیتا ہے۔

اس صفحے پر

یہ ایک چالیس-turn support گفتگو ہے، turn بہ turn billed۔ اس میں کوئی غیر معمولی بات نہیں: ایک developer API کے بارے میں پوچھ رہا ہے، assistant ایک دو paragraphs میں جواب دے رہا ہے۔ پوری exchange text کے 5,090 tokens ہے — تقریباً آٹھ pages۔

turnprompt tokensنیا textoutputاس turn کی لاگتrunning total
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

دوسرے اور تیسرے columns کو ساتھ پڑھیں۔ turn 40 پر user نے سترہ tokens type کیے اور اسے 4,947 کے لیے charge کیا گیا۔ سوال پہلے سوال سے زیادہ مشکل نہیں تھا؛ بلکہ چھوٹا تھا۔ جو بدلا وہ یہ تھا کہ request پوری گفتگو کو اپنے ساتھ دوبارہ لے کر گئی، چالیسویں بار۔

ان چالیس calls میں billed کل input tokens: 112,617۔ گفتگو 5,090 tokens لمبی ہے۔ آپ نے اس کی قیمت بائیس بار ادا کی۔

یہ chapter اس بارے میں ہے کہ ایسا کیوں ہوتا ہے، ہر provider کے invoice پر اسے کیا کہا جاتا ہے، اور جن پانچ چیزوں کے لیے آپ سے charge لیا جا رہا ہے ان میں سے کن کے بارے میں آپ کچھ کر سکتے ہیں۔

تفصیلات دکھائیں

اس chapter کو Part II سے کیا چاہیے۔

  • Chapter 7 نے tokenizer بنایا تھا۔ یہاں بھی token ہی unit ہے — وہی unit، اب priced۔
  • Chapter 9 نے self-attention اور asymptotic-notation box میں اس کی O(n2)O(n^2) cost derive کی تھی۔ یہی cost وجہ ہے کہ limit سرے سے موجود ہے، اور اسے دوبارہ explain کرنے کے بجائے یہاں link کیا گیا ہے۔
  • Chapter 13 نے prefill کو decode کے مقابل measure کیا اور compute کیا کہ KV cache کتنی جگہ لیتا ہے۔ اوپر input اور output columns دراصل انہی دو phases کو خرید رہے ہیں۔

باقی سب TypeScript ہے، کیونکہ یہ remote call کی accounting ہے، model کی mathematics نہیں۔

اس business میں واحد سب سے مہنگی غلط فہمی یہ ہے کہ model ایک conversation یاد رکھتا ہے۔

وہ نہیں رکھتا، اور Chapter 13 کا mechanism بالکل بتاتا ہے کیوں۔ generation کے دوران transformer کی state KV cache ہوتی ہے: sequence کے ہر token کے لیے computed keys اور values۔ یہ cache ایک request کی مدت تک زندہ رہتا ہے۔ request ختم ہوتے ہی جس process نے اسے hold کیا تھا وہ کسی اور کو serve کرنے کے لیے آزاد ہے، اور cache ختم ہو چکا ہوتا ہے۔ دوسری طرف کوئی per-user store نہیں، اور کوئی session نہیں۔

اس لیے اگلی request کو ہر وہ چیز اپنے ساتھ لے کر آنی پڑتی ہے جو model کو معلوم ہونی چاہیے، اور model ایک بھی نیا token emit کرنے سے پہلے پورے prompt پر forward pass چلا کر وہ state دوبارہ بناتا ہے۔ Chapter 15 نے prompt کو ”entire state“ کہا تھا۔ physical وجہ یہ ہے: prompt مکمل state ہے کیونکہ call کے بعد کوئی اور چیز باقی نہیں رہتی۔

context window اس prompt plus اس کے answer کی maximum length ہے۔ یہ اس بات کی ceiling ہے کہ آپ کتنی state دوبارہ بنا سکتے ہیں، کوئی container نہیں جو requests کے درمیان کچھ hold کرتا ہو۔ اسے ”model کی memory“ کہنا causality کی سمت الٹ دیتا ہے — آپ memory بھر نہیں رہے، آپ اسے دوبارہ establish کرنے کے لیے pay کر رہے ہیں۔

بائیس کا عدد اسی سے آتا ہے۔ turn nn پچھلے تمام n1n-1 turns ساتھ لے جاتا ہے، لہٰذا nn turns کی conversation میں کل input ایک growing series کا sum ہے، جو quadratic ہے:

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 turn ii پر history۔ چالیس turns پر measured cumulative input کو an2+bnan^2 + bn پر fit کرنے سے 60.22n2+432.25n60.22\,n^2 + 432.25\,n ملتا ہے، جو turn 40 پر 113,645 tokens predict کرتا ہے بمقابلہ 112,617 measured۔ quadratic term dominate کرتا ہے اور linear term وہ ہے جو user نے واقعی type کیا۔

اس chapter سے لے جانے والا نتیجہ یہ جملہ ہے: آپ کا bill conversation کے square کے ساتھ بڑھتا ہے، آخری سوال کے ساتھ نہیں۔ یہی چالیس سوالات اگر بالکل history کے بغیر پوچھے جائیں تو $0.066036 خرچ ہوتے ہیں۔ history رکھنے کی cost $0.274386 ہوئی۔ history نے bill کو 4.2 سے multiply کیا، اور یہ multiply کرتی رہے گی، کیونکہ multiplier conversation length ہے۔

window finite دو وجوہات کی بنا پر ہے جو ایک ہی سمت کھینچتی ہیں۔ پہلی Chapter 9 والی ہے: attention ہر token کو ہر دوسرے token سے compare کرتا ہے، اس لیے اس layer کا کام sequence length کے square کے ساتھ بڑھتا ہے۔ دوسری memory ہے: KV cache sequence length کے ساتھ linearly بڑھتا ہے، اور Chapter 13 نے یہی arithmetic کیا تھا — long sequences پر یہ weights سے بڑا ہوتا ہے۔

دونوں limits پر حملہ کیا گیا ہے اور کوئی بھی ختم نہیں ہوئی۔ FlashAttention1 computation کو reorganise کرتا ہے تاکہ یہ high-bandwidth memory کو کہیں کم read اور write کرے، جس سے long sequences practical ہو جاتے ہیں مگر asymptotic cost نہیں بدلتی۔ Position Interpolation2 اور YaRN3 Chapter 9 کے positional encodings کو rescale کر کے trained model کی usable window extend کرتے ہیں، retraining کے بجائے۔ یہی وجہ ہے کہ windows پانچ سال میں 2K سے 1M تک گئیں۔

جو انہوں نے نہیں کیا وہ long contexts کو free بنانا ہے۔ انہوں نے ceiling اونچی کی اور slope نرم۔ slope اب بھی موجود ہے، اور اسی کو اس chapter میں بعد کے price tiers measure کرتے ہیں۔

internet پر تقریباً ہر cost calculator API call کو input tokens ضرب input price plus output tokens ضرب output price کے طور پر model کرتا ہے۔ یہ 2023 میں درست تھا۔ اب یہ اس طرح غلط ہے کہ دونوں directions میں bills دو گنا یا اس سے زیادہ غلط نکل سکتے ہیں۔

billable token categories پانچ ہیں:

bucketیہ کیا ہےtypical price، input کے مقابل
uncached inputprompt tokens جنہیں model کو fresh process کرنا پڑا
cache readstored prefix سے serve ہونے والے prompt tokens0.1×
cache writeاس call پر cache میں stored prompt tokens1.25× تا 2×
outputtokens جو model نے generate کر کے آپ کو بھیجے5× تا 6×
reasoningtokens جو model نے generate کیے اور آپ کو نہیں بھیجےoutput rate

ان پانچ میں سے تین دو سال پہلے separate lines کے طور پر موجود نہیں تھے، اور cache کی دو lines وہ ہیں جنہیں لوگ غلط سمجھتے ہیں، کیونکہ cache write کی cost ordinary input سے زیادہ ہے، کم نہیں۔ آپ کچھ store کرنے کے لیے premium دیتے ہیں تاکہ اسے واپس read کرتے وقت discount دے سکیں، اور یہ trade اچھا ہے یا نہیں اس کا انحصار مکمل طور پر اس پر ہے کہ آپ اسے کتنی بار read کرتے ہیں۔

reasoning bucket Chapter 12 والا ہے، اب اس پر price لگی ہے، اور اس میں ایک detail ہے جو صاف لفظوں میں کہنے کے قابل ہے: Google کی documentation کہتی ہے pricing ”model کو generate کرنے کے لیے درکار full thought tokens پر based ہے، اگرچہ API سے صرف summary output ہوتی ہے۔“4 آپ کو ایسے tokens کے لیے billed کیا جاتا ہے جو آپ تک کبھی transmit نہیں ہوتے۔ یہ واحد bucket ہے جس کے contents آپ count، inspect، یا verify نہیں کر سکتے۔

اب وہ حصہ جو اسے multiplication problem کے بجائے normalisation problem بناتا ہے۔ ہر provider ان buckets کو مختلف ناموں سے report کرتا ہے، اور — یہی trap ہے — ان میں سے دو ایک ہی word کو دو مختلف quantities کے لیے استعمال کرتے ہیں۔

ایک call لیں: cache سے read ہوئے 4,837 tokens، 110 fresh، 142 visible output tokens، 300 reasoning tokens۔

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: 4947 اور input_tokens: 110 کو دیکھیں۔ دونوں fields اسی prompt کے input token count ہیں۔ OpenAI والا cached tokens کو include کرتا ہے؛ Anthropic والا انہیں exclude کرتا ہے — اس کی documentation identity کو explicit state کرتی ہے، total_input_tokens = cache_read_input_tokens + cache_creation_input_tokens + input_tokens.5 Anthropic کا input_tokens مطلب ہے ”آپ کے last cache breakpoint کے بعد کے tokens“۔

اور output کو دیکھیں۔ OpenAI اور Anthropic دونوں 442 report کرتے ہیں، جس میں پہلے ہی 300 reasoning tokens شامل ہیں۔ Gemini 142 report کرتا ہے اور 300 کو اپنی separate field میں رکھتا ہے۔ Chapter 12 نے اسے same work count کرنے کے دو طریقوں کے درمیان incompatibility کے طور پر flag کیا تھا؛ یہاں دیکھیں اس کی cost کیا ہے۔

normaliser تیس lines کا ہے اور optional نہیں:

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
  };
};

اوپر کے تین payloads کو تین readers سے گزاریں اور تینوں ایک ہی Usage produce کرتے ہیں، اور اس لیے ایک ہی number: $0.006491۔ یہی agreement layer لکھنے کا پورا point ہے۔

اسے غلط کریں تو اسی call پر cost یہ ہے:

mistakebillederror
cached_tokens کو prompt_tokens کے additional سمجھنا$0.0161652.49× — آپ prompt کو دو بار charge کرتے ہیں
cache reads کو 0.1× کے بجائے free سمجھنا$0.0055240.85× — آپ 15 % خود absorb کرتے ہیں
candidatesTokenCount پڑھنا اور thoughtsTokenCount ignore کرنا$0.002891call کا 55 % غائب ہو جاتا ہے

تیسرا سب سے خطرناک ہے، کیونکہ یہ اچھی خبر کی direction میں silently fail ہوتا ہے۔ آپ کا dashboard reasoning model کو اس کی اصل cost کے نصف سے بھی کم دکھاتا ہے، اور کہیں بھی کوئی error نہیں اٹھتا۔

buckets normalise ہونے کے بعد cost function مختصر ہے۔ واحد non-obvious حصہ tier lookup ہے، جسے next section explain کرتا ہے:

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);
}

وہاں دو design decisions کے لیے argument بنتا ہے۔ fallbacks — cache prices کا input پر fallback، reasoning کا output پر — یہ encode کرتے ہیں کہ missing table کا کیا مطلب ہے: Gemini پر reasoning tokens output rate پر billed ہوتے ہیں، اس لیے absent reasoning price zero نہیں، output price ہے۔ اور contextSize تینوں input buckets کو sum کرتا ہے، صرف fresh کو نہیں، کیونکہ tier اس بات سے chosen ہوتا ہے کہ prompt کتنا long ہے، نہ کہ اس کے کتنے حصے پر آپ کو full price charge کیا گیا۔

Prompt caching، اور اسے write کرنے کی cost

اس حصے کا لنک: Prompt caching، اور اسے write کرنے کی cost

prompt cache آپ کے prompt کے prefix کے لیے model کی computed state store کرتا ہے، تاکہ بعد کی request same prefix کے ساتھ اسے recompute کرنا skip کرے۔ لفظ ”prefix“ سے چار properties نکلتی ہیں اور چاروں لوگوں کو surprise کرتی ہیں۔

cache rendered prompt کے beginning سے آگے match کرتا ہے، اور پہلے مختلف byte پر رک جاتا ہے۔ اس content کے لیے کوئی partial credit نہیں جو بعد میں کسی different order میں آئے۔ OpenAI اسے صاف کہتا ہے: ”cache reuse requires the entire rendered prefix to match.“6

اس سے نیچے، کچھ cache نہیں ہوتا اور کوئی error واپس نہیں آتا۔ OpenAI پر GPT-5.6 اور بعد کے models کے لیے minimum 1,024 tokens ہے اور older models کے لیے 2,048۔ Anthropic پر model کے حساب سے 512 سے 4,096 تک ہے — Claude Sonnet 4.5 کے لیے 1,024، Claude Haiku 4.5 کے لیے 4,096۔ اگر دونوں cache fields zero واپس آئیں، عموماً وجہ یہی ہوتی ہے۔

write کرنا read کرنے سے، اور cache نہ کرنے سے بھی، زیادہ costly ہے

اس حصے کا لنک: write کرنا read کرنے سے، اور cache نہ کرنے سے بھی، زیادہ costly ہے

OpenAI اور Anthropic پر short-lived cache کے لیے cache write uncached input rate کا 1.25× ہے، اور Anthropic کا one-hour cache 2× ہے۔ read 0.1× ہے۔ Google write کے لیے کچھ charge نہیں کرتا مگر storage rent لیتا ہے: Gemini 2.5 Pro پر $4.50 per million tokens per hour۔

یہ expire ہوتا ہے، اور ایک machine پر رہتا ہے

اس حصے کا لنک: یہ expire ہوتا ہے، اور ایک machine پر رہتا ہے

Anthropic کی default entry پانچ minutes زندہ رہتی ہے، ہر hit پر free میں refreshed۔ OpenAI کی latest write یا reuse کے بعد کم از کم تیس minutes۔ اور OpenAI note کرتا ہے کہ cached states individual machines پر live ہوتی ہیں، اس لیے request تبھی hit کرتی ہے جب وہ entry رکھنے والی machine کو route ہو — اسی پر prompt_cache_key اثر انداز ہوتا ہے، guarantee نہیں دیتا۔

break-even اتنا چھوٹا ہے کہ ذہن میں رکھا جا سکے، اور OpenAI کی documentation arithmetic کر دیتی ہے: ایک prefix کو ایک بار write کر کے ایک بار reuse کرنا اس کی ordinary input cost کا 1.35× خرچ کرتا ہے، جبکہ اسے دو بار uncached process کرنے پر 2×؛ دس requests میں، ایک write اور نو reads 2.15× خرچ کرتے ہیں بمقابلہ 10×۔ ایک reuse write کی قیمت نکال دیتا ہے۔ Anthropic بھی اسی جگہ پہنچتا ہے: five-minute cache کے لیے ایک read، one-hour cache کے لیے دو۔

اب وہی forty-turn conversation دوبارہ، caching on اور prefix stable کے ساتھ:

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

اڑسٹھ فیصد سستا، اور اس table میں تین numbers attention deserve کرتے ہیں۔

cache turn 6 تک engage نہیں کرتا۔ prompt اس وقت تک 1,024 tokens تک نہیں پہنچتا، اس لیے پہلے پانچ turns بالکل پہلے جیسے billed ہوتے ہیں — اور چھٹا بدتر billed ہوتا ہے، 1.25\u00d7 write premium پر، کیونکہ یہی وہ turn ہے جو cache بھرتا ہے۔ پہلی read turn 7 پر آتی ہے۔ table میں 2,887 uncached tokens arithmetic ہیں: پانچ turns کی worth، چھ نہیں۔ caching long prompts پر discount ہے، اور short conversation کو اس سے کچھ نہیں ملتا۔

write premium $0.002474 ہے، جو cached bill کا 2.8 % ہے۔ ہر turn اپنا new tail write کرتا ہے، چالیس بار، اور پورا write premium reads کی saving کے مقابل rounding error ہے۔ write charge کو precise سمجھنا اس لیے worth ہے کہ آپ اس کے بارے میں فکر کرنا بند کریں۔

112,617 میں سے صرف 2,887 tokens full input price پر charged ہوئے۔ working cache کی shape یہی ہے: تقریباً سب کچھ read ہے۔

prompt کا order فیصلہ کرتا ہے کہ یہ سب ہوگا بھی یا نہیں

اس حصے کا لنک: prompt کا order فیصلہ کرتا ہے کہ یہ سب ہوگا بھی یا نہیں

یہ وہ failure ہے جو real money خرچ کرتا ہے، اور یہ one-line bug ہے۔

prompt کے front کے قریب ایسی چیز رکھ دیں جو ہر call پر بدلتی ہے — timestamp، request id، user کا name، ”today is“ line، تازہ retrieved document — اور prefix byte one سے different ہو جاتا ہے۔ کچھ match نہیں کرتا۔ ہر call miss ہے۔ اور کیونکہ ہر call novel prefix پیش کرتی ہے، ہر call writes بھی کرتی ہے۔

وہی conversation، وہی forty turns، caching enabled، system prompt کے top پر per-call timestamp کے ساتھ:

totalversus
no caching at all$0.274386
caching, stable prefix$0.088250−67.8 %
caching, volatile prefix$0.329251+20.0 %

prompt caching enable کرنے سے conversation caching enable نہ کرنے کے مقابل بیس فیصد زیادہ expensive ہو گئی۔ آپ نے 109,730 tokens پر 1.25× write premium دیا اور read back zero کیا۔ کوئی error نہیں، کوئی warning نہیں، اور feature on ہے۔

لہٰذا rule، اور ایک line میں prompt caching کی پوری بات: stable content آگے، variable content پیچھے۔ system instructions، tool definitions اور reference material پہلے؛ timestamps، user identity اور current question آخر میں۔ Anthropic hierarchy کو explicit بناتا ہے — cache toolssystemmessages follow کرتا ہے، اور کسی بھی level پر change اس level اور اس کے بعد سب کچھ invalidate کر دیتا ہے، لہٰذا ایک single tool description edit کرنا entire cache invalidate کر دیتا ہے۔5

دو consequences جن پر لوگ ٹھوکر کھاتے ہیں۔ کون سے tools enabled ہیں یہ change کرنا tool definitions change کرتا ہے، اس لیے feature flag جو کچھ users کے لیے tool add کرتا ہے آپ کا cache دو حصوں میں split کر دیتا ہے۔ اور Anthropic پر web search یا citations toggle کرنا system prompt modify کرتا ہے، جو system اور message caches invalidate کر دیتا ہے، چاہے آپ اپنی text کی ایک line کو بھی نہ چھوئیں۔

quadratic bill کا obvious response یہ ہے کہ پوری history بھیجنا بند کریں: last dozen messages رکھیں اور باقی drop کر دیں۔ یہ bill reduce کرتا ہے، اور عموماً غلط move ہے، اور measurement بتاتی ہے کیوں۔

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 %

twelve-message window تک truncate کرنا سب کچھ uncached بھیجنے سے 57 % سستا ہے — یہی comparison ہر کوئی کرتا ہے، اور اسی لیے technique popular ہے۔ لیکن یہ working cache کے ساتھ سب کچھ بھیجنے سے 39 % زیادہ expensive ہے، اور truncation کے ساتھ caching on کرنا اسے بہتر کے بجائے تھوڑا worse بنا دیتا ہے۔

mechanism پھر prefix ہے۔ sliding window ہر turn oldest message drop کرتی ہے، اس لیے prompt اب وہاں سے شروع نہیں ہوتا جہاں پچھلی بار شروع ہوا تھا اور ہر turn نیا prefix پیش کرتا ہے۔ OpenAI کی guidance یہی کہتی ہے: ”summarisation, compaction, or context truncation can change the prefix and reset cache reuse.“6 turn 40 تک windowed prompt 813 tokens ہے، 1,024-token minimum سے کم، اس لیے وہ cache ہو ہی نہیں سکتا۔

اور money cost کا cheap half ہے۔ جو آپ نے drop کیا وہ user کی turn 2 پر دی گئی instruction ہے جس کی model کو turn 40 پر ضرورت تھی۔ truncation ایک ایسا bill trade کرتا ہے جو آپ دیکھ سکتے ہیں ایک ایسے failure کے لیے جو آپ نہیں دیکھ سکتے، اور اسے properly کرنا — compaction، window کے باہر held structured notes، demand پر history retrieve کرنا — Chapter 24 کا subject ہے۔

tier cross کرنا پوری request کو reprice کرتا ہے

اس حصے کا لنک: tier cross کرنا پوری request کو reprice کرتا ہے

Long contexts صرف اس لیے زیادہ expensive نہیں کہ وہ longer ہیں۔ threshold کے بعد وہ per token بھی زیادہ expensive ہیں، اور threshold پوری prompt پر retroactively apply ہوتا ہے۔

OpenAI کا model page gpt-5.6-terra کے لیے اسے ایک sentence میں state کرتا ہے: ”Prompts with >272K input tokens are priced at 2x input and 1.5x output for the full request.“7 excess کے لیے نہیں۔ پوری چیز کے لیے۔

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

ایک token، پچپن cents۔ اگر آپ کی service retrieved documents سے prompts بناتی ہے جن کے size پر آپ کا control نہیں، تو آپ کے cost model میں ایک ایسی boundary پر cliff ہے جو آپ کی team میں کسی نے لکھی ہی نہیں۔

Google کی pricing بھی 200,000-token threshold کے ساتھ اسی طرح کام کرتی ہے: Gemini 2.5 Pro 200K تک prompts کے لیے $1.25 per million input tokens ہے اور اس سے اوپر $2.50، output $10.00 سے $15.00 ہو جاتا ہے۔8 Anthropic دوسری direction گیا — 6 September 2026 تک اس کی documentation state کرتی ہے کہ Claude 4.6 اور بعد کے models standard pricing پر full one-million-token window include کرتے ہیں، اس لیے ”a 900k-token request is billed at the same per-token rate as a 9k-token request.“9 Earlier models surcharge رکھتے تھے۔

اسی لیے price ایک number نہیں۔ price prompt length سے keyed tiers کی table ہے، اسی کے لیے cost function میں Tier[] ہے، اور اسی لیے computeCost tier کو ہر bucket separately نہیں بلکہ whole prompt استعمال کر کے select کرتا ہے۔

Prefill، decode، اور output input سے چھ گنا مہنگا کیوں ہے

اس حصے کا لنک: Prefill، decode، اور output input سے چھ گنا مہنگا کیوں ہے

پانچ buckets Chapter 13 کے دو phases پر map ہوتے ہیں، اور جب mapping نظر آ جائے تو price ratios arbitrary نہیں لگتے۔

Input tokens prefill ہیں۔ پورا prompt ایک pass میں model سے گزرتا ہے، parallel process ہوتا ہے — large matrix multiplications، compute-bound۔ cost per token low ہے، اور یہی phase time to first token set کرتا ہے: 4,947-token prompt کو first word appear ہونے سے پہلے 4,947 tokens کا prefill کرنا ہے۔

Output tokens decode ہیں۔ وہ ایک وقت میں ایک produced ہوتے ہیں، ہر ایک full forward pass ہے جو entire KV cache read کرتا ہے، GPU computing کے بجائے mostly memory کا wait کر رہا ہوتا ہے۔ یہی phase tokens per second set کرتا ہے، ایک response کے اندر parallelise نہیں ہو سکتا، اور اسی لیے یہاں priced model پر output input سے تقریباً چھ گنا خرچ ہوتا ہے: $12.00 بمقابلہ $2.00 per million tokens۔

تین consequences direct follow کرتے ہیں۔ cache read prefill work کو replace کرتا ہے، اس لیے یہ latency اور money دونوں ایک ساتھ خریدتا ہے — وہی discount lower bill اور first token کے لیے shorter wait کے طور پر دکھتا ہے۔ Reasoning tokens وہ decode ہیں جو آپ دیکھتے نہیں، اسی لیے reasoning model کئی seconds تک کچھ stream نہیں کرتا اور پھر جلدی answer دیتا ہے: Chapter 12 نے interface consequence کے بارے میں warn کیا تھا، اور یہ invoice consequence ہے۔ اور stream abort کرنا generation کو نہیں روکتاChapter 14 نے cancellation بنایا اور price اس chapter پر چھوڑی، اور price full output count ہے، کیونکہ tokens produced اور billed ہوتے ہیں چاہے کوئی listen کر رہا ہو یا نہیں۔ وہی بات اس answer کی بھی ہے جسے کوئی keep نہیں کرتا: turn 40 answer کو پانچ بار regenerate کرنا screen پر بچے ہوئے one answer کے لیے $0.057990 خرچ کرتا ہے۔

Chapter 7 کا tokenizer Python تھا اور وہیں رہا۔ budgeting اس server میں ہوتی ہے جو request build کرتا ہے، اس لیے یہاں ہونی چاہیے، اور accuracy کے بالکل تین levels available ہیں۔

Level one: locally count کریں۔ js-tiktoken وہی BPE merge tables ship کرتا ہے جو Python tiktoken، لہٰذا OpenAI encodings کے لیے byte-for-byte identical count، بغیر network call:

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);
}

دو constants matter کرتے ہیں اور local counts drift کرنے کی جگہ بھی یہی ہے۔ آپ کی text وہ نہیں جو tokenize ہوتی ہے — Chapter 11 کا chat template پہلے ہر message کو role markers میں wrap کرتا ہے، اور وہ tokens ہیں جن کی قیمت آپ دیتے ہیں۔ OpenAI chat models کے لیے four per message اور reply priming کے لیے three conventional approximation ہے؛ اوپر کی conversation کے eighty-one messages میں یہ 324 tokens بنتے ہیں، اس کی length کا 6.4 %۔ یہاں counts Chapter 7 کے Python tiktoken کے against تمام eighty-one strings پر cross-check کیے گئے اور identical ہیں۔

Level two: provider سے پوچھیں۔ Anthropic /v1/messages/count_tokens expose کرتا ہے اور Google count_tokens، دونوں real call جیسی same request shape accept کرتے ہیں اور free میں input token count return کرتے ہیں۔ انہیں تب use کریں جب آپ locally count نہیں کر سکتے — اور Anthropic کے لیے آپ locally count نہیں کر سکتے، جس کا tokenizer published نہیں۔ Anthropic کی documentation اس بارے میں careful ہے کہ وہ کیا دے رہی ہے: count ”estimate“ ہے، اور یہ ”Anthropic کی system optimizations کے لیے automatically added tokens include کر سکتا ہے“، جن کے لیے ”آپ billed نہیں ہوتے“۔10

Level three: response میں usage پڑھیں۔ یہی truth ہے، اور یہ money spent ہونے کے بعد آتا ہے۔ یہی وجہ ہے کہ پہلے دو levels موجود ہیں — یہ decide کرنے کے لیے کہ request بھیجنی ہے یا نہیں، bill کرنے کے لیے نہیں۔

وہ چیزیں جن کی قیمت آپ دیتے ہیں مگر کوئی دکھاتا نہیں

اس حصے کا لنک: وہ چیزیں جن کی قیمت آپ دیتے ہیں مگر کوئی دکھاتا نہیں

چار line items جو line items کے طور پر appear نہیں ہوتیں۔

system prompt، ہر call پر paid۔ اوپر والا اپنی template overhead کے ساتھ 192 tokens ہے۔ چالیس calls میں یہ 7,680 tokens ہے — اس conversation کے entire bill کا 5.6 %، آٹھ lines کے لیے جو ایک بار لکھی گئیں۔ یہ best possible cache candidate بھی ہے، کیونکہ stable بھی ہے اور first بھی۔

Tool definitions۔ ہر tool کا name، description اور JSON schema ہر request پر باہر جاتا ہے، اور providers اوپر scaffolding add کرتے ہیں۔ Anthropic number publish کرتا ہے: tools enable کرنا ہی Claude Sonnet 4.5 پر tool_choice کو auto set کرنے کے ساتھ 496 tokens کا hidden system prompt add کرتا ہے، یا any یا named tool کے ساتھ 588۔9 یہ آپ کے own schemas سے پہلے ہے۔ Chapter 18 catalogue بناتا ہے؛ Chapter 24 measure کرتا ہے کہ یہ کیا کھاتا ہے۔

ہر generation، ان سمیت جنہیں آپ discard کرتے ہیں۔ پانچ regenerations پانچ گنا خرچ کرتے ہیں۔ chat ایک دکھاتا ہے۔

وہ thoughts جو آپ کو نہیں دکھائے جاتے۔ Billing full thought tokens پر based ہے اگرچہ صرف summary return ہوتی ہے، اور آپ کی کوئی accounting اس number کو audit نہیں کر سکتی۔

200K tokens ہونا انہیں use کرنا نہیں

اس حصے کا لنک: 200K tokens ہونا انہیں use کرنا نہیں

اختتام کے لیے ایک warning، کیونکہ یہ natural next thought ہے اور answer obvious نہیں۔

million-token window کا مطلب million usable tokens نہیں۔ Retrieval accuracy position کے ساتھ degrade ہوتی ہے: Liu et al. نے پایا کہ models long input کے beginning اور end پر information reliably locate کرتے ہیں اور middle میں بہت کم reliably۔11 bigger window زیادہ بھیجنے کی ability خریدتی ہے، read ہونے کی certainty نہیں۔

یہ phenomenon اس course میں ایک بار measured ہے — اسی 853-token prompt میں nine positions پر retrieval rate — اور یہ Chapter 24 میں belong کرتا ہے، جہاں یہ change کرتا ہے کہ agent کیا کرتا ہے۔ اسے یہاں cite کیا گیا ہے کیونکہ یہ change کرتا ہے کہ آپ کو کیا buy کرنا چاہیے: سب سے cheap token وہ ہے جو آپ نے بھیجا ہی نہیں۔

اب آپ call کرنے سے پہلے predict کر سکتے ہیں کہ اس کی cost کیا ہوگی، بعد میں پڑھ سکتے ہیں کہ اس نے کیا cost کیا، اور دونوں میں فرق بتا سکتے ہیں۔ یہ request کے بارے میں سب کچھ cover کرتا ہے سوائے اس part کے جسے آپ نے ابھی touch نہیں کیا: knobs۔

Chapter 17 sampling ہے — temperature، top-p، top-k، penalties، اور وہ determinism جو آپ کے پاس نہیں۔ یہ field کی سب سے widespread error dismantle کر کے شروع ہوتا ہے، کہ temperature creativity dial ہے۔ ایسا نہیں: temperature Chapter 4 کے logits کو softmax سے پہلے divide کرتا ہے، اور اسے raise کرنا model کو imaginative نہیں بناتا، یہ اُن tokens کی probability raise کرتا ہے جنہیں model نے خود worse score کیا۔ وہاں سے، کیوں greedy decoding sampling کے مقابل measurably worse text produce کرتی ہے، کیوں top-k اور top-p distribution کی opposite shapes پر fail ہوتے ہیں، اور chapter ختم کرنے والا experiment: temperature 0 پر بیس identical forward passes bit-for-bit identical واپس آتے ہیں جب model alone run کرتا ہے، اور اسی prompt کو کسی اور کی requests کے ساتھ batch میں ڈالنا اس کے 97 % logits move کر دیتا ہے۔

وہ سب match نہیں کرتے۔ وجہ Chapter 2 کے floating-point box سے شروع ہوتی ہے۔


اس chapter میں تمام prices، thresholds اور multipliers providers کے own pages سے 6 September 2026 کو read کیے گئے اور اسی date کے ساتھ stated ہیں کیونکہ یہ change ہوں گے۔ method numbers سے زیادہ important ہے: buckets، prefix rule اور tier arithmetic دو سال سے stable ہیں جبکہ ان کے اندر ہر figure move ہو چکی ہے۔

Stanford CS336 lecture 2، Resource accounting، اس material کا closest academic treatment ہے اور right next read: یہ training side پر وہی arithmetic کرتا ہے جو یہ chapter inference side پر کرتا ہے۔ یہاں token counts js-tiktoken 1.0.21 کے ساتھ o200k_base اور cl100k_base encodings use کر کے produced کیے گئے، 5,090 tokens کی forty-turn conversation پر؛ per-message template overhead conventional four-plus-three approximation ہے اور جہاں include ہے وہاں stated ہے۔ cache، tier اور truncation figures documented pricing rules ہیں جو measured token counts پر apply کیے گئے، live API responses کی observations نہیں — اس chapter کو produce کرنے کے لیے کوئی paid call نہیں کی گئی، جو honest reason بھی ہے کہ latency claims qualitative ہیں اور cost claims نہیں۔

  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). ceiling asymptotic cost change کیے بغیر کیوں move ہوئی۔

  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، Thinking، ai.google.dev/gemini-api/docs/thinking، اور Token counting، ai.google.dev/gemini-api/docs/tokens، دونوں accessed 2026-09-06۔ ”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_tokens، total_output_tokens، total_thought_tokens، total_cached_tokens، total_tool_use_tokens اور total_tokens report کرتا ہے — six buckets، thoughts اور tool use output count کے outside۔ same quantity کے لیے earlier field name، جو generateContent surface اب بھی return کرتا ہے، thoughtsTokenCount ہے، documented on a third page، ai.google.dev/gemini-api/docs/generate-content/thinking۔

  5. Anthropic، Prompt caching، docs.anthropic.com/en/docs/build-with-claude/prompt-caching، accessed 2026-09-06۔ toolssystemmessages invalidation hierarchy اور اس کی table؛ per-model minimum cacheable lengths؛ identity total_input_tokens = cache_read_input_tokens + cache_creation_input_tokens + input_tokens؛ اور ہر hit پر no charge کے ساتھ refreshed five-minute default lifetime کا source۔ 2

  6. OpenAI، Prompt caching، platform.openai.com/docs/guides/prompt-caching، accessed 2026-09-06۔ Source of: entire-rendered-prefix rule؛ minimum cacheable prefix (GPT-5.6 اور بعد پر 1,024 visible input tokens، earlier پر 2,048)؛ 1.25× write اور 0.1× read multipliers، اور GPT-5.5 اور earlier پر کسی write charge کی absence؛ 30-minute lifetime؛ four-writes-per-request اور fifty-breakpoint limits؛ machine-affinity note اور prompt_cache_key؛ 1.35×، 2.15× اور 10× break-even worked examples؛ اور یہ statement کہ summarisation، compaction یا truncation cache reuse reset کر دیتا ہے۔ 2

  7. OpenAI، Pricing (platform.openai.com/docs/pricing) اور gpt-5.6-terra کا model page، دونوں accessed 2026-09-06۔ gpt-5.6-terra، standard service tier، per million tokens: 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 with maximum 922,000 input tokens۔ یہی table gpt-6-astra کو $10.00/$1.00/$12.50/$50.00 پر اور gpt-5.6-luna کو $0.20/$0.02/$0.25/$1.20 پر list کرتی ہے۔ اس chapter میں ہر worked cost gpt-5.6-terra standard short-context rates use کرتی ہے۔

  8. Google، Gemini Developer API pricing، ai.google.dev/gemini-api/docs/pricing، accessed 2026-09-06۔ Gemini 2.5 Pro، per million tokens: 200K تک prompts کے لیے input $1.25 اور اس سے اوپر $2.50؛ output $10.00 اور $15.00، دونوں cases میں ”including thinking tokens“ labelled؛ context caching $0.125 اور $0.25، plus storage charge $4.50 per million tokens per hour۔ Gemini 3.1 Pro Preview same 200K threshold use کرتا ہے input $2.00/$4.00 اور output $12.00/$18.00 پر۔

  9. Anthropic، Pricing، docs.anthropic.com/en/docs/about-claude/pricing، accessed 2026-09-06۔ Per million tokens، 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: five-minute write کے لیے 1.25×، one-hour write کے لیے 2×، read کے لیے 0.1×۔ long-context statement کا source بھی یہی ہے (”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_choice of auto یا none کے ساتھ 496 tokens، any یا named tool کے ساتھ 588)، اور note کہ Claude 4.7 اور بعد والے newer tokenizer use کرتے ہیں جو ”approximately 30 % more tokens for the same text“ produce کرتا ہے۔ 2 3

  10. Anthropic، Token counting، docs.anthropic.com/en/docs/build-with-claude/token-counting، accessed 2026-09-06۔ /v1/messages/count_tokens endpoint message جیسے same inputs لیتا ہے اور input token count return کرتا ہے؛ documentation state کرتی ہے کہ count estimate ہے، یہ Anthropic کے system optimisations کے لیے added tokens include کر سکتا ہے، اور وہ billed نہیں ہوتے۔

  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). یہاں cited، Chapter 24 میں measured۔


تیار کردہ

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.
jev14 منٹ مطالعہ

Jev AI ماڈل فیصلوں کے لیے بنایا گیا ہے، نثر کے لیے نہیں

TypeSafe AI کا Jev اس لیے توجہ کھینچ رہا ہے کہ یہ software intelligence کو احتمال کے مسئلے کے طور پر دیکھتا ہے: درست branch چنیں، confidence منسلک کریں، اور جب code کو فیصلہ چاہیے ہو تو text لکھوانے کے لیے LLM کو ادائیگی سے بچیں۔

Abstract agent runtime sorting documents, memory blocks and pointer nodes inside a bounded context frame.
context-engineering14 منٹ مطالعہ

طویل مدتی AI ایجنٹس کے لیے کانٹیکسٹ انجینئرنگ

طویل عرصے تک چلنے والے ایجنٹس صرف اس لیے ناکام نہیں ہوتے کہ ونڈو چھوٹی ہے۔ وہ اس وقت ناکام ہوتے ہیں جب فائلیں، ٹول آؤٹ پٹس اور پرانی ہسٹری اس کام کو باہر دھکیل دیتی ہیں جسے ایجنٹ نے مکمل کرنا تھا۔

ماڈل چننے کا کام LIA کے سپرد کرنے کے لیے تیار ہیں؟

ہر AI ماڈل ایک ہی جگہ — آج ہی مفت شروع کریں۔