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

create-chat-hook.ts

77 lines2.2 KB

1import { useChat as useUnboundChat } from './use-chat'
2import type {
3 AnyClientTool,
4 InterruptDefinition,
5 SchemaInput,
6} from '@tanstack/ai/client'
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 TSubagents extends ReadonlyArray<{ name: string }> | undefined,
16> = {
17 threadId?: string
18 live?: boolean
19 forwardedProps?: Record<string, any>
20 body?: Record<string, any>
21 initialMessages?: UseChatOptions<
22 TTools,
23 TSchema,
24 TContext,
25 TInterrupts,
26 TSubagents
27 >['initialMessages']
29​
30/**
31 * Bind chat options once at module scope. The returned `useChat` hook
32 * creates a chat instance from those options.
33 *
34 * Pass per-call overrides for instance keys such as `threadId`,
35 * `initialMessages`, `live`, and `forwardedProps`. Do not change `tools`,
36 * `interrupts`, or `outputSchema` here. Those stay on the factory options.
37 *
38 * Rename the hook at the call site if you already import `useChat` from
39 * `@tanstack/ai-react`: `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} />
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 const TSubagents extends ReadonlyArray<{ name: string }> | undefined =
59 undefined,
60>(options: UseChatOptions<TTools, TSchema, TContext, TInterrupts, TSubagents>) {
61 function useChat(
62 overrides?: ChatHookOverrides<
63 TTools,
64 TSchema,
65 TContext,
66 TInterrupts,
67 TSubagents
68 >,
69 ) {
70 if (!overrides) {
71 return useUnboundChat(options)
72 }
73 return useUnboundChat({ ...options, ...overrides })
74 }
75​
76 return { useChat }