Wenn du eine Anfrage an die OpenAI API sendest, generieren wir standardmäßig die gesamte Modellausgabe, bevor wir sie in einer einzigen HTTP-Antwort zurückgeben. Bei langen Ausgaben kann das Warten auf die Antwort einige Zeit dauern. Mit Streaming kannst du den Anfang der Modellausgabe bereits anzeigen oder verarbeiten, während das Modell den Rest der Antwort generiert.
Dieser Leitfaden behandelt HTTP-Streaming (stream=true) über Server-Sent Events (SSE). Informationen zur dauerhaften WebSocket-Verbindung mit schrittweisen Eingaben über previous_response_id findest du unter WebSocket-Modus der Responses API.
Um Antworten zu streamen, setze stream=True in deiner Anfrage an den Responses-Endpunkt:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17import { OpenAI } from "openai";
const client = new OpenAI();
const stream = await client.responses.create({
model: "gpt-6-astra",
input: [
{
role: "user",
content: "Say 'double bubble bath' ten times fast.",
},
],
stream: true,
});
for await (const event of stream) {
console.log(event);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17from openai import OpenAI
client = OpenAI()
stream = client.responses.create(
model="gpt-6-astra",
input=[
{
"role": "user",
"content": "Say 'double bubble bath' ten times fast.",
},
],
stream=True,
)
for event in stream:
print(event)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/responses"
)
func main() {
client := openai.NewClient()
stream := client.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{
Model: "gpt-6-astra",
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Say 'double bubble bath' ten times fast.")},
})
for stream.Next() {
fmt.Println(stream.Current().Type)
}
if err := stream.Err(); err != nil {
panic(err)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.StreamResponse;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseStreamEvent;
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6-astra")
.input("Say 'double bubble bath' ten times fast.")
.build();
try (StreamResponse<ResponseStreamEvent> stream = client.responses().createStreaming(params)) {
stream.stream().forEach(System.out::println);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18using OpenAI.Responses;
#pragma warning disable OPENAI001
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
ResponsesClient client = new(key);
var responses = client.CreateResponseStreamingAsync(
"gpt-6-astra",
"Say 'double bubble bath' ten times fast."
);
await foreach (StreamingResponseUpdate response in responses)
{
if (response is StreamingResponseOutputTextDeltaUpdate delta)
{
Console.Write(delta.Delta);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17require "openai"
openai = OpenAI::Client.new
stream = openai.responses.stream(
model: "gpt-6-astra",
input: [
{
role: "user",
content: "Say 'double bubble bath' ten times fast."
}
]
)
stream.each do |event|
puts(event)
end
Die Responses API verwendet semantische Ereignisse für das Streaming. Jedes Ereignis ist anhand eines vordefinierten Schemas typisiert. So kannst du gezielt auf die Ereignisse reagieren, die für dich relevant sind.
Eine vollständige Liste der Ereignistypen findest du in der API-Referenz für Streaming. Hier sind einige Beispiele:
1
2
3
4
5
6
7
8
9for await (const event of stream) {
if (event.type === "response.output_text.delta") {
process.stdout.write(event.delta);
} else if (event.type === "response.completed") {
console.log("\nResponse completed.");
} else if (event.type === "error") {
console.error(event.message);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26StreamingEvent = (
ResponseCreatedEvent
| ResponseInProgressEvent
| ResponseFailedEvent
| ResponseCompletedEvent
| ResponseOutputItemAdded
| ResponseOutputItemDone
| ResponseContentPartAdded
| ResponseContentPartDone
| ResponseOutputTextDelta
| ResponseOutputTextAnnotationAdded
| ResponseTextDone
| ResponseRefusalDelta
| ResponseRefusalDone
| ResponseFunctionCallArgumentsDelta
| ResponseFunctionCallArgumentsDone
| ResponseFileSearchCallInProgress
| ResponseFileSearchCallSearching
| ResponseFileSearchCallCompleted
| ResponseCodeInterpreterInProgress
| ResponseCodeInterpreterCallCodeDelta
| ResponseCodeInterpreterCallCodeDone
| ResponseCodeInterpreterCallInterpreting
| ResponseCodeInterpreterCallCompleted
| Error
)
1type StreamingEvent = responses.ResponseStreamEventUnion
1
2
3
4
5
6
7
8
9
10
11
12import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.StreamResponse;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseStreamEvent;
ResponseCreateParams params =
ResponseCreateParams.builder().model("gpt-5.5").input("Say hello.").build();
try (StreamResponse<ResponseStreamEvent> stream = client.responses().createStreaming(params)) {
stream.stream().forEach(System.out::println);
}
1
2
3
4
5require "openai"
client = OpenAI::Client.new
stream = client.responses.stream(model: "gpt-5.5", input: "Say hello.")
stream.each { |event| puts(event) }
Das Streaming von Chat Completions ist recht einfach. Wir empfehlen jedoch, die Responses API für Streaming zu verwenden, da wir sie gezielt dafür entwickelt haben. Die Responses API verwendet semantische Ereignisse für das Streaming und ist typsicher.
Um Completions zu streamen, setze beim Aufruf der Chat Completions-Endpunkte oder der älteren Completions-Endpunkte stream=True. Dadurch erhältst du ein Objekt, das die Antwort als Server-Sent Events streamt, die ausschließlich Daten enthalten.
Die Antwort wird über einen Ereignisstream schrittweise in einzelnen Teilen zurückgegeben. Du kannst mit einer for-Schleife über den Ereignisstream iterieren, zum Beispiel so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19import OpenAI from "openai";
const openai = new OpenAI();
const stream = await openai.chat.completions.create({
model: "gpt-6-astra",
messages: [
{
role: "user",
content: "Say 'double bubble bath' ten times fast.",
},
],
stream: true,
});
for await (const chunk of stream) {
console.log(chunk);
console.log(chunk.choices[0].delta);
console.log("****************");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19from openai import OpenAI
client = OpenAI()
stream = client.chat.completions.create(
model="gpt-6-astra",
messages=[
{
"role": "user",
"content": "Say 'double bubble bath' ten times fast.",
},
],
stream=True,
)
for chunk in stream:
print(chunk)
print(chunk.choices[0].delta)
print("****************")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
stream := client.Chat.Completions.NewStreaming(context.Background(), openai.ChatCompletionNewParams{
Model: "gpt-6-astra",
Messages: []openai.ChatCompletionMessageParamUnion{
openai.UserMessage("Say 'double bubble bath' ten times fast."),
},
})
for stream.Next() {
fmt.Println(stream.Current())
}
if err := stream.Err(); err != nil {
panic(err)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.StreamResponse;
import com.openai.models.chat.completions.ChatCompletionChunk;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
ChatCompletionCreateParams params =
ChatCompletionCreateParams.builder()
.model("gpt-6-astra")
.addUserMessage("Say hello.")
.build();
try (StreamResponse<ChatCompletionChunk> stream =
client.chat().completions().createStreaming(params)) {
stream.stream().forEach(System.out::println);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15using System.ClientModel.Primitives;
using OpenAI.Chat;
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-6-astra";
ChatClient client = new(model, key);
await foreach (
StreamingChatCompletionUpdate update in client.CompleteChatStreamingAsync(
new UserChatMessage("Say double bubble bath ten times fast.")
)
)
{
Console.WriteLine(ModelReaderWriter.Write(update));
}
1
2
3
4
5
6
7
8
9
10
11
12require "openai"
client = OpenAI::Client.new
stream = client.chat.completions.stream(
model: "gpt-6-astra", messages: [
{
role: :user,
content: "Say hello."
}
]
)
stream.each { |event| puts(event) }
Wenn du unser SDK verwendest, ist jedes Ereignis eine typisierte Instanz. Du kannst einzelne Ereignisse auch anhand ihrer Eigenschaft type identifizieren.
Einige zentrale Lebenszyklusereignisse werden nur einmal ausgegeben, andere dagegen mehrfach, während die Antwort generiert wird. Beim Streaming von Text reagierst du typischerweise auf folgende Ereignisse:
- `response.created`
- `response.output_text.delta`
- `response.completed`
- `error`
Eine vollständige Liste der Ereignisse, auf die du reagieren kannst, findest du in der API-Referenz für Streaming.
Wenn du eine Chat Completion streamst, enthalten die Antworten ein Feld delta statt eines Felds message. Das Feld delta kann ein Rollen-Token oder ein Inhalts-Token enthalten oder leer sein.
{ role: 'assistant', content: '', refusal: null }
****************
{ content: 'Why' }
****************
{ content: " don't" }
****************
{ content: ' scientists' }
****************
{ content: ' trust' }
****************
{ content: ' atoms' }
****************
{ content: '?\n\n' }
****************
{ content: 'Because' }
****************
{ content: ' they' }
****************
{ content: ' make' }
****************
{ content: ' up' }
****************
{ content: ' everything' }
****************
{ content: '!' }
****************
{}
****************
Um nur die Textantwort deiner Chat Completion zu streamen, könnte dein Code so aussehen:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17import OpenAI from "openai";
const client = new OpenAI();
const stream = await client.chat.completions.create({
model: "gpt-6-astra",
messages: [
{
role: "user",
content: "Say 'double bubble bath' ten times fast.",
},
],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content || "");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18from openai import OpenAI
client = OpenAI()
stream = client.chat.completions.create(
model="gpt-6-astra",
messages=[
{
"role": "user",
"content": "Say 'double bubble bath' ten times fast.",
},
],
stream=True,
)
for chunk in stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
)
func main() {
client := openai.NewClient()
stream := client.Chat.Completions.NewStreaming(context.Background(), openai.ChatCompletionNewParams{
Model: "gpt-6-astra",
Messages: []openai.ChatCompletionMessageParamUnion{
openai.UserMessage("Say 'double bubble bath' ten times fast."),
},
})
for stream.Next() {
if len(stream.Current().Choices) > 0 {
fmt.Print(stream.Current().Choices[0].Delta.Content)
}
}
if err := stream.Err(); err != nil {
panic(err)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.StreamResponse;
import com.openai.models.chat.completions.ChatCompletionChunk;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
ChatCompletionCreateParams params =
ChatCompletionCreateParams.builder()
.model("gpt-6-astra")
.addUserMessage("Say 'double bubble bath' ten times fast.")
.build();
try (StreamResponse<ChatCompletionChunk> stream =
client.chat().completions().createStreaming(params)) {
stream.stream()
.flatMap(chunk -> chunk.choices().stream())
.flatMap(choice -> choice.delta().content().stream())
.forEach(System.out::print);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17using OpenAI.Chat;
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
string model = "gpt-6-astra";
ChatClient client = new(model, key);
await foreach (
StreamingChatCompletionUpdate update in client.CompleteChatStreamingAsync(
new UserChatMessage("Say double bubble bath ten times fast.")
)
)
{
foreach (ChatMessageContentPart part in update.ContentUpdate)
{
Console.Write(part.Text);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13require "openai"
client = OpenAI::Client.new
stream = client.chat.completions.stream(
model: "gpt-6-astra",
messages: [
{
role: :user,
content: "Say 'double bubble bath' ten times fast."
}
]
)
stream.text.each { |text| print(text) }
Für fortgeschrittene Anwendungsfälle wie das Streaming von Tool-Aufrufen findest du weitere Informationen in diesen speziellen Leitfäden:
Beachte, dass das Streaming der Modellausgabe in einer Anwendung im Produktivbetrieb die Moderation der generierten Inhalte erschwert, da sich unvollständige Antworten möglicherweise schwerer beurteilen lassen. Dies kann Auswirkungen auf die zulässige Nutzung haben.
Wenn du Moderationswerte zusammen mit einer Generierungsanfrage anforderst, erhältst du die Werte erst, nachdem die vollständige generierte Ausgabe verfügbar ist. In den Deltas der Teilausgaben sind sie nicht enthalten.