@tanstack/ai-react 0.6.4 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,7 @@
1
1
  export { useChat } from './use-chat.js';
2
+ export { useRealtimeChat } from './use-realtime-chat.js';
2
3
  export type { UseChatOptions, UseChatReturn, UIMessage, ChatRequestBody, } from './types.js';
4
+ export type { UseRealtimeChatOptions, UseRealtimeChatReturn, } from './realtime-types.js';
3
5
  export { useGeneration } from './use-generation.js';
4
6
  export type { UseGenerationOptions, UseGenerationReturn, } from './use-generation.js';
5
7
  export { useGenerateImage } from './use-generate-image.js';
package/dist/esm/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { useChat } from "./use-chat.js";
2
+ import { useRealtimeChat } from "./use-realtime-chat.js";
2
3
  import { useGeneration } from "./use-generation.js";
3
4
  import { useGenerateImage } from "./use-generate-image.js";
4
5
  import { useGenerateSpeech } from "./use-generate-speech.js";
@@ -16,6 +17,7 @@ export {
16
17
  useGenerateSpeech,
17
18
  useGenerateVideo,
18
19
  useGeneration,
20
+ useRealtimeChat,
19
21
  useSummarize,
20
22
  useTranscription
21
23
  };
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;"}
@@ -0,0 +1,109 @@
1
+ import { AnyClientTool, RealtimeMessage, RealtimeMode, RealtimeStatus, RealtimeToken } from '@tanstack/ai';
2
+ import { RealtimeAdapter } from '@tanstack/ai-client';
3
+ /**
4
+ * Options for the useRealtimeChat hook.
5
+ */
6
+ export interface UseRealtimeChatOptions {
7
+ /**
8
+ * Function to fetch a realtime token from the server.
9
+ * Called on connect and when token needs refresh.
10
+ */
11
+ getToken: () => Promise<RealtimeToken>;
12
+ /**
13
+ * The realtime adapter to use (e.g., openaiRealtime())
14
+ */
15
+ adapter: RealtimeAdapter;
16
+ /**
17
+ * Client-side tools with execution logic
18
+ */
19
+ tools?: ReadonlyArray<AnyClientTool>;
20
+ /**
21
+ * Auto-play assistant audio (default: true)
22
+ */
23
+ autoPlayback?: boolean;
24
+ /**
25
+ * Request microphone access on connect (default: true)
26
+ */
27
+ autoCapture?: boolean;
28
+ /**
29
+ * System instructions for the assistant
30
+ */
31
+ instructions?: string;
32
+ /**
33
+ * Voice to use for audio output
34
+ */
35
+ voice?: string;
36
+ /**
37
+ * Voice activity detection mode (default: 'server')
38
+ */
39
+ vadMode?: 'server' | 'semantic' | 'manual';
40
+ /**
41
+ * Output modalities for responses (e.g., ['audio', 'text'])
42
+ */
43
+ outputModalities?: Array<'audio' | 'text'>;
44
+ /**
45
+ * Temperature for generation (provider-specific range)
46
+ */
47
+ temperature?: number;
48
+ /**
49
+ * Maximum number of tokens in a response
50
+ */
51
+ maxOutputTokens?: number | 'inf';
52
+ /**
53
+ * Eagerness level for semantic VAD ('low', 'medium', 'high')
54
+ */
55
+ semanticEagerness?: 'low' | 'medium' | 'high';
56
+ onConnect?: () => void;
57
+ onDisconnect?: () => void;
58
+ onError?: (error: Error) => void;
59
+ onMessage?: (message: RealtimeMessage) => void;
60
+ onModeChange?: (mode: RealtimeMode) => void;
61
+ onInterrupted?: () => void;
62
+ }
63
+ /**
64
+ * Return type for the useRealtimeChat hook.
65
+ */
66
+ export interface UseRealtimeChatReturn {
67
+ /** Current connection status */
68
+ status: RealtimeStatus;
69
+ /** Current error, if any */
70
+ error: Error | null;
71
+ /** Connect to the realtime session */
72
+ connect: () => Promise<void>;
73
+ /** Disconnect from the realtime session */
74
+ disconnect: () => Promise<void>;
75
+ /** Current mode (idle, listening, thinking, speaking) */
76
+ mode: RealtimeMode;
77
+ /** Conversation messages */
78
+ messages: Array<RealtimeMessage>;
79
+ /** User transcript while speaking (before finalized) */
80
+ pendingUserTranscript: string | null;
81
+ /** Assistant transcript while speaking (before finalized) */
82
+ pendingAssistantTranscript: string | null;
83
+ /** Start listening for voice input (manual VAD mode) */
84
+ startListening: () => void;
85
+ /** Stop listening for voice input (manual VAD mode) */
86
+ stopListening: () => void;
87
+ /** Interrupt the current assistant response */
88
+ interrupt: () => void;
89
+ /** Send a text message instead of voice */
90
+ sendText: (text: string) => void;
91
+ /** Send an image to the conversation */
92
+ sendImage: (imageData: string, mimeType: string) => void;
93
+ /** Current input (microphone) volume level */
94
+ inputLevel: number;
95
+ /** Current output (speaker) volume level */
96
+ outputLevel: number;
97
+ /** Get frequency data for input audio visualization */
98
+ getInputFrequencyData: () => Uint8Array;
99
+ /** Get frequency data for output audio visualization */
100
+ getOutputFrequencyData: () => Uint8Array;
101
+ /** Get time domain data for input waveform */
102
+ getInputTimeDomainData: () => Uint8Array;
103
+ /** Get time domain data for output waveform */
104
+ getOutputTimeDomainData: () => Uint8Array;
105
+ /** Current VAD mode */
106
+ vadMode: 'server' | 'semantic' | 'manual';
107
+ /** Change VAD mode at runtime */
108
+ setVADMode: (mode: 'server' | 'semantic' | 'manual') => void;
109
+ }
@@ -0,0 +1,42 @@
1
+ import { UseRealtimeChatOptions, UseRealtimeChatReturn } from './realtime-types.js';
2
+ /**
3
+ * React hook for realtime voice conversations.
4
+ *
5
+ * Provides a simple interface for voice-to-voice AI interactions
6
+ * with support for multiple providers (OpenAI, ElevenLabs, etc.).
7
+ *
8
+ * @param options - Configuration options including adapter and callbacks
9
+ * @returns Hook return value with state and control methods
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * import { useRealtimeChat } from '@tanstack/ai-react'
14
+ * import { openaiRealtime } from '@tanstack/ai-openai'
15
+ *
16
+ * function VoiceChat() {
17
+ * const {
18
+ * status,
19
+ * mode,
20
+ * messages,
21
+ * connect,
22
+ * disconnect,
23
+ * inputLevel,
24
+ * outputLevel,
25
+ * } = useRealtimeChat({
26
+ * getToken: () => fetch('/api/realtime-token').then(r => r.json()),
27
+ * adapter: openaiRealtime(),
28
+ * })
29
+ *
30
+ * return (
31
+ * <div>
32
+ * <p>Status: {status}</p>
33
+ * <p>Mode: {mode}</p>
34
+ * <button onClick={status === 'idle' ? connect : disconnect}>
35
+ * {status === 'idle' ? 'Start' : 'Stop'}
36
+ * </button>
37
+ * </div>
38
+ * )
39
+ * }
40
+ * ```
41
+ */
42
+ export declare function useRealtimeChat(options: UseRealtimeChatOptions): UseRealtimeChatReturn;
@@ -0,0 +1,174 @@
1
+ import { useState, useRef, useEffect, useCallback } from "react";
2
+ import { RealtimeClient } from "@tanstack/ai-client";
3
+ const emptyFrequencyData = new Uint8Array(128);
4
+ const emptyTimeDomainData = new Uint8Array(128).fill(128);
5
+ function useRealtimeChat(options) {
6
+ const [status, setStatus] = useState("idle");
7
+ const [mode, setMode] = useState("idle");
8
+ const [messages, setMessages] = useState([]);
9
+ const [pendingUserTranscript, setPendingUserTranscript] = useState(null);
10
+ const [pendingAssistantTranscript, setPendingAssistantTranscript] = useState(null);
11
+ const [error, setError] = useState(null);
12
+ const [inputLevel, setInputLevel] = useState(0);
13
+ const [outputLevel, setOutputLevel] = useState(0);
14
+ const [vadMode, setVADModeState] = useState(
15
+ options.vadMode ?? "server"
16
+ );
17
+ const clientRef = useRef(null);
18
+ const optionsRef = useRef(options);
19
+ optionsRef.current = options;
20
+ const animationFrameRef = useRef(null);
21
+ if (!clientRef.current) {
22
+ clientRef.current = new RealtimeClient({
23
+ getToken: optionsRef.current.getToken,
24
+ adapter: optionsRef.current.adapter,
25
+ tools: optionsRef.current.tools,
26
+ instructions: optionsRef.current.instructions,
27
+ voice: optionsRef.current.voice,
28
+ autoPlayback: optionsRef.current.autoPlayback,
29
+ autoCapture: optionsRef.current.autoCapture,
30
+ vadMode: optionsRef.current.vadMode,
31
+ outputModalities: optionsRef.current.outputModalities,
32
+ temperature: optionsRef.current.temperature,
33
+ maxOutputTokens: optionsRef.current.maxOutputTokens,
34
+ semanticEagerness: optionsRef.current.semanticEagerness,
35
+ onStatusChange: (newStatus) => {
36
+ setStatus(newStatus);
37
+ },
38
+ onModeChange: (newMode) => {
39
+ setMode(newMode);
40
+ optionsRef.current.onModeChange?.(newMode);
41
+ },
42
+ onMessage: (message) => {
43
+ setMessages((prev) => [...prev, message]);
44
+ optionsRef.current.onMessage?.(message);
45
+ },
46
+ onError: (err) => {
47
+ setError(err);
48
+ optionsRef.current.onError?.(err);
49
+ },
50
+ onConnect: () => {
51
+ setError(null);
52
+ optionsRef.current.onConnect?.();
53
+ },
54
+ onDisconnect: () => {
55
+ optionsRef.current.onDisconnect?.();
56
+ },
57
+ onInterrupted: () => {
58
+ setPendingAssistantTranscript(null);
59
+ optionsRef.current.onInterrupted?.();
60
+ }
61
+ });
62
+ clientRef.current.onStateChange((state) => {
63
+ setPendingUserTranscript(state.pendingUserTranscript);
64
+ setPendingAssistantTranscript(state.pendingAssistantTranscript);
65
+ });
66
+ }
67
+ const client = clientRef.current;
68
+ useEffect(() => {
69
+ function updateLevels() {
70
+ if (clientRef.current?.audio) {
71
+ setInputLevel(clientRef.current.audio.inputLevel);
72
+ setOutputLevel(clientRef.current.audio.outputLevel);
73
+ }
74
+ animationFrameRef.current = requestAnimationFrame(updateLevels);
75
+ }
76
+ if (status === "connected") {
77
+ updateLevels();
78
+ }
79
+ return () => {
80
+ if (animationFrameRef.current) {
81
+ cancelAnimationFrame(animationFrameRef.current);
82
+ animationFrameRef.current = null;
83
+ }
84
+ };
85
+ }, [status]);
86
+ useEffect(() => {
87
+ return () => {
88
+ clientRef.current?.destroy();
89
+ };
90
+ }, []);
91
+ const connect = useCallback(async () => {
92
+ setError(null);
93
+ setMessages([]);
94
+ setPendingUserTranscript(null);
95
+ setPendingAssistantTranscript(null);
96
+ await client.connect();
97
+ }, [client]);
98
+ const disconnect = useCallback(async () => {
99
+ await client.disconnect();
100
+ }, [client]);
101
+ const startListening = useCallback(() => {
102
+ client.startListening();
103
+ }, [client]);
104
+ const stopListening = useCallback(() => {
105
+ client.stopListening();
106
+ }, [client]);
107
+ const interrupt = useCallback(() => {
108
+ client.interrupt();
109
+ }, [client]);
110
+ const sendText = useCallback(
111
+ (text) => {
112
+ client.sendText(text);
113
+ },
114
+ [client]
115
+ );
116
+ const sendImage = useCallback(
117
+ (imageData, mimeType) => {
118
+ client.sendImage(imageData, mimeType);
119
+ },
120
+ [client]
121
+ );
122
+ const getInputFrequencyData = useCallback(() => {
123
+ return clientRef.current?.audio?.getInputFrequencyData() ?? emptyFrequencyData;
124
+ }, []);
125
+ const getOutputFrequencyData = useCallback(() => {
126
+ return clientRef.current?.audio?.getOutputFrequencyData() ?? emptyFrequencyData;
127
+ }, []);
128
+ const getInputTimeDomainData = useCallback(() => {
129
+ return clientRef.current?.audio?.getInputTimeDomainData() ?? emptyTimeDomainData;
130
+ }, []);
131
+ const getOutputTimeDomainData = useCallback(() => {
132
+ return clientRef.current?.audio?.getOutputTimeDomainData() ?? emptyTimeDomainData;
133
+ }, []);
134
+ const setVADMode = useCallback(
135
+ (newMode) => {
136
+ setVADModeState(newMode);
137
+ },
138
+ []
139
+ );
140
+ return {
141
+ // Connection state
142
+ status,
143
+ error,
144
+ connect,
145
+ disconnect,
146
+ // Conversation state
147
+ mode,
148
+ messages,
149
+ pendingUserTranscript,
150
+ pendingAssistantTranscript,
151
+ // Voice control
152
+ startListening,
153
+ stopListening,
154
+ interrupt,
155
+ // Text input
156
+ sendText,
157
+ // Image input
158
+ sendImage,
159
+ // Audio visualization
160
+ inputLevel,
161
+ outputLevel,
162
+ getInputFrequencyData,
163
+ getOutputFrequencyData,
164
+ getInputTimeDomainData,
165
+ getOutputTimeDomainData,
166
+ // VAD control
167
+ vadMode,
168
+ setVADMode
169
+ };
170
+ }
171
+ export {
172
+ useRealtimeChat
173
+ };
174
+ //# sourceMappingURL=use-realtime-chat.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-realtime-chat.js","sources":["../../src/use-realtime-chat.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from 'react'\nimport { RealtimeClient } from '@tanstack/ai-client'\nimport type {\n RealtimeMessage,\n RealtimeMode,\n RealtimeStatus,\n} from '@tanstack/ai'\nimport type {\n UseRealtimeChatOptions,\n UseRealtimeChatReturn,\n} from './realtime-types'\n\n// Empty frequency data for when client is not connected\nconst emptyFrequencyData = new Uint8Array(128)\nconst emptyTimeDomainData = new Uint8Array(128).fill(128)\n\n/**\n * React hook for realtime voice conversations.\n *\n * Provides a simple interface for voice-to-voice AI interactions\n * with support for multiple providers (OpenAI, ElevenLabs, etc.).\n *\n * @param options - Configuration options including adapter and callbacks\n * @returns Hook return value with state and control methods\n *\n * @example\n * ```typescript\n * import { useRealtimeChat } from '@tanstack/ai-react'\n * import { openaiRealtime } from '@tanstack/ai-openai'\n *\n * function VoiceChat() {\n * const {\n * status,\n * mode,\n * messages,\n * connect,\n * disconnect,\n * inputLevel,\n * outputLevel,\n * } = useRealtimeChat({\n * getToken: () => fetch('/api/realtime-token').then(r => r.json()),\n * adapter: openaiRealtime(),\n * })\n *\n * return (\n * <div>\n * <p>Status: {status}</p>\n * <p>Mode: {mode}</p>\n * <button onClick={status === 'idle' ? connect : disconnect}>\n * {status === 'idle' ? 'Start' : 'Stop'}\n * </button>\n * </div>\n * )\n * }\n * ```\n */\nexport function useRealtimeChat(\n options: UseRealtimeChatOptions,\n): UseRealtimeChatReturn {\n // State\n const [status, setStatus] = useState<RealtimeStatus>('idle')\n const [mode, setMode] = useState<RealtimeMode>('idle')\n const [messages, setMessages] = useState<Array<RealtimeMessage>>([])\n const [pendingUserTranscript, setPendingUserTranscript] = useState<\n string | null\n >(null)\n const [pendingAssistantTranscript, setPendingAssistantTranscript] = useState<\n string | null\n >(null)\n const [error, setError] = useState<Error | null>(null)\n const [inputLevel, setInputLevel] = useState(0)\n const [outputLevel, setOutputLevel] = useState(0)\n const [vadMode, setVADModeState] = useState<'server' | 'semantic' | 'manual'>(\n options.vadMode ?? 'server',\n )\n\n // Refs\n const clientRef = useRef<RealtimeClient | null>(null)\n const optionsRef = useRef(options)\n optionsRef.current = options\n const animationFrameRef = useRef<number | null>(null)\n\n // Create client instance - use ref to ensure we reuse the same instance\n // This handles React StrictMode double-rendering\n if (!clientRef.current) {\n clientRef.current = new RealtimeClient({\n getToken: optionsRef.current.getToken,\n adapter: optionsRef.current.adapter,\n tools: optionsRef.current.tools,\n instructions: optionsRef.current.instructions,\n voice: optionsRef.current.voice,\n autoPlayback: optionsRef.current.autoPlayback,\n autoCapture: optionsRef.current.autoCapture,\n vadMode: optionsRef.current.vadMode,\n outputModalities: optionsRef.current.outputModalities,\n temperature: optionsRef.current.temperature,\n maxOutputTokens: optionsRef.current.maxOutputTokens,\n semanticEagerness: optionsRef.current.semanticEagerness,\n onStatusChange: (newStatus) => {\n setStatus(newStatus)\n },\n onModeChange: (newMode) => {\n setMode(newMode)\n optionsRef.current.onModeChange?.(newMode)\n },\n onMessage: (message) => {\n setMessages((prev) => [...prev, message])\n optionsRef.current.onMessage?.(message)\n },\n onError: (err) => {\n setError(err)\n optionsRef.current.onError?.(err)\n },\n onConnect: () => {\n setError(null)\n optionsRef.current.onConnect?.()\n },\n onDisconnect: () => {\n optionsRef.current.onDisconnect?.()\n },\n onInterrupted: () => {\n setPendingAssistantTranscript(null)\n optionsRef.current.onInterrupted?.()\n },\n })\n\n // Subscribe to state changes for transcripts\n clientRef.current.onStateChange((state) => {\n setPendingUserTranscript(state.pendingUserTranscript)\n setPendingAssistantTranscript(state.pendingAssistantTranscript)\n })\n }\n\n const client = clientRef.current\n\n // Audio level animation loop\n useEffect(() => {\n function updateLevels() {\n if (clientRef.current?.audio) {\n setInputLevel(clientRef.current.audio.inputLevel)\n setOutputLevel(clientRef.current.audio.outputLevel)\n }\n animationFrameRef.current = requestAnimationFrame(updateLevels)\n }\n\n if (status === 'connected') {\n updateLevels()\n }\n\n return () => {\n if (animationFrameRef.current) {\n cancelAnimationFrame(animationFrameRef.current)\n animationFrameRef.current = null\n }\n }\n }, [status])\n\n // Cleanup on unmount\n useEffect(() => {\n return () => {\n clientRef.current?.destroy()\n }\n }, [])\n\n // Connection methods\n const connect = useCallback(async () => {\n setError(null)\n setMessages([])\n setPendingUserTranscript(null)\n setPendingAssistantTranscript(null)\n await client.connect()\n }, [client])\n\n const disconnect = useCallback(async () => {\n await client.disconnect()\n }, [client])\n\n // Voice control methods\n const startListening = useCallback(() => {\n client.startListening()\n }, [client])\n\n const stopListening = useCallback(() => {\n client.stopListening()\n }, [client])\n\n const interrupt = useCallback(() => {\n client.interrupt()\n }, [client])\n\n // Text input\n const sendText = useCallback(\n (text: string) => {\n client.sendText(text)\n },\n [client],\n )\n\n // Image input\n const sendImage = useCallback(\n (imageData: string, mimeType: string) => {\n client.sendImage(imageData, mimeType)\n },\n [client],\n )\n\n // Audio visualization\n const getInputFrequencyData = useCallback(() => {\n return (\n clientRef.current?.audio?.getInputFrequencyData() ?? emptyFrequencyData\n )\n }, [])\n\n const getOutputFrequencyData = useCallback(() => {\n return (\n clientRef.current?.audio?.getOutputFrequencyData() ?? emptyFrequencyData\n )\n }, [])\n\n const getInputTimeDomainData = useCallback(() => {\n return (\n clientRef.current?.audio?.getInputTimeDomainData() ?? emptyTimeDomainData\n )\n }, [])\n\n const getOutputTimeDomainData = useCallback(() => {\n return (\n clientRef.current?.audio?.getOutputTimeDomainData() ?? emptyTimeDomainData\n )\n }, [])\n\n // VAD mode control\n const setVADMode = useCallback(\n (newMode: 'server' | 'semantic' | 'manual') => {\n setVADModeState(newMode)\n // TODO: Update session config if connected\n },\n [],\n )\n\n return {\n // Connection state\n status,\n error,\n connect,\n disconnect,\n\n // Conversation state\n mode,\n messages,\n pendingUserTranscript,\n pendingAssistantTranscript,\n\n // Voice control\n startListening,\n stopListening,\n interrupt,\n\n // Text input\n sendText,\n\n // Image input\n sendImage,\n\n // Audio visualization\n inputLevel,\n outputLevel,\n getInputFrequencyData,\n getOutputFrequencyData,\n getInputTimeDomainData,\n getOutputTimeDomainData,\n\n // VAD control\n vadMode,\n setVADMode,\n }\n}\n"],"names":[],"mappings":";;AAaA,MAAM,qBAAqB,IAAI,WAAW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AAAA,EAAC;AAGH,SAAO;AAAA;AAAA,IAEL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA,IAGA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA,IAGA;AAAA,IACA;AAAA,IACA;AAAA;AAAA,IAGA;AAAA;AAAA,IAGA;AAAA;AAAA,IAGA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA,IAGA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/ai-react",
3
- "version": "0.6.4",
3
+ "version": "0.7.1",
4
4
  "description": "React hooks for TanStack AI",
5
5
  "author": "",
6
6
  "license": "MIT",
@@ -31,12 +31,12 @@
31
31
  "streaming"
32
32
  ],
33
33
  "dependencies": {
34
- "@tanstack/ai-client": "0.6.0"
34
+ "@tanstack/ai-client": "0.7.1"
35
35
  },
36
36
  "peerDependencies": {
37
37
  "@types/react": ">=18.0.0",
38
38
  "react": ">=18.0.0",
39
- "@tanstack/ai": "^0.6.3"
39
+ "@tanstack/ai": "^0.8.0"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@testing-library/react": "^16.3.0",
@@ -45,7 +45,7 @@
45
45
  "jsdom": "^27.2.0",
46
46
  "react": "^19.2.3",
47
47
  "vite": "^7.2.7",
48
- "@tanstack/ai": "0.6.3"
48
+ "@tanstack/ai": "0.8.0"
49
49
  },
50
50
  "scripts": {
51
51
  "clean": "premove ./build ./dist",
package/src/index.ts CHANGED
@@ -1,10 +1,15 @@
1
1
  export { useChat } from './use-chat'
2
+ export { useRealtimeChat } from './use-realtime-chat'
2
3
  export type {
3
4
  UseChatOptions,
4
5
  UseChatReturn,
5
6
  UIMessage,
6
7
  ChatRequestBody,
7
8
  } from './types'
9
+ export type {
10
+ UseRealtimeChatOptions,
11
+ UseRealtimeChatReturn,
12
+ } from './realtime-types'
8
13
 
9
14
  // Generation hooks
10
15
  export { useGeneration } from './use-generation'
@@ -0,0 +1,143 @@
1
+ import type {
2
+ AnyClientTool,
3
+ RealtimeMessage,
4
+ RealtimeMode,
5
+ RealtimeStatus,
6
+ RealtimeToken,
7
+ } from '@tanstack/ai'
8
+ import type { RealtimeAdapter } from '@tanstack/ai-client'
9
+
10
+ /**
11
+ * Options for the useRealtimeChat hook.
12
+ */
13
+ export interface UseRealtimeChatOptions {
14
+ /**
15
+ * Function to fetch a realtime token from the server.
16
+ * Called on connect and when token needs refresh.
17
+ */
18
+ getToken: () => Promise<RealtimeToken>
19
+
20
+ /**
21
+ * The realtime adapter to use (e.g., openaiRealtime())
22
+ */
23
+ adapter: RealtimeAdapter
24
+
25
+ /**
26
+ * Client-side tools with execution logic
27
+ */
28
+ tools?: ReadonlyArray<AnyClientTool>
29
+
30
+ /**
31
+ * Auto-play assistant audio (default: true)
32
+ */
33
+ autoPlayback?: boolean
34
+
35
+ /**
36
+ * Request microphone access on connect (default: true)
37
+ */
38
+ autoCapture?: boolean
39
+
40
+ /**
41
+ * System instructions for the assistant
42
+ */
43
+ instructions?: string
44
+
45
+ /**
46
+ * Voice to use for audio output
47
+ */
48
+ voice?: string
49
+
50
+ /**
51
+ * Voice activity detection mode (default: 'server')
52
+ */
53
+ vadMode?: 'server' | 'semantic' | 'manual'
54
+
55
+ /**
56
+ * Output modalities for responses (e.g., ['audio', 'text'])
57
+ */
58
+ outputModalities?: Array<'audio' | 'text'>
59
+
60
+ /**
61
+ * Temperature for generation (provider-specific range)
62
+ */
63
+ temperature?: number
64
+
65
+ /**
66
+ * Maximum number of tokens in a response
67
+ */
68
+ maxOutputTokens?: number | 'inf'
69
+
70
+ /**
71
+ * Eagerness level for semantic VAD ('low', 'medium', 'high')
72
+ */
73
+ semanticEagerness?: 'low' | 'medium' | 'high'
74
+
75
+ // Callbacks
76
+ onConnect?: () => void
77
+ onDisconnect?: () => void
78
+ onError?: (error: Error) => void
79
+ onMessage?: (message: RealtimeMessage) => void
80
+ onModeChange?: (mode: RealtimeMode) => void
81
+ onInterrupted?: () => void
82
+ }
83
+
84
+ /**
85
+ * Return type for the useRealtimeChat hook.
86
+ */
87
+ export interface UseRealtimeChatReturn {
88
+ // Connection state
89
+ /** Current connection status */
90
+ status: RealtimeStatus
91
+ /** Current error, if any */
92
+ error: Error | null
93
+ /** Connect to the realtime session */
94
+ connect: () => Promise<void>
95
+ /** Disconnect from the realtime session */
96
+ disconnect: () => Promise<void>
97
+
98
+ // Conversation state
99
+ /** Current mode (idle, listening, thinking, speaking) */
100
+ mode: RealtimeMode
101
+ /** Conversation messages */
102
+ messages: Array<RealtimeMessage>
103
+ /** User transcript while speaking (before finalized) */
104
+ pendingUserTranscript: string | null
105
+ /** Assistant transcript while speaking (before finalized) */
106
+ pendingAssistantTranscript: string | null
107
+
108
+ // Voice control
109
+ /** Start listening for voice input (manual VAD mode) */
110
+ startListening: () => void
111
+ /** Stop listening for voice input (manual VAD mode) */
112
+ stopListening: () => void
113
+ /** Interrupt the current assistant response */
114
+ interrupt: () => void
115
+
116
+ // Text input
117
+ /** Send a text message instead of voice */
118
+ sendText: (text: string) => void
119
+
120
+ // Image input
121
+ /** Send an image to the conversation */
122
+ sendImage: (imageData: string, mimeType: string) => void
123
+
124
+ // Audio visualization (0-1 normalized)
125
+ /** Current input (microphone) volume level */
126
+ inputLevel: number
127
+ /** Current output (speaker) volume level */
128
+ outputLevel: number
129
+ /** Get frequency data for input audio visualization */
130
+ getInputFrequencyData: () => Uint8Array
131
+ /** Get frequency data for output audio visualization */
132
+ getOutputFrequencyData: () => Uint8Array
133
+ /** Get time domain data for input waveform */
134
+ getInputTimeDomainData: () => Uint8Array
135
+ /** Get time domain data for output waveform */
136
+ getOutputTimeDomainData: () => Uint8Array
137
+
138
+ // VAD control
139
+ /** Current VAD mode */
140
+ vadMode: 'server' | 'semantic' | 'manual'
141
+ /** Change VAD mode at runtime */
142
+ setVADMode: (mode: 'server' | 'semantic' | 'manual') => void
143
+ }
@@ -0,0 +1,277 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react'
2
+ import { RealtimeClient } from '@tanstack/ai-client'
3
+ import type {
4
+ RealtimeMessage,
5
+ RealtimeMode,
6
+ RealtimeStatus,
7
+ } from '@tanstack/ai'
8
+ import type {
9
+ UseRealtimeChatOptions,
10
+ UseRealtimeChatReturn,
11
+ } from './realtime-types'
12
+
13
+ // Empty frequency data for when client is not connected
14
+ const emptyFrequencyData = new Uint8Array(128)
15
+ const emptyTimeDomainData = new Uint8Array(128).fill(128)
16
+
17
+ /**
18
+ * React hook for realtime voice conversations.
19
+ *
20
+ * Provides a simple interface for voice-to-voice AI interactions
21
+ * with support for multiple providers (OpenAI, ElevenLabs, etc.).
22
+ *
23
+ * @param options - Configuration options including adapter and callbacks
24
+ * @returns Hook return value with state and control methods
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * import { useRealtimeChat } from '@tanstack/ai-react'
29
+ * import { openaiRealtime } from '@tanstack/ai-openai'
30
+ *
31
+ * function VoiceChat() {
32
+ * const {
33
+ * status,
34
+ * mode,
35
+ * messages,
36
+ * connect,
37
+ * disconnect,
38
+ * inputLevel,
39
+ * outputLevel,
40
+ * } = useRealtimeChat({
41
+ * getToken: () => fetch('/api/realtime-token').then(r => r.json()),
42
+ * adapter: openaiRealtime(),
43
+ * })
44
+ *
45
+ * return (
46
+ * <div>
47
+ * <p>Status: {status}</p>
48
+ * <p>Mode: {mode}</p>
49
+ * <button onClick={status === 'idle' ? connect : disconnect}>
50
+ * {status === 'idle' ? 'Start' : 'Stop'}
51
+ * </button>
52
+ * </div>
53
+ * )
54
+ * }
55
+ * ```
56
+ */
57
+ export function useRealtimeChat(
58
+ options: UseRealtimeChatOptions,
59
+ ): UseRealtimeChatReturn {
60
+ // State
61
+ const [status, setStatus] = useState<RealtimeStatus>('idle')
62
+ const [mode, setMode] = useState<RealtimeMode>('idle')
63
+ const [messages, setMessages] = useState<Array<RealtimeMessage>>([])
64
+ const [pendingUserTranscript, setPendingUserTranscript] = useState<
65
+ string | null
66
+ >(null)
67
+ const [pendingAssistantTranscript, setPendingAssistantTranscript] = useState<
68
+ string | null
69
+ >(null)
70
+ const [error, setError] = useState<Error | null>(null)
71
+ const [inputLevel, setInputLevel] = useState(0)
72
+ const [outputLevel, setOutputLevel] = useState(0)
73
+ const [vadMode, setVADModeState] = useState<'server' | 'semantic' | 'manual'>(
74
+ options.vadMode ?? 'server',
75
+ )
76
+
77
+ // Refs
78
+ const clientRef = useRef<RealtimeClient | null>(null)
79
+ const optionsRef = useRef(options)
80
+ optionsRef.current = options
81
+ const animationFrameRef = useRef<number | null>(null)
82
+
83
+ // Create client instance - use ref to ensure we reuse the same instance
84
+ // This handles React StrictMode double-rendering
85
+ if (!clientRef.current) {
86
+ clientRef.current = new RealtimeClient({
87
+ getToken: optionsRef.current.getToken,
88
+ adapter: optionsRef.current.adapter,
89
+ tools: optionsRef.current.tools,
90
+ instructions: optionsRef.current.instructions,
91
+ voice: optionsRef.current.voice,
92
+ autoPlayback: optionsRef.current.autoPlayback,
93
+ autoCapture: optionsRef.current.autoCapture,
94
+ vadMode: optionsRef.current.vadMode,
95
+ outputModalities: optionsRef.current.outputModalities,
96
+ temperature: optionsRef.current.temperature,
97
+ maxOutputTokens: optionsRef.current.maxOutputTokens,
98
+ semanticEagerness: optionsRef.current.semanticEagerness,
99
+ onStatusChange: (newStatus) => {
100
+ setStatus(newStatus)
101
+ },
102
+ onModeChange: (newMode) => {
103
+ setMode(newMode)
104
+ optionsRef.current.onModeChange?.(newMode)
105
+ },
106
+ onMessage: (message) => {
107
+ setMessages((prev) => [...prev, message])
108
+ optionsRef.current.onMessage?.(message)
109
+ },
110
+ onError: (err) => {
111
+ setError(err)
112
+ optionsRef.current.onError?.(err)
113
+ },
114
+ onConnect: () => {
115
+ setError(null)
116
+ optionsRef.current.onConnect?.()
117
+ },
118
+ onDisconnect: () => {
119
+ optionsRef.current.onDisconnect?.()
120
+ },
121
+ onInterrupted: () => {
122
+ setPendingAssistantTranscript(null)
123
+ optionsRef.current.onInterrupted?.()
124
+ },
125
+ })
126
+
127
+ // Subscribe to state changes for transcripts
128
+ clientRef.current.onStateChange((state) => {
129
+ setPendingUserTranscript(state.pendingUserTranscript)
130
+ setPendingAssistantTranscript(state.pendingAssistantTranscript)
131
+ })
132
+ }
133
+
134
+ const client = clientRef.current
135
+
136
+ // Audio level animation loop
137
+ useEffect(() => {
138
+ function updateLevels() {
139
+ if (clientRef.current?.audio) {
140
+ setInputLevel(clientRef.current.audio.inputLevel)
141
+ setOutputLevel(clientRef.current.audio.outputLevel)
142
+ }
143
+ animationFrameRef.current = requestAnimationFrame(updateLevels)
144
+ }
145
+
146
+ if (status === 'connected') {
147
+ updateLevels()
148
+ }
149
+
150
+ return () => {
151
+ if (animationFrameRef.current) {
152
+ cancelAnimationFrame(animationFrameRef.current)
153
+ animationFrameRef.current = null
154
+ }
155
+ }
156
+ }, [status])
157
+
158
+ // Cleanup on unmount
159
+ useEffect(() => {
160
+ return () => {
161
+ clientRef.current?.destroy()
162
+ }
163
+ }, [])
164
+
165
+ // Connection methods
166
+ const connect = useCallback(async () => {
167
+ setError(null)
168
+ setMessages([])
169
+ setPendingUserTranscript(null)
170
+ setPendingAssistantTranscript(null)
171
+ await client.connect()
172
+ }, [client])
173
+
174
+ const disconnect = useCallback(async () => {
175
+ await client.disconnect()
176
+ }, [client])
177
+
178
+ // Voice control methods
179
+ const startListening = useCallback(() => {
180
+ client.startListening()
181
+ }, [client])
182
+
183
+ const stopListening = useCallback(() => {
184
+ client.stopListening()
185
+ }, [client])
186
+
187
+ const interrupt = useCallback(() => {
188
+ client.interrupt()
189
+ }, [client])
190
+
191
+ // Text input
192
+ const sendText = useCallback(
193
+ (text: string) => {
194
+ client.sendText(text)
195
+ },
196
+ [client],
197
+ )
198
+
199
+ // Image input
200
+ const sendImage = useCallback(
201
+ (imageData: string, mimeType: string) => {
202
+ client.sendImage(imageData, mimeType)
203
+ },
204
+ [client],
205
+ )
206
+
207
+ // Audio visualization
208
+ const getInputFrequencyData = useCallback(() => {
209
+ return (
210
+ clientRef.current?.audio?.getInputFrequencyData() ?? emptyFrequencyData
211
+ )
212
+ }, [])
213
+
214
+ const getOutputFrequencyData = useCallback(() => {
215
+ return (
216
+ clientRef.current?.audio?.getOutputFrequencyData() ?? emptyFrequencyData
217
+ )
218
+ }, [])
219
+
220
+ const getInputTimeDomainData = useCallback(() => {
221
+ return (
222
+ clientRef.current?.audio?.getInputTimeDomainData() ?? emptyTimeDomainData
223
+ )
224
+ }, [])
225
+
226
+ const getOutputTimeDomainData = useCallback(() => {
227
+ return (
228
+ clientRef.current?.audio?.getOutputTimeDomainData() ?? emptyTimeDomainData
229
+ )
230
+ }, [])
231
+
232
+ // VAD mode control
233
+ const setVADMode = useCallback(
234
+ (newMode: 'server' | 'semantic' | 'manual') => {
235
+ setVADModeState(newMode)
236
+ // TODO: Update session config if connected
237
+ },
238
+ [],
239
+ )
240
+
241
+ return {
242
+ // Connection state
243
+ status,
244
+ error,
245
+ connect,
246
+ disconnect,
247
+
248
+ // Conversation state
249
+ mode,
250
+ messages,
251
+ pendingUserTranscript,
252
+ pendingAssistantTranscript,
253
+
254
+ // Voice control
255
+ startListening,
256
+ stopListening,
257
+ interrupt,
258
+
259
+ // Text input
260
+ sendText,
261
+
262
+ // Image input
263
+ sendImage,
264
+
265
+ // Audio visualization
266
+ inputLevel,
267
+ outputLevel,
268
+ getInputFrequencyData,
269
+ getOutputFrequencyData,
270
+ getInputTimeDomainData,
271
+ getOutputTimeDomainData,
272
+
273
+ // VAD control
274
+ vadMode,
275
+ setVADMode,
276
+ }
277
+ }