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

create-chat-hook.ts

69 lines1.9 KB

1import { useChat as useUnboundChat } from './use-chat.tsrx'
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> = {
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` hook
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 */
38export function createChatHook<
39 const TTools extends ReadonlyArray<AnyClientTool> = any,
40 TSchema extends SchemaInput | undefined = undefined,
41 TContext = InferredClientContext<TTools>,
42 const TInterrupts extends ReadonlyArray<
43 InterruptDefinition<any, any, any, any>
44 > = readonly [],
45>(
46 options: DistributedOmit<
47 UseChatOptions<TTools, TSchema, TContext, TInterrupts>,
48 'threadId'
49 > & {
50 // Plain keys so TypeScript can infer the generics through the Omit.
51 tools?: TTools
52 outputSchema?: TSchema
53 interrupts?: TInterrupts
54 },
55) {
56 function useChat(
57 overrides: ChatHookOverrides<TTools, TSchema, TContext, TInterrupts>,
58 ) {
59 // `overrides` carries the required `threadId`.
60 return useUnboundChat({ ...options, ...overrides } as UseChatOptions<
61 TTools,
62 TSchema,
63 TContext,
64 TInterrupts
65 >)
66 }
67​
68 return { useChat }