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

create-chat-hook.ts

82 lines2.3 KB

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']
29​
30/**
31 * Bind chat options once at module scope. The returned `useChat` primitive
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 primitive at the call site if you already import `useChat` from
39 * `@tanstack/ai-solid`: `const { useChat: useAppChat } = createChatHook(chatOptions)`.
40 *
41 * @example
42 * ```tsx
43 * const { useChat } = createChatHook(chatOptions)
44 *
45 * function Support() {
46 * const chat = useChat({ threadId: 'support-1' })
47 * return <UI.Chat chat={chat} components={components} />
48 * }
49 * ```
50 */
51export function createChatHook<
52 const TTools extends ReadonlyArray<AnyClientTool> = any,
53 TSchema extends SchemaInput | undefined = undefined,
54 TContext = InferredClientContext<TTools>,
55 const TInterrupts extends ReadonlyArray<
56 InterruptDefinition<any, any, any, any>
57 > = readonly [],
58>(
59 options: DistributedOmit<
60 UseChatOptions<TTools, TSchema, TContext, TInterrupts>,
61 'threadId'
62 > & {
63 // Plain keys so TypeScript can infer the generics through the Omit.
64 tools?: TTools
65 outputSchema?: TSchema
66 interrupts?: TInterrupts
67 },
68) {
69 function useChat(
70 overrides: ChatHookOverrides<TTools, TSchema, TContext, TInterrupts>,
71 ) {
72 // `overrides` carries the required `threadId`.
73 return useUnboundChat({ ...options, ...overrides } as UseChatOptions<
74 TTools,
75 TSchema,
76 TContext,
77 TInterrupts
78 >)
79 }
80​
81 return { useChat }