Open History to see the last commit
1import { useChat as useUnboundChat } from './use-chat'
2import type { AnyClientTool, InterruptDefinition } from '@tanstack/ai/client'
3import type {
4 DistributedOmit,
5 InferredClientContext,
6} from '@tanstack/ai-client'
7import type { UseChatOptions } from './types'
8
9type ChatHookOverrides<
10 TTools extends ReadonlyArray<AnyClientTool>,
11 TContext,
12 TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>>,
13> = {
14 threadId: string
15 live?: boolean
16 forwardedProps?: Record<string, any>
17 initialMessages?: UseChatOptions<
18 TTools,
19 TContext,
20 TInterrupts
21 >['initialMessages']
22}
23
24/**
25 * Bind chat options once at module scope. The returned `useChat` hook
26 * creates a chat instance from those options.
27 *
28 * Pass `threadId` on every call. You can also override `initialMessages`,
29 * `live`, and `forwardedProps` per call. Do not change `tools`,
30 * `interrupts`, or `outputSchema` here. Those stay on the factory options.
31 */
32export function createChatHook<
33 const TTools extends ReadonlyArray<AnyClientTool> = any,
34 TContext = InferredClientContext<TTools>,
35 const TInterrupts extends ReadonlyArray<
36 InterruptDefinition<any, any, any, any>
37 > = readonly [],
38>(
39 options: DistributedOmit<
40 UseChatOptions<TTools, TContext, TInterrupts>,
41 'threadId'
42 > & {
43 // Plain keys so TypeScript can infer the generics through the Omit.
44 tools?: TTools
45 interrupts?: TInterrupts
46 },
47) {
48 function useChat(
49 overrides: ChatHookOverrides<TTools, TContext, TInterrupts>,
50 ) {
51 // `overrides` carries the required `threadId`.
52 return useUnboundChat({ ...options, ...overrides } as UseChatOptions<
53 TTools,
54 TContext,
55 TInterrupts
56 >)
57 }
58
59 return { useChat }
60}