Open History to see the last commit
1import { GoogleGenAI } from '@google/genai'
2import { getGeminiApiKeyFromEnv } from '../utils'
3import type { RealtimeToken, RealtimeTokenAdapter } from '@tanstack/ai'
4import type { GeminiRealtimeTokenOptions } from './types'
5
6/**
7 * Creates a Google Gemini realtime token adapter.
8 *
9 * This adapter generates ephemeral tokens for client-side WebSocket connections.
10 *
11 * @param options - Configuration options for the realtime session
12 * @returns A RealtimeTokenAdapter for use with realtimeToken()
13 *
14 * @example
15 * ```typescript
16 * import { realtimeToken } from '@tanstack/ai'
17 * import { geminiRealtimeToken } from '@tanstack/ai-gemini'
18 *
19 * const token = await realtimeToken({
20 * adapter: geminiRealtimeToken({
21 * // Optional: constraint model config by token
22 * liveConnectConstraints: {
23 * model: 'gemini-3.8-live',
24 * },
25 * }),
26 * })
27 * ```
28 */
29export function geminiRealtimeToken(
30 options: GeminiRealtimeTokenOptions = {},
31): RealtimeTokenAdapter {
32 const apiKey = getGeminiApiKeyFromEnv()
33
34 const client = new GoogleGenAI({
35 apiKey,
36 })
37
38 return {
39 provider: 'gemini',
40 async generateToken(): Promise<RealtimeToken> {
41 // Computed per call so a reused adapter doesn't mint tokens with a
42 // fixed (and eventually past) expiry. Defaults to 30 minutes.
43 const expireTime = options.expiresAt ?? Date.now() + 30 * 60 * 1000
44
45 const token = await client.authTokens.create({
46 config: {
47 uses: options.uses ?? 1,
48 expireTime: new Date(expireTime).toISOString(),
49 liveConnectConstraints: options.liveConnectConstraints,
50 httpOptions: {
51 apiVersion: 'v1alpha',
52 },
53 },
54 })
55
56 if (!token.name) {
57 throw new Error('Gemini realtime token creation failed')
58 }
59
60 return {
61 provider: 'gemini',
62 token: token.name,
63 expiresAt: expireTime,
64 config: {
65 model: options.liveConnectConstraints?.model,
66 },
67 }
68 },
69 }
70}