ガイド
ストリーミング
stream: trueを設定すると、返答はOpenAIのserver-sent eventsとして1語ずつ届きます。usageを要求すると、最後のチャンクに呼び出しの料金が示されます。
2026年10月26日 確認
返答をストリーミングする
import os
from openai import OpenAI
client = OpenAI(
base_url="https://nokeep.ai/v1",
api_key=os.environ["NOKEEP_API_KEY"],
)
stream = client.chat.completions.create(
model="deepseek-v4.1-flash-uncensored",
messages=[{"role": "user", "content": "Tell me a story in three lines."}],
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
if chunk.choices:
print(chunk.choices[0].delta.content or "", end="", flush=True)
if chunk.usage:
print("\ncredits:", chunk.usage.model_extra.get("nokeep_credits"))届くもの
data: {"choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}
data: {"choices":[{"index":0,"delta":{"content":"The"}}]}
data: {"choices":[{"index":0,"delta":{"content":" lighthouse"}}]}
…
data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: {"choices":[],"usage":{"prompt_tokens":18,"completion_tokens":61,"nokeep_credits":0}}
data: [DONE]- 言葉は
delta.contentに届きます。思考をオンにしていると、思考が先にdelta.reasoning_contentで届きます。 - ツール呼び出しは
delta.tool_callsに届きます。引数はOpenAIと同じく小分けで届きます。 stream_options.include_usageを付けると、choicesが空の最後のチャンクにusageが入ります。そこにはnokeep_credits、つまり呼び出しの料金が含まれます。- ストリームは
data: [DONE]で終わります。
返答を途中で止める
接続を閉じると、モデルは書くのをやめます。支払うのは止めるまでに送られた分だけで、その後の分はかかりません。SDKではループを抜けてストリームを閉じます。アプリでは停止ボタンを押してください。
for chunk in stream:
text = chunk.choices[0].delta.content if chunk.choices else ""
if text and "THE END" in text:
stream.close() # the model stops here, and so does the bill
breakモデルが先に止まったとき
モデルがストリームを完了前に終わらせた場合、[DONE]の直前のイベントは、OpenAIの形式のエラーになります。コードはstream_cutです。書かれた分は課金されますが、それ以上はかかりません。再試行するか、届いた分から続けてください。
data: {"error":{"type":"api_error","code":"stream_cut","message":"The model stopped before it finished. What it wrote is billed, nothing more."}}
data: [DONE]よくある質問
ストリーミングすると高くなりますか?
いいえ。ストリーミングの返答は、まとめて受け取る場合と同じトークン分の料金です。
ストリームにx-nokeep-creditsヘッダーがないのはなぜですか?
ヘッダーは最初の語より前に送られ、そのときは料金がまだ分からないからです。usageを要求し、最後のチャンクのnokeep_creditsを読んでください。