Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

token.ts

116 lines3.5 KB

1import { getOpenAIApiKeyFromEnv } from '../utils/client'
2import type { RealtimeToken, RealtimeTokenAdapter } from '@tanstack/ai'
3import type {
4 OpenAIRealtimeClientSecretResponse,
5 OpenAIRealtimeModel,
6 OpenAIRealtimeTokenOptions,
7} from './types'
8​
9const OPENAI_REALTIME_CLIENT_SECRETS_URL =
10 'https://api.openai.com/v1/realtime/client_secrets'
11​
12/**
13 * Builds the GA `/v1/realtime/client_secrets` request body.
14 *
15 * The session config (including its required `type`) is nested under the
16 * `session` key. The model is bound to the resulting ephemeral key, so the
17 * client never sends it during the WebRTC SDP exchange.
18 */
19export function buildClientSecretRequest(
20 model: OpenAIRealtimeModel,
21): Record<string, unknown> {
22 return { session: { type: 'realtime', model } }
24​
25/**
26 * Parses the GA client secret response into a {@link RealtimeToken}.
27 *
28 * GA returns the ephemeral key at the top level (`value` / `expires_at`),
29 * not nested under `client_secret` like the retired Beta
30 * `/v1/realtime/sessions` response did.
31 */
32export function parseClientSecretResponse(
33 data: Partial<OpenAIRealtimeClientSecretResponse> | undefined,
34 fallbackModel: OpenAIRealtimeModel,
35): RealtimeToken {
36 // Validate shape before dereferencing — the API could return an error
37 // envelope with 200 status, or a partial response under protocol drift.
38 if (
39 !data ||
40 typeof data.value !== 'string' ||
41 typeof data.expires_at !== 'number' ||
42 !Number.isFinite(data.expires_at)
43 ) {
44 throw new Error(
45 'OpenAI realtime client secret response missing or malformed `value`/`expires_at`',
46 )
47 }
48​
49 return {
50 provider: 'openai',
51 token: data.value,
52 expiresAt: data.expires_at * 1000,
53 config: {
54 model: data.session?.model ?? fallbackModel,
55 },
56 }
58​
59/**
60 * Creates an OpenAI realtime token adapter.
61 *
62 * This adapter generates ephemeral keys for client-side WebRTC connections
63 * via the GA `/v1/realtime/client_secrets` endpoint. The key is valid for
64 * 10 minutes by default.
65 *
66 * @param options - Configuration options for the realtime session
67 * @returns A RealtimeTokenAdapter for use with realtimeToken()
68 *
69 * @example
70 * ```typescript
71 * import { realtimeToken } from '@tanstack/ai'
72 * import { openaiRealtimeToken } from '@tanstack/ai-openai'
73 *
74 * const token = await realtimeToken({
75 * adapter: openaiRealtimeToken({ model: 'gpt-realtime-2.1' }),
76 * })
77 * ```
78 */
79export function openaiRealtimeToken(
80 options: OpenAIRealtimeTokenOptions = {},
81): RealtimeTokenAdapter {
82 const apiKey = getOpenAIApiKeyFromEnv()
83​
84 return {
85 provider: 'openai',
86​
87 async generateToken(): Promise<RealtimeToken> {
88 const model: OpenAIRealtimeModel = options.model ?? 'gpt-realtime-2.1'
89​
90 // Only the model is sent server-side; all other session config
91 // (instructions, voice, tools, VAD) is applied client-side via
92 // session.update.
93 const response = await fetch(OPENAI_REALTIME_CLIENT_SECRETS_URL, {
94 method: 'POST',
95 headers: {
96 Authorization: `Bearer ${apiKey}`,
97 'Content-Type': 'application/json',
98 },
99 body: JSON.stringify(buildClientSecretRequest(model)),
100 })
101​
102 if (!response.ok) {
103 const errorText = await response.text()
104 throw new Error(
105 `OpenAI realtime client secret creation failed: ${response.status} ${errorText}`,
106 )
107 }
108​
109 const data = (await response.json()) as
110 | Partial<OpenAIRealtimeClientSecretResponse>
111 | undefined
112​
113 return parseClientSecretResponse(data, model)
114 },
115 }