Open History to see the last commit
1import { createContext, useContext } from 'solid-js'
2import { useChat } from '@tanstack/ai-solid'
3import type { JSX } from 'solid-js'
4import type {
5 ConnectionAdapter,
6 UIMessage,
7 UseChatReturn,
8} from '@tanstack/ai-solid'
9
10/**
11 * Chat context - provides chat state to all child components
12 */
13const ChatContext = createContext<UseChatReturn | null>(null)
14
15/**
16 * Hook to access chat context
17 * @throws Error if used outside of Chat component
18 */
19export function useChatContext(): UseChatReturn {
20 const context = useContext(ChatContext)
21 if (!context) {
22 throw new Error(
23 "Chat components must be wrapped in <Chat>. Make sure you're using Chat.Messages, Chat.Input, etc. inside a <Chat> component.",
24 )
25 }
26 return context
27}
28
29export interface ChatProps {
30 /** Child components (Chat.Messages, Chat.Input, etc.) */
31 children: JSX.Element
32 /** CSS class name for the root element */
33 class?: string
34 /** Connection adapter for communicating with your API */
35 connection: ConnectionAdapter
36 /** Initial messages to display */
37 initialMessages?: Array<UIMessage>
38 /** Custom message ID generator */
39 id?: string
40 /** Additional body data to send with requests */
41 body?: any
42 /** Callback when a response is received */
43 onResponse?: (response?: Response) => void | Promise<void>
44 /** Callback when each chunk arrives */
45 onChunk?: (chunk: any) => void
46 /** Callback when a message is complete */
47 onFinish?: (message: UIMessage) => void
48 /** Callback when an error occurs */
49 onError?: (error: Error) => void
50 /** Client-side tools with execute functions */
51 tools?: Array<any>
52 /** Custom tool components registry for rendering */
53 toolComponents?: Record<
54 string,
55 (props: { input: any; output?: any }) => JSX.Element
56 >
57}
58
59/**
60 * Root Chat component - provides context for all chat subcomponents
61 *
62 * @example
63 * ```tsx
64 * <Chat connection={fetchServerSentEvents("/api/chat")}>
65 * <Chat.Messages />
66 * <Chat.Input />
67 * </Chat>
68 * ```
69 */
70export function Chat(props: ChatProps) {
71 const chat = useChat({
72 connection: props.connection,
73 ...(props.initialMessages !== undefined && {
74 initialMessages: props.initialMessages,
75 }),
76 ...(props.id !== undefined && { id: props.id }),
77 ...(props.body !== undefined && { body: props.body }),
78 ...(props.onResponse !== undefined && { onResponse: props.onResponse }),
79 ...(props.onChunk !== undefined && { onChunk: props.onChunk }),
80 ...(props.onFinish !== undefined && { onFinish: props.onFinish }),
81 ...(props.onError !== undefined && { onError: props.onError }),
82 ...(props.tools !== undefined && { tools: props.tools }),
83 })
84
85 return (
86 <ChatContext.Provider value={chat}>
87 <div class={props.class} data-chat-root>
88 {props.children}
89 </div>
90 </ChatContext.Provider>
91 )
92}