OpenAI API は、特定の要求に対して部分的な結果を許可するために、応答をクライアントにストリーミングする機能を提供します。これを実現するために、サーバー送信イベントの標準に従います。公式の Node ライブラリと Python ライブラリには、これらのイベントの解析をより簡単にするためのヘルパーが含まれています。Python では、ストリーミングリクエストは次のようになります。from openai import OpenAI
client = OpenAI()
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Say this is a test"}],
stream=True,
)
for chunk in stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")
Node / Typescriptでは、ストリーミングリクエストは次のようになります。import OpenAI from "openai";
const openai = new OpenAI();
async function main() {
const stream = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "user", content: "Say this is a test" }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || "");
}
}
main();
サーバー送信イベントの解析#
サーバーから送信されたイベントの解析は簡単ではなく、注意して行う必要があります。改行で分割するなどの単純な戦略では、解析エラーが発生する可能性があります。可能な場合は、既存のクライアントライブラリを使用することをお勧めします。 Modified at 2025-01-02 08:53:03