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

create-chat-hook.tsx

77 lines2.1 KB

1import type { Component } from 'solid-js'
2import type { InferredClientContext } from '@tanstack/ai-client'
3import type {
4 ChatUIInterruptsOf,
5 ChatUISchemaOf,
6 ChatUIToolsOf,
7} from '@tanstack/ai-client/ui'
8import { useChat as useUnboundChat } from '../use-chat'
9import type { UseChatOptions } from '../types'
10import { createChatUI } from './create-ui'
11import type { ChatUIFactoryConfig, ChatUIHost, InputProps } from './create-ui'
12​
13type HeadlessOptions<TOptions> = UseChatOptions<
14 ChatUIToolsOf<TOptions>,
15 ChatUISchemaOf<TOptions>,
16 InferredClientContext<ChatUIToolsOf<TOptions>>,
17 ChatUIInterruptsOf<TOptions>
19​
20type ChatInstanceOverrides<TOptions> = {
21 threadId?: string
22 live?: boolean
23 forwardedProps?: Record<string, any>
24 body?: Record<string, any>
25 initialMessages?: HeadlessOptions<TOptions>['initialMessages']
27​
28/**
29 * Bind chat options and UI widgets once at module scope.
30 *
31 * This matches Form `createFormHook` and Table `createTableHook`. The
32 * returned `useAppChat` creates a chat instance. `chat.AppChat` renders it.
33 * Context `useChatContext` reads that instance. Part and interrupt
34 * widgets take `part` / `interrupt` as props.
35 *
36 * Pass instance overrides such as `threadId` into `useAppChat()`.
37 */
38export function createChatHook<
39 const TOptions,
40 TInput extends Component<any> | undefined =
41 | Component<InputProps<NoInfer<TOptions>>>
42 | undefined,
43>({
44 options,
45 ...chatComponents
46}: {
47 options: TOptions
48} & ChatUIFactoryConfig<NoInfer<TOptions>, TInput>) {
49 const ui = createChatUI(
50 options,
51 chatComponents as ChatUIFactoryConfig<NoInfer<TOptions>, TInput>,
52 )
53​
54 function useAppChat(overrides?: ChatInstanceOverrides<TOptions>) {
55 const chat = (
56 overrides
57 ? useUnboundChat({
58 ...(options as HeadlessOptions<TOptions>),
59 ...overrides,
60 })
61 : useUnboundChat(options as HeadlessOptions<TOptions>)
62 ) as ChatUIHost<TOptions>
63​
64 function AppChat() {
65 return <ui.Chat chat={chat} />
66 }
67​
68 return Object.assign(chat, { AppChat }) as ChatUIHost<TOptions> & {
69 AppChat: Component
70 }
71 }
72​
73 return {
74 useAppChat,
75 useChatContext: ui.useChatContext,
76 }