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

create-chat.ts

378 lines10.0 KB

1import { ChatClient } from '@tanstack/ai-client'
2import { createChatDevtoolsBridge } from '@tanstack/ai-client/devtools'
3import type { Handle } from 'remix/ui'
4import type {
5 ResolvableChatInterrupt,
6 ChatResumeState,
7 InferredClientContext,
8 SendMessageOptions,
9 StructuredOutputPart,
10} from '@tanstack/ai-client'
11import type {
12 AnyClientTool,
13 InterruptDefinition,
14 InferSchemaType,
15 ModelMessage,
16 RunAgentResumeItem,
17 SchemaInput,
18 StreamChunk,
19} from '@tanstack/ai/client'
20import type {
21 CreateChatOptions,
22 CreateChatReturn,
23 DeepPartial,
24 MultimodalContent,
25 UIMessage,
26} from './types.ts'
27​
28/**
29 * Create a chat helper for a Remix component.
30 *
31 * Call this in setup with the component Handle from `remix/ui`. The helper
32 * wraps ChatClient and calls `handle.update()` when the client snapshot
33 * changes, so render reads the latest frozen snapshot through getters.
34 *
35 * The default thread id is `options.threadId ?? handle.id`. Cleanup runs when
36 * `handle.signal` aborts. Do not pass identification in `options.devtools`;
37 * the helper sets `framework: 'remix'` and `hookName: 'createChat'`.
38 *
39 * @param handle Remix component handle from setup.
40 * @param options Chat client options. Pass `connection` or `fetcher`.
41 *
42 * @example
43 * ```tsx
44 * import { createChat } from '@tanstack/ai-remix'
45 * import { fetchServerSentEvents } from '@tanstack/ai-client'
46 * import type { Handle } from 'remix/ui'
47 *
48 * function Chat(handle: Handle) {
49 * const chat = createChat(handle, {
50 * connection: fetchServerSentEvents('/api/chat'),
51 * })
52 * return () => (
53 * <div>
54 * {chat.messages.map((message) => (
55 * <div>{message.role}</div>
56 * ))}
57 * <button on={{ click: () => chat.sendMessage('Hello') }}>Send</button>
58 * </div>
59 * )
60 * }
61 * ```
62 *
63 * @see {@link CreateChatReturn}
64 */
65export function createChat<
66 const TTools extends ReadonlyArray<AnyClientTool> = any,
67 TSchema extends SchemaInput | undefined = undefined,
68 TContext = InferredClientContext<TTools>,
69 const TInterrupts extends ReadonlyArray<
70 InterruptDefinition<any, any, any, any>
71 > = readonly [],
72>(
73 handle: Pick<Handle, 'id' | 'update' | 'signal'>,
74 options: CreateChatOptions<TTools, TSchema, TContext, TInterrupts>,
75) {
76 let closed = false
77​
78 type Partial = DeepPartial<InferSchemaType<NonNullable<TSchema>>>
79 type Final = InferSchemaType<NonNullable<TSchema>>
80​
81 const threadId = options.threadId ?? handle.id
82 const transport = options.connection
83 ? { connection: options.connection }
84 : { fetcher: options.fetcher }
85​
86 function commit() {
87 if (closed) return
88 void handle.update()
89 }
90​
91 const client = new ChatClient<TTools, TContext, TInterrupts>({
92 devtoolsBridgeFactory: createChatDevtoolsBridge,
93 ...transport,
94 ...(options.initialMessages !== undefined && {
95 initialMessages: options.initialMessages,
96 }),
97 ...(options.persistence === true
98 ? {
99 persistence: true,
100 threadId,
101 ...(options.history !== undefined && {
102 history: options.history,
103 }),
104 }
105 : options.persistence
106 ? {
107 persistence: options.persistence,
108 threadId,
109 }
110 : { threadId }),
111 ...(options.initialResumeSnapshot !== undefined && {
112 initialResumeSnapshot: options.initialResumeSnapshot,
113 }),
114 ...(options.body !== undefined && { body: options.body }),
115 ...(options.forwardedProps !== undefined && {
116 forwardedProps: options.forwardedProps,
117 }),
118 ...(options.byok !== undefined && { byok: options.byok }),
119 byokProvider: () => options.byokProvider?.(),
120 ...(options.context !== undefined && { context: options.context }),
121 devtools: {
122 ...options.devtools,
123 framework: 'remix',
124 hookName: 'createChat',
125 outputKind: options.outputSchema ? 'structured' : 'chat',
126 },
127 onResponse: (response) => options.onResponse?.(response),
128 onChunk: (chunk: StreamChunk) => {
129 options.onChunk?.(chunk)
130 },
131 onFinish: (message) => {
132 options.onFinish?.(message)
133 },
134 onError: (err) => {
135 options.onError?.(err)
136 },
137 ...(options.tools !== undefined && { tools: options.tools }),
138 ...(options.interrupts !== undefined && {
139 interrupts: options.interrupts,
140 }),
141 onCustomEvent: (eventType, data, context) =>
142 options.onCustomEvent?.(eventType, data, context),
143 ...(options.streamProcessor !== undefined && {
144 streamProcessor: options.streamProcessor,
145 }),
146 ...(options.queue !== undefined && { queue: options.queue }),
147 onInterruptStateChange: (nextInterruptState, context) => {
148 options.onInterruptStateChange?.(nextInterruptState, context)
149 },
150 })
151​
152 // Render reads the frozen client snapshot through the getters below.
153 const unsubscribeSnapshot = client.subscribeSnapshot(commit)
154​
155 function close() {
156 if (closed) return
157 closed = true
158 unsubscribeSnapshot()
159 client.detach()
160 if (options.live) {
161 client.unsubscribe()
162 } else {
163 client.stop()
164 }
165 client.dispose()
166 }
167​
168 if (handle.signal.aborted) {
169 close()
170 } else {
171 handle.signal.addEventListener('abort', close, { once: true })
172 if (options.live) {
173 client.subscribe()
174 }
175 client.attach()
176 client.mountDevtools()
177 }
178​
179 // Remix has no effects, so read `options.tools` before each call that can
180 // start a run. A getter such as `get tools() { return page.tools }` then
181 // sends the current tools.
182 const syncTools = () => {
183 if (options.tools !== undefined) {
184 client.updateOptions({ tools: options.tools })
185 }
186 }
187​
188 const sendMessage = async (
189 content: string | MultimodalContent,
190 sendOptions?: SendMessageOptions,
191 ) => {
192 syncTools()
193 await client.sendMessage(content, undefined, sendOptions)
194 }
195​
196 const cancelQueued = (id: string) => client.cancelQueued(id)
197​
198 const append = async (message: ModelMessage | UIMessage<TTools>) => {
199 syncTools()
200 await client.append(message)
201 }
202​
203 const reload = async () => {
204 syncTools()
205 await client.reload()
206 }
207​
208 const loadOlderMessages = async () => {
209 await client.loadOlderMessages()
210 }
211​
212 const stop = () => {
213 client.stop()
214 }
215​
216 const clear = () => {
217 client.clear()
218 }
219​
220 const setMessages = (newMessages: ReadonlyArray<UIMessage<TTools>>) => {
221 client.setMessagesManually(newMessages)
222 }
223​
224 const addToolResult = async (result: {
225 toolCallId: string
226 tool: string
227 output: any
228 state?: 'output-available' | 'output-error'
229 errorText?: string
230 }) => {
231 syncTools()
232 await client.addToolResult(result)
233 }
234​
235 /** @deprecated Use a bound `tool-approval` interrupt and `interrupt.resolveInterrupt`. */
236 const addToolApprovalResponse = async (response: {
237 id: string
238 approved: boolean
239 }) => {
240 syncTools()
241 await client.addToolApprovalResponse(response)
242 }
243​
244 const resumeInterrupts = async (
245 resumeItems: Array<RunAgentResumeItem>,
246 state?: ChatResumeState,
247 ) => {
248 syncTools()
249 return await client.resumeInterrupts(resumeItems, state)
250 }
251​
252 const resolveInterrupts = (
253 resolution:
254 | boolean
255 | ((
256 interrupt: ResolvableChatInterrupt<TTools, TInterrupts>,
257 ) => undefined),
258 ) => {
259 syncTools()
260 if (typeof resolution === 'boolean') {
261 client.resolveInterrupts(resolution)
262 } else {
263 client.resolveInterrupts(resolution)
264 }
265 }
266​
267 const cancelInterrupts = () => {
268 client.cancelInterrupts()
269 }
270​
271 const retryInterrupts = () => {
272 syncTools()
273 client.retryInterrupts()
274 }
275​
276 const resumeInterruptsUnsafe = (
277 resumeItems: Array<RunAgentResumeItem>,
278 state?: ChatResumeState,
279 ) => {
280 syncTools()
281 return client.resumeInterruptsUnsafe(resumeItems, state)
282 }
283​
284 function activeStructuredPart(): StructuredOutputPart | null {
285 const { messages } = client.getSnapshot()
286 let lastUserIndex = -1
287 for (let i = messages.length - 1; i >= 0; i--) {
288 if (messages[i]?.role === 'user') {
289 lastUserIndex = i
290 break
291 }
292 }
293 if (lastUserIndex === -1) return null
294 for (let i = messages.length - 1; i > lastUserIndex; i--) {
295 const m = messages[i]
296 if (m?.role !== 'assistant') continue
297 const part = m.parts.find(
298 (p): p is StructuredOutputPart => p.type === 'structured-output',
299 )
300 if (part) return part
301 }
302 return null
303 }
304​
305 return {
306 get messages() {
307 return client.getSnapshot().messages
308 },
309 get isLoading() {
310 return client.getSnapshot().isLoading
311 },
312 get hasOlderMessages() {
313 return client.getSnapshot().hasOlderMessages
314 },
315 get error() {
316 return client.getSnapshot().error
317 },
318 get status() {
319 return client.getSnapshot().status
320 },
321 get isSubscribed() {
322 return client.getSnapshot().isSubscribed
323 },
324 get connectionStatus() {
325 return client.getSnapshot().connectionStatus
326 },
327 get sessionGenerating() {
328 return client.getSnapshot().sessionGenerating
329 },
330 get isHydrating() {
331 return client.getSnapshot().isHydrating
332 },
333 get queue() {
334 return client.getSnapshot().queue
335 },
336 get runId() {
337 return client.getSnapshot().runId
338 },
339 get interrupts() {
340 return client.getSnapshot().interruptState.interrupts
341 },
342 get pendingInterrupts() {
343 return client.getSnapshot().interruptState.interrupts
344 },
345 get interruptErrors() {
346 return client.getSnapshot().interruptState.interruptErrors
347 },
348 get resuming() {
349 return client.getSnapshot().interruptState.resuming
350 },
351 get partial() {
352 const part = activeStructuredPart()
353 if (!part) return {} as Partial
354 const v = part.partial ?? part.data
355 return (v ?? {}) as Partial
356 },
357 get final() {
358 const part = activeStructuredPart()
359 if (!part || part.status !== 'complete') return null
360 return part.data as Final
361 },
362 sendMessage,
363 cancelQueued,
364 append,
365 reload,
366 loadOlderMessages,
367 stop,
368 setMessages,
369 clear,
370 addToolResult,
371 addToolApprovalResponse,
372 resolveInterrupts,
373 cancelInterrupts,
374 retryInterrupts,
375 resumeInterruptsUnsafe,
376 resumeInterrupts,
377 }