Use the access token saved during Sign in to populate a model picker and complete the first inference request.
Before showing a model picker, request the selected ChatGPT account’s model catalog with the same access token you will use for inference:
curl --fail-with-body --silent --show-error \
https://api.openai.com/v1/models \
-H "Authorization: Bearer $ACCESS_TOKEN" \
| jq '[.models[] | select(.visibility == "list") | {slug, display_name}]'
The model-list response contains a models array. This example keeps models intended for display (visibility: "list") and preserves the server’s ordering. Show display_name in your UI and pass the selected slug as model in the next step. Refresh these choices when the user switches ChatGPT accounts. If you use Codex app-server, its model/list RPC may use a bundled or cached catalog. Use the request above when your UI needs current account-specific model choices.
To perform inference on behalf of the user, send the OAuth access token as Authorization: Bearer <ACCESS_TOKEN> to POST https://api.openai.com/v1/responses.
Supported endpoint: Use the public Responses API endpoint above for this ChatGPT plan usage flow; do not point it at ChatGPT’s backend-api endpoints. Use a model available to the signed-in account.
Set store to false and stream to true on each HTTP inference request in this flow. Consume the response as a stream of events.
Read the saved access_token for the selected ChatGPT account into the process environment as ACCESS_TOKEN before running these examples.
curl --no-buffer https://api.openai.com/v1/responses \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-6.1-sol",
"input": [
{
"role": "user",
"content": "Say exactly: Hello, world!"
}
],
"store": false,
"stream": true
}'
Set ACCESS_TOKEN to the OAuth access token. The SDK sends it as the bearer credential.
For TypeScript, install the SDK with npm install openai. Save the complete example below as token-sharing.ts in the directory where you installed the SDK, then run node --experimental-strip-types token-sharing.ts.
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
27import OpenAI from "openai";
const accessToken = process.env.ACCESS_TOKEN;
if (!accessToken) throw new Error("Set ACCESS_TOKEN to the user's OAuth token");
const client = new OpenAI({
apiKey: accessToken,
baseURL: "https://api.openai.com/v1",
maxRetries: 0,
});
const stream = await client.responses.create({
model: "gpt-6.2-sol",
input: [{ role: "user", content: "Say exactly: Hello, world!" }],
store: false,
stream: true,
});
let completed = false;
for await (const event of stream) {
if (event.type === "response.output_text.delta")
process.stdout.write(event.delta);
else if (event.type === "response.failed") {
throw new Error(
`Response failed: ${event.response.error?.code ?? "unknown_error"}`
);
} else if (event.type === "response.completed") completed = true;
}
if (!completed) throw new Error("Stream ended without response.completed");
process.stdout.write("\n");
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
27
28
29
30import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["ACCESS_TOKEN"], # OAuth token sent as Bearer.
base_url="https://api.openai.com/v1",
max_retries=0,
)
completed = False
with client.responses.create(
model="gpt-6.2-sol",
input=[{"role": "user", "content": "Say exactly: Hello, world!"}],
store=False,
stream=True,
) as stream:
for event in stream:
if event.type == "response.output_text.delta":
print(event.delta, end="", flush=True)
elif event.type == "response.failed":
error = event.response.error
code = error.code if error else "unknown_error"
raise RuntimeError(f"Response failed: {code}")
elif event.type == "response.completed":
completed = True
if not completed:
raise RuntimeError("Stream ended without response.completed.")
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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56import (
"context"
"errors"
"fmt"
"log"
"os"
"time"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/option"
"github.com/openai/openai-go/v3/responses"
)
func run() error {
accessToken := os.Getenv("ACCESS_TOKEN")
if accessToken == "" {
return errors.New("ACCESS_TOKEN must contain a ChatGPT OAuth user token")
}
client := openai.NewClient(option.WithAPIKey(accessToken), option.WithBaseURL("https://api.openai.com/v1"), option.WithMaxRetries(0))
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
stream := client.Responses.NewStreaming(ctx, responses.ResponseNewParams{
Model: "gpt-6.2-sol",
Input: responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{
responses.ResponseInputItemParamOfMessage("Say exactly: Hello, world!", responses.EasyInputMessageRoleUser),
}},
Store: openai.Bool(false),
})
defer stream.Close()
completed := false
for stream.Next() {
event := stream.Current()
switch event.Type {
case "response.output_text.delta":
fmt.Print(event.AsResponseOutputTextDelta().Delta)
case "response.completed":
completed = true
case "response.failed", "response.incomplete", "error":
return fmt.Errorf("response stream ended with %s", event.Type)
}
}
if err := stream.Err(); err != nil {
return err
}
if !completed {
return errors.New("stream ended without response.completed")
}
fmt.Println()
return nil
}
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.StreamResponse;
import com.openai.models.responses.EasyInputMessage;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputItem;
import com.openai.models.responses.ResponseStreamEvent;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
String accessToken = System.getenv("ACCESS_TOKEN");
if (accessToken == null || accessToken.isBlank()) {
throw new IllegalStateException(
"ACCESS_TOKEN must contain the test user's OAuth access token");
}
OpenAIClient client =
OpenAIOkHttpClient.builder()
.apiKey(accessToken)
.baseUrl("https://api.openai.com/v1")
.maxRetries(0)
.timeout(Duration.ofMinutes(2))
.build();
ResponseCreateParams params =
ResponseCreateParams.builder()
.model("gpt-6.2-sol")
.inputOfResponse(
List.of(
ResponseInputItem.ofEasyInputMessage(
EasyInputMessage.builder()
.role(EasyInputMessage.Role.USER)
.content("Say exactly: Hello, world!")
.build())))
.store(false)
.build();
AtomicBoolean completed = new AtomicBoolean();
try (StreamResponse<ResponseStreamEvent> stream = client.responses().createStreaming(params)) {
stream.stream()
.forEach(
event -> {
event.outputTextDelta().ifPresent(delta -> System.out.print(delta.delta()));
if (event.failed().isPresent()
|| event.incomplete().isPresent()
|| event.error().isPresent()) {
throw new IllegalStateException("Response did not complete successfully");
}
if (event.completed().isPresent()) completed.set(true);
});
}
if (!completed.get())
throw new IllegalStateException("Response stream ended before completion");
System.out.println();
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
27
28
29
30
31
32
33
34
35
36
37
38using System.ClientModel;
using System.ClientModel.Primitives;
using OpenAI.Responses;
#pragma warning disable OPENAI001
string accessToken = Environment.GetEnvironmentVariable("ACCESS_TOKEN")
?? throw new InvalidOperationException("Provide the user's OAuth access token.");
ArgumentException.ThrowIfNullOrWhiteSpace(accessToken);
ResponsesClient client = new(new ApiKeyCredential(accessToken), new ResponsesClientOptions
{
Endpoint = new Uri("https://api.openai.com/v1"),
RetryPolicy = new ClientRetryPolicy(0)
});
CreateResponseOptions options = new("gpt-6.2-sol",
[ResponseItem.CreateUserMessageItem("Say exactly: Hello, world!")])
{
StreamingEnabled = true,
StoredOutputEnabled = false
};
using CancellationTokenSource deadline = new(TimeSpan.FromSeconds(120));
await using var stream = await client.CreateResponseStreamingAsync(options, deadline.Token);
bool completed = false;
await foreach (StreamingResponseUpdate update in stream.WithCancellation(deadline.Token))
{
switch (update)
{
case StreamingResponseOutputTextDeltaUpdate delta:
Console.Write(delta.Delta);
break;
case StreamingResponseCompletedUpdate:
completed = true;
break;
case StreamingResponseFailedUpdate or StreamingResponseIncompleteUpdate or StreamingResponseErrorUpdate:
throw new InvalidOperationException("Response did not complete successfully.");
}
}
if (!completed) throw new InvalidOperationException("Stream ended before response.completed.");
Console.WriteLine();
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
27
28
29
30
31
32
33
34
35
36
37
38require "openai"
access_token = ENV.fetch("ACCESS_TOKEN")
raise ArgumentError, "ACCESS_TOKEN must contain the user's OAuth token" if access_token.strip.empty?
client = OpenAI::Client.new(
api_key: access_token,
base_url: "https://api.openai.com/v1",
max_retries: 0,
timeout: 120
)
stream = client.responses.stream(
model: "gpt-6.2-sol",
input: [
{
role: "user",
content: "Say exactly: Hello, world!"
}
],
store: false
)
begin
stream.each do |event|
case event
when OpenAI::Models::Responses::ResponseTextDeltaEvent
print event.delta
when OpenAI::Models::Responses::ResponseFailedEvent,
OpenAI::Models::Responses::ResponseIncompleteEvent,
OpenAI::Models::Responses::ResponseErrorEvent
raise "Response did not complete successfully"
end
end
stream.get_final_response # Reject a stream that ends without response.completed.
puts
ensure
stream.close
end
Treat inference as successful only after receiving response.completed. Read through the terminal event. A usage-limit error can arrive as response.failed with subscription_sharing_usage_limit_exceeded or subscription_sharing_usage_unavailable after streaming has begun. Apply the corresponding recovery in Structured Responses errors. Handle response.incomplete, explicit errors, and interrupted streams separately from response.completed.