@tanstack/ai-react 0.6.4 → 0.7.2
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.
- package/README.md +6 -6
- package/dist/esm/index.d.ts +2 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/realtime-types.d.ts +109 -0
- package/dist/esm/types.d.ts +23 -2
- package/dist/esm/use-chat.js +28 -2
- package/dist/esm/use-chat.js.map +1 -1
- package/dist/esm/use-generate-image.d.ts +6 -6
- package/dist/esm/use-generate-image.js.map +1 -1
- package/dist/esm/use-generate-speech.d.ts +5 -5
- package/dist/esm/use-generate-speech.js.map +1 -1
- package/dist/esm/use-generate-video.d.ts +5 -5
- package/dist/esm/use-generate-video.js.map +1 -1
- package/dist/esm/use-generation.d.ts +5 -5
- package/dist/esm/use-generation.js.map +1 -1
- package/dist/esm/use-realtime-chat.d.ts +42 -0
- package/dist/esm/use-realtime-chat.js +174 -0
- package/dist/esm/use-realtime-chat.js.map +1 -0
- package/dist/esm/use-summarize.d.ts +5 -5
- package/dist/esm/use-summarize.js.map +1 -1
- package/dist/esm/use-transcription.d.ts +5 -5
- package/dist/esm/use-transcription.js.map +1 -1
- package/package.json +4 -4
- package/src/index.ts +5 -0
- package/src/realtime-types.ts +143 -0
- package/src/types.ts +33 -2
- package/src/use-chat.ts +33 -4
- package/src/use-generate-image.ts +6 -6
- package/src/use-generate-speech.ts +5 -5
- package/src/use-generate-video.ts +5 -5
- package/src/use-generation.ts +5 -5
- package/src/use-realtime-chat.ts +277 -0
- package/src/use-summarize.ts +5 -5
- package/src/use-transcription.ts +5 -5
|
@@ -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,GAAG;AAC7C,MAAM,sBAAsB,IAAI,WAAW,GAAG,EAAE,KAAK,GAAG;AA0CjD,SAAS,gBACd,SACuB;AAEvB,QAAM,CAAC,QAAQ,SAAS,IAAI,SAAyB,MAAM;AAC3D,QAAM,CAAC,MAAM,OAAO,IAAI,SAAuB,MAAM;AACrD,QAAM,CAAC,UAAU,WAAW,IAAI,SAAiC,CAAA,CAAE;AACnE,QAAM,CAAC,uBAAuB,wBAAwB,IAAI,SAExD,IAAI;AACN,QAAM,CAAC,4BAA4B,6BAA6B,IAAI,SAElE,IAAI;AACN,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAuB,IAAI;AACrD,QAAM,CAAC,YAAY,aAAa,IAAI,SAAS,CAAC;AAC9C,QAAM,CAAC,aAAa,cAAc,IAAI,SAAS,CAAC;AAChD,QAAM,CAAC,SAAS,eAAe,IAAI;AAAA,IACjC,QAAQ,WAAW;AAAA,EAAA;AAIrB,QAAM,YAAY,OAA8B,IAAI;AACpD,QAAM,aAAa,OAAO,OAAO;AACjC,aAAW,UAAU;AACrB,QAAM,oBAAoB,OAAsB,IAAI;AAIpD,MAAI,CAAC,UAAU,SAAS;AACtB,cAAU,UAAU,IAAI,eAAe;AAAA,MACrC,UAAU,WAAW,QAAQ;AAAA,MAC7B,SAAS,WAAW,QAAQ;AAAA,MAC5B,OAAO,WAAW,QAAQ;AAAA,MAC1B,cAAc,WAAW,QAAQ;AAAA,MACjC,OAAO,WAAW,QAAQ;AAAA,MAC1B,cAAc,WAAW,QAAQ;AAAA,MACjC,aAAa,WAAW,QAAQ;AAAA,MAChC,SAAS,WAAW,QAAQ;AAAA,MAC5B,kBAAkB,WAAW,QAAQ;AAAA,MACrC,aAAa,WAAW,QAAQ;AAAA,MAChC,iBAAiB,WAAW,QAAQ;AAAA,MACpC,mBAAmB,WAAW,QAAQ;AAAA,MACtC,gBAAgB,CAAC,cAAc;AAC7B,kBAAU,SAAS;AAAA,MACrB;AAAA,MACA,cAAc,CAAC,YAAY;AACzB,gBAAQ,OAAO;AACf,mBAAW,QAAQ,eAAe,OAAO;AAAA,MAC3C;AAAA,MACA,WAAW,CAAC,YAAY;AACtB,oBAAY,CAAC,SAAS,CAAC,GAAG,MAAM,OAAO,CAAC;AACxC,mBAAW,QAAQ,YAAY,OAAO;AAAA,MACxC;AAAA,MACA,SAAS,CAAC,QAAQ;AAChB,iBAAS,GAAG;AACZ,mBAAW,QAAQ,UAAU,GAAG;AAAA,MAClC;AAAA,MACA,WAAW,MAAM;AACf,iBAAS,IAAI;AACb,mBAAW,QAAQ,YAAA;AAAA,MACrB;AAAA,MACA,cAAc,MAAM;AAClB,mBAAW,QAAQ,eAAA;AAAA,MACrB;AAAA,MACA,eAAe,MAAM;AACnB,sCAA8B,IAAI;AAClC,mBAAW,QAAQ,gBAAA;AAAA,MACrB;AAAA,IAAA,CACD;AAGD,cAAU,QAAQ,cAAc,CAAC,UAAU;AACzC,+BAAyB,MAAM,qBAAqB;AACpD,oCAA8B,MAAM,0BAA0B;AAAA,IAChE,CAAC;AAAA,EACH;AAEA,QAAM,SAAS,UAAU;AAGzB,YAAU,MAAM;AACd,aAAS,eAAe;AACtB,UAAI,UAAU,SAAS,OAAO;AAC5B,sBAAc,UAAU,QAAQ,MAAM,UAAU;AAChD,uBAAe,UAAU,QAAQ,MAAM,WAAW;AAAA,MACpD;AACA,wBAAkB,UAAU,sBAAsB,YAAY;AAAA,IAChE;AAEA,QAAI,WAAW,aAAa;AAC1B,mBAAA;AAAA,IACF;AAEA,WAAO,MAAM;AACX,UAAI,kBAAkB,SAAS;AAC7B,6BAAqB,kBAAkB,OAAO;AAC9C,0BAAkB,UAAU;AAAA,MAC9B;AAAA,IACF;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AAGX,YAAU,MAAM;AACd,WAAO,MAAM;AACX,gBAAU,SAAS,QAAA;AAAA,IACrB;AAAA,EACF,GAAG,CAAA,CAAE;AAGL,QAAM,UAAU,YAAY,YAAY;AACtC,aAAS,IAAI;AACb,gBAAY,CAAA,CAAE;AACd,6BAAyB,IAAI;AAC7B,kCAA8B,IAAI;AAClC,UAAM,OAAO,QAAA;AAAA,EACf,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,aAAa,YAAY,YAAY;AACzC,UAAM,OAAO,WAAA;AAAA,EACf,GAAG,CAAC,MAAM,CAAC;AAGX,QAAM,iBAAiB,YAAY,MAAM;AACvC,WAAO,eAAA;AAAA,EACT,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,gBAAgB,YAAY,MAAM;AACtC,WAAO,cAAA;AAAA,EACT,GAAG,CAAC,MAAM,CAAC;AAEX,QAAM,YAAY,YAAY,MAAM;AAClC,WAAO,UAAA;AAAA,EACT,GAAG,CAAC,MAAM,CAAC;AAGX,QAAM,WAAW;AAAA,IACf,CAAC,SAAiB;AAChB,aAAO,SAAS,IAAI;AAAA,IACtB;AAAA,IACA,CAAC,MAAM;AAAA,EAAA;AAIT,QAAM,YAAY;AAAA,IAChB,CAAC,WAAmB,aAAqB;AACvC,aAAO,UAAU,WAAW,QAAQ;AAAA,IACtC;AAAA,IACA,CAAC,MAAM;AAAA,EAAA;AAIT,QAAM,wBAAwB,YAAY,MAAM;AAC9C,WACE,UAAU,SAAS,OAAO,sBAAA,KAA2B;AAAA,EAEzD,GAAG,CAAA,CAAE;AAEL,QAAM,yBAAyB,YAAY,MAAM;AAC/C,WACE,UAAU,SAAS,OAAO,uBAAA,KAA4B;AAAA,EAE1D,GAAG,CAAA,CAAE;AAEL,QAAM,yBAAyB,YAAY,MAAM;AAC/C,WACE,UAAU,SAAS,OAAO,uBAAA,KAA4B;AAAA,EAE1D,GAAG,CAAA,CAAE;AAEL,QAAM,0BAA0B,YAAY,MAAM;AAChD,WACE,UAAU,SAAS,OAAO,wBAAA,KAA6B;AAAA,EAE3D,GAAG,CAAA,CAAE;AAGL,QAAM,aAAa;AAAA,IACjB,CAAC,YAA8C;AAC7C,sBAAgB,OAAO;AAAA,IAEzB;AAAA,IACA,CAAA;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;"}
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import { StreamChunk, SummarizationResult } from '@tanstack/ai';
|
|
2
|
-
import {
|
|
2
|
+
import { ConnectConnectionAdapter, GenerationClientState, GenerationFetcher, InferGenerationOutput, SummarizeGenerateInput } from '@tanstack/ai-client';
|
|
3
3
|
/**
|
|
4
4
|
* Options for the useSummarize hook.
|
|
5
5
|
*
|
|
6
6
|
* @template TOutput - The output type after optional transform (defaults to SummarizationResult)
|
|
7
7
|
*/
|
|
8
8
|
export interface UseSummarizeOptions<TOutput = SummarizationResult> {
|
|
9
|
-
/**
|
|
10
|
-
connection?:
|
|
9
|
+
/** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */
|
|
10
|
+
connection?: ConnectConnectionAdapter;
|
|
11
11
|
/** Direct async function for summarization */
|
|
12
12
|
fetcher?: GenerationFetcher<SummarizeGenerateInput, SummarizationResult>;
|
|
13
13
|
/** Unique identifier for this generation instance */
|
|
14
14
|
id?: string;
|
|
15
|
-
/** Additional body parameters to send with
|
|
15
|
+
/** Additional body parameters to send with connect-based adapter requests */
|
|
16
16
|
body?: Record<string, any>;
|
|
17
17
|
/**
|
|
18
18
|
* Callback when summarization is complete. Can optionally return a transformed value.
|
|
@@ -26,7 +26,7 @@ export interface UseSummarizeOptions<TOutput = SummarizationResult> {
|
|
|
26
26
|
onError?: (error: Error) => void;
|
|
27
27
|
/** Callback when progress is reported (0-100) */
|
|
28
28
|
onProgress?: (progress: number, message?: string) => void;
|
|
29
|
-
/** Callback for each stream chunk (
|
|
29
|
+
/** Callback for each stream chunk (connect-based adapter mode only) */
|
|
30
30
|
onChunk?: (chunk: StreamChunk) => void;
|
|
31
31
|
}
|
|
32
32
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-summarize.js","sources":["../../src/use-summarize.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport type { StreamChunk, SummarizationResult } from '@tanstack/ai'\nimport type {\n
|
|
1
|
+
{"version":3,"file":"use-summarize.js","sources":["../../src/use-summarize.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport type { StreamChunk, SummarizationResult } from '@tanstack/ai'\nimport type {\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutput,\n SummarizeGenerateInput,\n} from '@tanstack/ai-client'\n\n/**\n * Options for the useSummarize hook.\n *\n * @template TOutput - The output type after optional transform (defaults to SummarizationResult)\n */\nexport interface UseSummarizeOptions<TOutput = SummarizationResult> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for summarization */\n fetcher?: GenerationFetcher<SummarizeGenerateInput, SummarizationResult>\n /** Unique identifier for this generation instance */\n id?: string\n /** Additional body parameters to send with connect-based adapter requests */\n body?: Record<string, any>\n /**\n * Callback when summarization is complete. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: SummarizationResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n}\n\n/**\n * Return type for the useSummarize hook.\n *\n * @template TOutput - The output type (after optional transform)\n */\nexport interface UseSummarizeReturn<TOutput = SummarizationResult> {\n /** Trigger summarization */\n generate: (input: SummarizeGenerateInput) => Promise<void>\n /** The summarization result, or null */\n result: TOutput | null\n /** Whether summarization is in progress */\n isLoading: boolean\n /** Current error, if any */\n error: Error | undefined\n /** Current state of the generation */\n status: GenerationClientState\n /** Abort the current summarization */\n stop: () => void\n /** Clear result, error, and return to idle */\n reset: () => void\n}\n\n/**\n * React hook for summarizing text using AI models.\n *\n * @example\n * ```tsx\n * import { useSummarize } from '@tanstack/ai-react'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function Summarizer() {\n * const { generate, result, isLoading } = useSummarize({\n * connection: fetchServerSentEvents('/api/summarize'),\n * })\n *\n * return (\n * <div>\n * <button onClick={() => generate({\n * text: 'Long article text...',\n * style: 'bullet-points',\n * maxLength: 200,\n * })}>\n * Summarize\n * </button>\n * {isLoading && <p>Summarizing...</p>}\n * {result && <p>{result.summary}</p>}\n * </div>\n * )\n * }\n * ```\n */\nexport function useSummarize<\n TOnResult extends ((result: SummarizationResult) => any) | undefined =\n undefined,\n>(\n options: Omit<UseSummarizeOptions, 'onResult'> & {\n onResult?: TOnResult\n },\n): UseSummarizeReturn<InferGenerationOutput<SummarizationResult, TOnResult>> {\n const { generate, result, isLoading, error, status, stop, reset } =\n useGeneration<SummarizeGenerateInput, SummarizationResult, TOnResult>(\n options,\n )\n\n return {\n generate: generate as (input: SummarizeGenerateInput) => Promise<void>,\n result,\n isLoading,\n error,\n status,\n stop,\n reset,\n }\n}\n"],"names":[],"mappings":";AA2FO,SAAS,aAId,SAG2E;AAC3E,QAAM,EAAE,UAAU,QAAQ,WAAW,OAAO,QAAQ,MAAM,UACxD;AAAA,IACE;AAAA,EAAA;AAGJ,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
import { StreamChunk, TranscriptionResult } from '@tanstack/ai';
|
|
2
|
-
import {
|
|
2
|
+
import { ConnectConnectionAdapter, GenerationClientState, GenerationFetcher, InferGenerationOutput, TranscriptionGenerateInput } from '@tanstack/ai-client';
|
|
3
3
|
/**
|
|
4
4
|
* Options for the useTranscription hook.
|
|
5
5
|
*
|
|
6
6
|
* @template TOutput - The output type after optional transform (defaults to TranscriptionResult)
|
|
7
7
|
*/
|
|
8
8
|
export interface UseTranscriptionOptions<TOutput = TranscriptionResult> {
|
|
9
|
-
/**
|
|
10
|
-
connection?:
|
|
9
|
+
/** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */
|
|
10
|
+
connection?: ConnectConnectionAdapter;
|
|
11
11
|
/** Direct async function for transcription */
|
|
12
12
|
fetcher?: GenerationFetcher<TranscriptionGenerateInput, TranscriptionResult>;
|
|
13
13
|
/** Unique identifier for this generation instance */
|
|
14
14
|
id?: string;
|
|
15
|
-
/** Additional body parameters to send with
|
|
15
|
+
/** Additional body parameters to send with connect-based adapter requests */
|
|
16
16
|
body?: Record<string, any>;
|
|
17
17
|
/**
|
|
18
18
|
* Callback when transcription is complete. Can optionally return a transformed value.
|
|
@@ -26,7 +26,7 @@ export interface UseTranscriptionOptions<TOutput = TranscriptionResult> {
|
|
|
26
26
|
onError?: (error: Error) => void;
|
|
27
27
|
/** Callback when progress is reported (0-100) */
|
|
28
28
|
onProgress?: (progress: number, message?: string) => void;
|
|
29
|
-
/** Callback for each stream chunk (
|
|
29
|
+
/** Callback for each stream chunk (connect-based adapter mode only) */
|
|
30
30
|
onChunk?: (chunk: StreamChunk) => void;
|
|
31
31
|
}
|
|
32
32
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-transcription.js","sources":["../../src/use-transcription.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport type { StreamChunk, TranscriptionResult } from '@tanstack/ai'\nimport type {\n
|
|
1
|
+
{"version":3,"file":"use-transcription.js","sources":["../../src/use-transcription.ts"],"sourcesContent":["import { useGeneration } from './use-generation'\nimport type { StreamChunk, TranscriptionResult } from '@tanstack/ai'\nimport type {\n ConnectConnectionAdapter,\n GenerationClientState,\n GenerationFetcher,\n InferGenerationOutput,\n TranscriptionGenerateInput,\n} from '@tanstack/ai-client'\n\n/**\n * Options for the useTranscription hook.\n *\n * @template TOutput - The output type after optional transform (defaults to TranscriptionResult)\n */\nexport interface UseTranscriptionOptions<TOutput = TranscriptionResult> {\n /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */\n connection?: ConnectConnectionAdapter\n /** Direct async function for transcription */\n fetcher?: GenerationFetcher<TranscriptionGenerateInput, TranscriptionResult>\n /** Unique identifier for this generation instance */\n id?: string\n /** Additional body parameters to send with connect-based adapter requests */\n body?: Record<string, any>\n /**\n * Callback when transcription is complete. Can optionally return a transformed value.\n *\n * - Return a non-null value to transform and store it as the result\n * - Return `null` to keep the previous result unchanged\n * - Return nothing (`void`) to store the raw result as-is\n */\n onResult?: (result: TranscriptionResult) => TOutput | null | void\n /** Callback when an error occurs */\n onError?: (error: Error) => void\n /** Callback when progress is reported (0-100) */\n onProgress?: (progress: number, message?: string) => void\n /** Callback for each stream chunk (connect-based adapter mode only) */\n onChunk?: (chunk: StreamChunk) => void\n}\n\n/**\n * Return type for the useTranscription hook.\n *\n * @template TOutput - The output type (after optional transform)\n */\nexport interface UseTranscriptionReturn<TOutput = TranscriptionResult> {\n /** Trigger transcription */\n generate: (input: TranscriptionGenerateInput) => Promise<void>\n /** The transcription result, or null */\n result: TOutput | null\n /** Whether transcription is in progress */\n isLoading: boolean\n /** Current error, if any */\n error: Error | undefined\n /** Current state of the generation */\n status: GenerationClientState\n /** Abort the current transcription */\n stop: () => void\n /** Clear result, error, and return to idle */\n reset: () => void\n}\n\n/**\n * React hook for transcribing audio to text using AI models.\n *\n * @example\n * ```tsx\n * import { useTranscription } from '@tanstack/ai-react'\n * import { fetchServerSentEvents } from '@tanstack/ai-client'\n *\n * function Transcriber() {\n * const { generate, result, isLoading } = useTranscription({\n * connection: fetchServerSentEvents('/api/transcribe'),\n * })\n *\n * const handleFile = (e: React.ChangeEvent<HTMLInputElement>) => {\n * const file = e.target.files?.[0]\n * if (file) {\n * const reader = new FileReader()\n * reader.onload = () => {\n * generate({ audio: reader.result as string, language: 'en' })\n * }\n * reader.readAsDataURL(file)\n * }\n * }\n *\n * return (\n * <div>\n * <input type=\"file\" accept=\"audio/*\" onChange={handleFile} />\n * {isLoading && <p>Transcribing...</p>}\n * {result && <p>{result.text}</p>}\n * </div>\n * )\n * }\n * ```\n */\nexport function useTranscription<\n TOnResult extends ((result: TranscriptionResult) => any) | undefined =\n undefined,\n>(\n options: Omit<UseTranscriptionOptions, 'onResult'> & {\n onResult?: TOnResult\n },\n): UseTranscriptionReturn<\n InferGenerationOutput<TranscriptionResult, TOnResult>\n> {\n const { generate, result, isLoading, error, status, stop, reset } =\n useGeneration<TranscriptionGenerateInput, TranscriptionResult, TOnResult>(\n options,\n )\n\n return {\n generate: generate as (input: TranscriptionGenerateInput) => Promise<void>,\n result,\n isLoading,\n error,\n status,\n stop,\n reset,\n }\n}\n"],"names":[],"mappings":";AAgGO,SAAS,iBAId,SAKA;AACA,QAAM,EAAE,UAAU,QAAQ,WAAW,OAAO,QAAQ,MAAM,UACxD;AAAA,IACE;AAAA,EAAA;AAGJ,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAEJ;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/ai-react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.2",
|
|
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.
|
|
34
|
+
"@tanstack/ai-client": "0.7.2"
|
|
35
35
|
},
|
|
36
36
|
"peerDependencies": {
|
|
37
37
|
"@types/react": ">=18.0.0",
|
|
38
38
|
"react": ">=18.0.0",
|
|
39
|
-
"@tanstack/ai": "^0.
|
|
39
|
+
"@tanstack/ai": "^0.8.1"
|
|
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.
|
|
48
|
+
"@tanstack/ai": "0.8.1"
|
|
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
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type {
|
|
|
3
3
|
ChatClientOptions,
|
|
4
4
|
ChatClientState,
|
|
5
5
|
ChatRequestBody,
|
|
6
|
+
ConnectionStatus,
|
|
6
7
|
MultimodalContent,
|
|
7
8
|
UIMessage,
|
|
8
9
|
} from '@tanstack/ai-client'
|
|
@@ -29,8 +30,20 @@ export type { ChatRequestBody, MultimodalContent, UIMessage }
|
|
|
29
30
|
export type UseChatOptions<TTools extends ReadonlyArray<AnyClientTool> = any> =
|
|
30
31
|
Omit<
|
|
31
32
|
ChatClientOptions<TTools>,
|
|
32
|
-
|
|
33
|
-
|
|
33
|
+
| 'onMessagesChange'
|
|
34
|
+
| 'onLoadingChange'
|
|
35
|
+
| 'onErrorChange'
|
|
36
|
+
| 'onStatusChange'
|
|
37
|
+
| 'onSubscriptionChange'
|
|
38
|
+
| 'onConnectionStatusChange'
|
|
39
|
+
| 'onSessionGeneratingChange'
|
|
40
|
+
> & {
|
|
41
|
+
/**
|
|
42
|
+
* Opt into mount-time live subscription behavior.
|
|
43
|
+
* When enabled, the hook subscribes on mount and unsubscribes on unmount.
|
|
44
|
+
*/
|
|
45
|
+
live?: boolean
|
|
46
|
+
}
|
|
34
47
|
|
|
35
48
|
export interface UseChatReturn<
|
|
36
49
|
TTools extends ReadonlyArray<AnyClientTool> = any,
|
|
@@ -95,6 +108,24 @@ export interface UseChatReturn<
|
|
|
95
108
|
*/
|
|
96
109
|
status: ChatClientState
|
|
97
110
|
|
|
111
|
+
/**
|
|
112
|
+
* Whether the subscription loop is currently active
|
|
113
|
+
*/
|
|
114
|
+
isSubscribed: boolean
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Current connection lifecycle status
|
|
118
|
+
*/
|
|
119
|
+
connectionStatus: ConnectionStatus
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Whether the shared session is actively generating.
|
|
123
|
+
* Derived from stream run events (RUN_STARTED / RUN_FINISHED / RUN_ERROR).
|
|
124
|
+
* Unlike `isLoading` (request-local), this reflects shared generation
|
|
125
|
+
* activity visible to all subscribers (e.g. across tabs/devices).
|
|
126
|
+
*/
|
|
127
|
+
sessionGenerating: boolean
|
|
128
|
+
|
|
98
129
|
/**
|
|
99
130
|
* Set messages manually
|
|
100
131
|
*/
|