⚡ नया — Kimi K3 अब लाइव: अपनी Moonshot key जोड़ें →
दस्तावेज़

टोकन स्ट्रीम करें और सटीक ₹ लागत जानें

← कुकबुक

server-sent events पढ़ें और अंतिम usage chunk पकड़ें ताकि हर request की लागत निकले।

SSE + usage chunkएडवांस्डमध्यम8 min

streaming उपयोगकर्ताओं को tokens जैसे-जैसे बनते हैं देती है। ज़्यादातर gateways में अड़चन यह है कि आप token count खो देते हैं। BharatRouter समर्थन करने वाले providers पर stream_options.include_usage inject करता है, इसलिए [DONE] से पहले का अंतिम chunk हमेशा एक usage block ले जाता है — आप stream और लागत दोनों पाते हैं।

आप इस्तेमाल करेंगे: stream: true + अंतिम usage chunk. संदर्भ: chat completions

करें

from openai import OpenAI

client = OpenAI(base_url="https://api.bharatrouter.com/v1", api_key="br-...")

stream = client.chat.completions.create(
    model="gemma-4-e4b-it",
    messages=[{"role": "user", "content": "Explain UPI in two lines"}],
    stream=True,
    stream_options={"include_usage": True},
)

usage = None
for chunk in stream:
    if chunk.usage:                       # final chunk carries usage
        usage = chunk.usage
    elif chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

print(f"\n\n[tokens: {usage.total_tokens}]")

यह कैसे काम करता है

response text/event-stream है। पहले content deltas आते हैं; [DONE] से पहले का बिल्कुल अंतिम data chunk खाली choices और भरा हुआ usage object रखता है। जिस route ने serve किया वह अब भी x-br-provider response header में है।

खर्च घटाने और मापने — दोनों एक ही कॉल में — के लिए लागत प्लेबुक से जोड़ें।

और रेसिपी कुकबुक में, या पूराAPI reference देखें।