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

create-chat-hook.ts

67 lines2.0 KB

1import { useChat as useUnboundChat } from './use-chat'
2import type {
3 AnyClientTool,
4 InterruptDefinition,
5 SchemaInput,
6} from '@tanstack/ai'
7import type { InferredClientContext } from '@tanstack/ai-client'
8import type { UseChatOptions } from './types'
9​
10type ChatHookOverrides<
11 TTools extends ReadonlyArray<AnyClientTool>,
12 TSchema extends SchemaInput | undefined,
13 TContext,
14 TInterrupts extends ReadonlyArray<InterruptDefinition<any, any, any, any>>,
15> = {
16 threadId?: string
17 live?: boolean
18 forwardedProps?: Record<string, any>
19 body?: Record<string, any>
20 initialMessages?: UseChatOptions<
21 TTools,
22 TSchema,
23 TContext,
24 TInterrupts
25 >['initialMessages']
27​
28/**
29 * Bind chat options once at module scope. The returned `useChat` primitive
30 * creates a chat instance from those options.
31 *
32 * Pass per-call overrides for instance keys such as `threadId`,
33 * `initialMessages`, `live`, and `forwardedProps`. Do not change `tools`,
34 * `interrupts`, or `outputSchema` here. Those stay on the factory options.
35 *
36 * Rename the primitive at the call site if you already import `useChat` from
37 * `@tanstack/ai-solid`: `const { useChat: useAppChat } = createChatHook(chatOptions)`.
38 *
39 * @example
40 * ```tsx
41 * const { useChat } = createChatHook(chatOptions)
42 *
43 * function Support() {
44 * const chat = useChat({ threadId: 'support-1' })
45 * return <UI.Chat chat={chat} components={components} />
46 * }
47 * ```
48 */
49export function createChatHook<
50 const TTools extends ReadonlyArray<AnyClientTool> = any,
51 TSchema extends SchemaInput | undefined = undefined,
52 TContext = InferredClientContext<TTools>,
53 const TInterrupts extends ReadonlyArray<
54 InterruptDefinition<any, any, any, any>
55 > = readonly [],
56>(options: UseChatOptions<TTools, TSchema, TContext, TInterrupts>) {
57 function useChat(
58 overrides?: ChatHookOverrides<TTools, TSchema, TContext, TInterrupts>,
59 ) {
60 if (!overrides) {
61 return useUnboundChat(options)
62 }
63 return useUnboundChat({ ...options, ...overrides })
64 }
65​
66 return { useChat }