De forma predeterminada, cuando haces una solicitud a la API de OpenAI, generamos toda la salida del modelo antes de devolverla en una sola respuesta HTTP. Cuando se generan salidas extensas, la respuesta puede tardar. Las respuestas en streaming te permiten empezar a imprimir o procesar el inicio de la salida del modelo mientras este continúa generando la respuesta completa.
Esta guía se centra en el streaming HTTP (stream=true) mediante eventos enviados por el servidor (SSE). Para usar un transporte WebSocket persistente con entradas incrementales mediante previous_response_id, consulta el modo WebSocket de la API Responses.
Para empezar a recibir respuestas en streaming, establece stream=True en tu solicitud al punto de acceso Responses:
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
La API Responses usa eventos semánticos para el streaming. Cada evento tiene un tipo definido por un esquema preestablecido, por lo que puedes escuchar los eventos que te interesen.
Para ver la lista completa de tipos de eventos, consulta la referencia de la API para streaming. Estos son algunos ejemplos:
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) }
Usar Chat Completions en streaming es bastante sencillo. Sin embargo, recomendamos usar la API Responses para streaming, ya que la diseñamos pensando en este uso. La API Responses usa eventos semánticos para el streaming y ofrece seguridad de tipos.
Para recibir respuestas en streaming, establece stream=True al llamar a los puntos de acceso Chat Completions o Completions heredado. Esto devuelve un objeto que transmite la respuesta en streaming como eventos enviados por el servidor que solo contienen datos.
La respuesta se devuelve de forma incremental en fragmentos mediante un flujo de eventos. Puedes recorrer el flujo de eventos con un bucle for, de esta manera:
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) }
Si usas nuestro SDK, cada evento es una instancia tipada. También puedes identificar eventos individuales mediante la propiedad type del evento.
Algunos eventos clave del ciclo de vida se emiten una sola vez, mientras que otros se emiten varias veces a medida que se genera la respuesta. Estos son algunos eventos habituales que puedes escuchar al recibir texto en streaming:
- `response.created`
- `response.output_text.delta`
- `response.completed`
- `error`
Para ver la lista completa de eventos que puedes escuchar, consulta la referencia de la API para streaming.
Cuando recibes una respuesta de chat en streaming, las respuestas tienen un campo delta en lugar de un campo message. El campo delta puede contener un token de rol, un token de contenido o nada.
{ 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: '!' }
****************
{}
****************
Para recibir en streaming solo el texto de la respuesta de chat, tu código sería así:
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) }
Para casos de uso más avanzados, como las llamadas a herramientas en streaming, consulta las siguientes guías específicas:
Ten en cuenta que transmitir la salida del modelo en streaming en una aplicación en producción dificulta la moderación del contenido de las respuestas, ya que las respuestas parciales pueden ser más difíciles de evaluar. Esto puede tener implicaciones para el uso aprobado.
Si solicitas puntuaciones de moderación junto con una solicitud de generación, las puntuaciones llegan después de que esté disponible toda la salida generada. No se incluyen con los fragmentos incrementales de la salida parcial.