Skip to content

Realtime

Connect to the Realtime API with the generated WebSocket client and wait for the initial session event.

This example assumes using tryAGI.OpenAI; is in scope and apiKey contains your tryAGI.OpenAI API key.

 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
var apiKey =
    Environment.GetEnvironmentVariable("OPENAI_API_KEY") is { Length: > 0 } apiKeyValue
        ? apiKeyValue
        : throw new AssertInconclusiveException("OPENAI_API_KEY environment variable is not found.");
var model =
    Environment.GetEnvironmentVariable("OPENAI_REALTIME_MODEL") is { Length: > 0 } modelValue
        ? modelValue
        : "gpt-4o-realtime-preview";

using var client = new OpenAiRealtimeClient(apiKey);
using var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var cancellationToken = cancellationTokenSource.Token;

await client.ConnectAsync(model: model, cancellationToken: cancellationToken);

await foreach (var serverEvent in client.ReceiveUpdatesAsync(cancellationToken))
{
    if (serverEvent.IsSessionCreated)
    {
        Console.WriteLine(serverEvent.SessionCreated!.EventId);
        return;
    }

    if (serverEvent.IsError)
    {
        throw new AssertFailedException(
            $"Realtime connection returned an error: {serverEvent.Error!.Error.Message}");
    }
}

throw new AssertFailedException("Realtime connection did not produce a session.created event before timing out.");