Por padrão, quando você faz uma requisição à API da OpenAI, geramos toda a saída do modelo antes de enviá-la em uma única resposta HTTP. Se a saída for longa, a resposta pode demorar. Com o streaming, você pode começar a exibir ou processar os primeiros trechos da saída enquanto o modelo gera o restante da resposta.
Este guia aborda o streaming via HTTP (stream=true) com eventos enviados pelo servidor (SSE). Para usar uma conexão WebSocket persistente com entradas incrementais por meio de previous_response_id, consulte o modo WebSocket da API Responses .
Para começar a receber respostas em streaming, defina stream=True na requisição ao endpoint Responses.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 import { 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
17 from 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
23 package 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
15 import 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
18 using 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
17 require "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 A API Responses usa eventos semânticos no streaming. Cada evento tem um tipo com um schema predefinido, o que permite escutar apenas os eventos de interesse.
Para ver a lista completa de tipos de evento, consulte a referência da API sobre streaming . Veja alguns exemplos a seguir.
1
2
3
4
5
6
7
8
9 for 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 ( " \n Response 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
26 StreamingEvent = (
ResponseCreatedEvent
| ResponseInProgressEvent
| ResponseFailedEvent
| ResponseCompletedEvent
| ResponseOutputItemAdded
| ResponseOutputItemDone
| ResponseContentPartAdded
| ResponseContentPartDone
| ResponseOutputTextDelta
| ResponseOutputTextAnnotationAdded
| ResponseTextDone
| ResponseRefusalDelta
| ResponseRefusalDone
| ResponseFunctionCallArgumentsDelta
| ResponseFunctionCallArgumentsDone
| ResponseFileSearchCallInProgress
| ResponseFileSearchCallSearching
| ResponseFileSearchCallCompleted
| ResponseCodeInterpreterInProgress
| ResponseCodeInterpreterCallCodeDelta
| ResponseCodeInterpreterCallCodeDone
| ResponseCodeInterpreterCallInterpreting
| ResponseCodeInterpreterCallCompleted
| Error
) 1 type StreamingEvent = responses.ResponseStreamEventUnion 1
2
3
4
5
6
7
8
9
10
11
12 import 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
5 require "openai"
client = OpenAI::Client.new
stream = client.responses.stream(model: "gpt-5.5", input: "Say hello.")
stream.each { |event| puts(event) }
É relativamente simples usar streaming com a API chat completions. No entanto, recomendamos usar a API Responses para streaming , pois a projetamos para esse uso. A API Responses usa eventos semânticos no streaming e oferece segurança de tipos.
Receber uma resposta de chat em streaming Para receber respostas em streaming, defina stream=True ao chamar o endpoint Chat Completions ou o endpoint legado Completions. A chamada retorna um objeto que fornece a resposta em streaming por meio de eventos enviados pelo servidor que contêm apenas dados.
A resposta chega em partes, de forma incremental, em um fluxo de eventos. Você pode percorrer esse fluxo com um laço for, como no exemplo a seguir.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 import 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
19 from 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
24 package 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
16 import 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
15 using 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
12 require "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) }
Ler as respostas
Se você usa nosso SDK, cada evento é uma instância tipada. Também é possível identificar cada evento pela propriedade type.
A API emite alguns eventos importantes do ciclo de vida apenas uma vez. Outros são emitidos várias vezes durante a geração da resposta. Ao receber texto em streaming, é comum escutar os seguintes eventos.
- `response.created`
- `response.output_text.delta`
- `response.completed`
- `error` Para ver a lista completa de eventos que você pode escutar, consulte a referência da API sobre streaming .
Quando você recebe uma resposta de chat em streaming, cada parte tem um campo delta em vez de um campo message. O campo delta pode conter um token que indica o papel do participante, conter um token de conteúdo ou estar vazio.
{ 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 receber apenas o texto da resposta de chat em streaming, use um código como o do exemplo a seguir.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 import 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
18 from 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
26 package 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
19 import 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
17 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.")
)
)
{
foreach (ChatMessageContentPart part in update.ContentUpdate)
{
Console.Write(part.Text);
}
} 1
2
3
4
5
6
7
8
9
10
11
12
13 require "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 mais avançados, como o streaming de chamadas de ferramentas, consulte os guias a seguir.
Transmitir a saída do modelo em streaming em um aplicativo em produção dificulta a moderação do conteúdo das respostas, pois pode ser mais difícil avaliar uma resposta parcial. Isso pode afetar a avaliação de conformidade com os usos permitidos.
Se você solicitar pontuações de moderação na requisição de geração , elas só chegam depois que toda a saída gerada está disponível. Os eventos que trazem trechos da saída durante a geração não incluem essas pontuações.