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/client'
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 TSubagents extends ReadonlyArray<{ name: string }> | undefined,
19> = {
20 threadId: string
21 live?: boolean
22 forwardedProps?: Record<string, any>
23 initialMessages?: UseChatOptions<
24 TTools,
25 TSchema,
26 TContext,
27 TInterrupts,
28 TSubagents
29 >['initialMessages']
30}
31
32/**
33 * Bind chat options once at module scope. The returned `useChat` hook
34 * creates a chat instance from those options.
35 *
36 * Pass `threadId` on every call. You can also override `initialMessages`,
37 * `live`, and `forwardedProps` per call. Do not change `tools`,
38 * `interrupts`, or `outputSchema` here. Those stay on the factory options.
39 *
40 * Rename the hook at the call site if you already import `useChat` from
41 * `@tanstack/ai-react`: `const { useChat: useAppChat } = createChatHook(chatOptions)`.
42 *
43 * @example
44 * ```tsx
45 * const { useChat } = createChatHook(chatOptions)
46 *
47 * function Support() {
48 * const chat = useChat({ threadId: 'support-1' })
49 * return <UI.Chat chat={chat} />
50 * }
51 * ```
52 */
53export function createChatHook<
54 const TTools extends ReadonlyArray<AnyClientTool> = any,
55 TSchema extends SchemaInput | undefined = undefined,
56 TContext = InferredClientContext<TTools>,
57 const TInterrupts extends ReadonlyArray<
58 InterruptDefinition<any, any, any, any>
59 > = readonly [],
60 const TSubagents extends ReadonlyArray<{ name: string }> | undefined =
61 undefined,
62>(
63 options: DistributedOmit<
64 UseChatOptions<TTools, TSchema, TContext, TInterrupts, TSubagents>,
65 'threadId'
66 > & {
67 // Plain keys so TypeScript can infer the generics through the Omit.
68 tools?: TTools
69 outputSchema?: TSchema
70 interrupts?: TInterrupts
71 subagents?: TSubagents
72 },
73) {
74 function useChat(
75 overrides: ChatHookOverrides<
76 TTools,
77 TSchema,
78 TContext,
79 TInterrupts,
80 TSubagents
81 >,
82 ) {
83 // `overrides` carries the required `threadId`.
84 return useUnboundChat({ ...options, ...overrides } as UseChatOptions<
85 TTools,
86 TSchema,
87 TContext,
88 TInterrupts,
89 TSubagents
90 >)
91 }
92
93 return { useChat }
94}