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 { createChat as createUnboundChat } from './create-chat.svelte'
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 { CreateChatOptions } 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?: CreateChatOptions<
23 TTools,
24 TSchema,
25 TContext,
26 TInterrupts
27 >['initialMessages']
29​
30/**
31 * Bind chat options once at module scope. The returned `createChat`
32 * function 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 function at the call site if you already import `createChat` from
39 * `@tanstack/ai-svelte`: `const { createChat: createAppChat } = createChatHook(chatOptions)`.
40 *
41 * @example
42 * ```svelte
43 * <script>
44 * import { createChatHook } from '@tanstack/ai-svelte'
45 *
46 * const { createChat } = createChatHook(chatOptions)
47 * const chat = createChat({ threadId: 'support-1' })
48 * </script>
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 CreateChatOptions<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 createChat(
70 overrides: ChatHookOverrides<TTools, TSchema, TContext, TInterrupts>,
71 ) {
72 // `overrides` carries the required `threadId`.
73 return createUnboundChat({ ...options, ...overrides } as CreateChatOptions<
74 TTools,
75 TSchema,
76 TContext,
77 TInterrupts
78 >)
79 }
80​
81 return { createChat }