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

chat.tsx

95 lines2.5 KB

1import { createContext, useContext } from 'react'
2import { useChat } from '@tanstack/ai-react'
3import type { ReactNode } from 'react'
4import type {
5 ConnectionAdapter,
6 UIMessage,
7 UseChatReturn,
8} from '@tanstack/ai-react'
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() {
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
28​
29export interface ChatProps {
30 /** Child components (Chat.Messages, Chat.Input, etc.) */
31 children: ReactNode
32 /** CSS class name for the root element */
33 className?: 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 /** Custom tool components registry */
51 tools?: Record<string, React.ComponentType<{ input: any; output?: any }>>
53​
54/**
55 * Root Chat component - provides context for all chat subcomponents
56 *
57 * @example
58 * ```tsx
59 * <Chat connection={fetchServerSentEvents("/api/chat")}>
60 * <Chat.Messages />
61 * <Chat.Input />
62 * </Chat>
63 * ```
64 */
65export function Chat({
66 children,
67 className,
68 connection,
69 initialMessages,
70 id,
71 body,
72 onResponse,
73 onChunk,
74 onFinish,
75 onError,
76}: ChatProps) {
77 const chat = useChat({
78 connection,
79 ...(initialMessages !== undefined ? { initialMessages } : {}),
80 ...(id !== undefined ? { id } : {}),
81 ...(body !== undefined ? { body } : {}),
82 ...(onResponse !== undefined ? { onResponse } : {}),
83 ...(onChunk !== undefined ? { onChunk } : {}),
84 ...(onFinish !== undefined ? { onFinish } : {}),
85 ...(onError !== undefined ? { onError } : {}),
86 })
87​
88 return (
89 <ChatContext.Provider value={chat}>
90 <div className={className} data-chat-root>
91 {children}
92 </div>
93 </ChatContext.Provider>
94 )