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