UNPKG

@llamaindex/ui

Version:

A comprehensive UI component library built with React, TypeScript, and Tailwind CSS for LlamaIndex applications

607 lines (568 loc) 21.7 kB
import * as react_jsx_runtime from 'react/jsx-runtime'; import { c as JSONValue } from '../json-types-CmrC0JAm.js'; import { F as FileType } from '../file-utils-CUHxYCcA.js'; import * as React$1 from 'react'; import { FC, ComponentType } from 'react'; import { Components } from 'react-markdown'; import { LucideIcon } from 'lucide-react'; import { c as WorkflowEvent } from '../workflow-event-CFyLs7Zw.js'; import '@llamaindex/workflows-client'; declare enum ArtifactType { Document = "document" } /** * Generic artifact type definition * @typeParam T - The type of the data payload (e.g., \{ imageUrl: string, caption: string \}) * @typeParam K - The artifact type identifier string (e.g., 'image', 'code', 'document') */ type Artifact<D = unknown, T = ArtifactType> = { created_at: number; data: D; type: T; }; type ChatEvent = { title: string; description?: string; status: "pending" | "success" | "error"; data?: any; }; declare function ChatEvent({ event, className, renderData, }: { event: ChatEvent; className?: string; renderData?: (data: ChatEvent["data"]) => React.ReactNode; }): react_jsx_runtime.JSX.Element; type DocumentFile = { id: string; name: string; size: number; type: string; url: string; refs?: string[]; }; type SourceNode = { id: string; metadata: Record<string, JSONValue>; score?: number; text: string; url?: string; }; type Document = { url: string; sources: SourceNode[]; }; declare function DocumentInfo({ document, className, onRemove, startIndex, }: { document: Document; className?: string; onRemove?: () => void; startIndex?: number; }): react_jsx_runtime.JSX.Element; type SourceData = { nodes: SourceNode[]; }; declare function preprocessSourceNodes(nodes: SourceNode[]): SourceNode[]; declare function ChatSources({ data, className, }: { data: SourceData; className?: string; }): react_jsx_runtime.JSX.Element | null; type SuggestedQuestionsData = string[]; declare function SuggestedQuestions({ questions, sendMessage, className, }: { questions: SuggestedQuestionsData; sendMessage: ChatContext["sendMessage"]; className?: string; }): false | react_jsx_runtime.JSX.Element; type MessagePart = TextPart | DataPart | AnyPart; declare const TextPartType: "text"; declare const ArtifactPartType: "data-artifact"; declare const EventPartType: "data-event"; declare const SourcesPartType: "data-sources"; declare const SuggestionPartType: "data-suggested_questions"; type TextPart = { type: typeof TextPartType; text: string; }; type DataPart<T extends `data-${string}` = `data-${string}`, D = any> = { id?: string; type: T; data: D; }; type ArtifactPart = DataPart<typeof ArtifactPartType, Artifact>; type EventPart = DataPart<typeof EventPartType, ChatEvent>; type SourcesPart = DataPart<typeof SourcesPartType, SourceData>; type SuggestionPart = DataPart<typeof SuggestionPartType, SuggestedQuestionsData>; type AnyPart<T extends string = any> = { id?: string; type: T; data?: any; }; declare const MessageRole: { readonly System: "system"; readonly User: "user"; readonly Assistant: "assistant"; }; type MessageRoleType = (typeof MessageRole)[keyof typeof MessageRole]; interface Message { id: string; role: MessageRoleType; parts: MessagePart[]; } type ChatRequestOptions = { headers?: Record<string, string> | Headers; }; type ChatHandler = { messages: Message[]; status: "idle" | "submitted" | "streaming" | "ready" | "error"; sendMessage: (msg: Message, opts?: ChatRequestOptions) => Promise<void>; stop?: () => Promise<void>; regenerate?: (opts?: { messageId?: string; } & ChatRequestOptions) => void; setMessages?: (messages: Message[]) => void; }; type ChatContext = ChatHandler & { input: string; setInput: (input: string) => void; isLoading: boolean; }; interface ChatSectionProps extends React.PropsWithChildren { handler: ChatHandler; className?: string; autoOpenCanvas?: boolean; } declare function ChatSection(props: ChatSectionProps): react_jsx_runtime.JSX.Element; interface CitationComponentProps { index: number; node: SourceNode; } declare function Citation({ index }: CitationComponentProps): react_jsx_runtime.JSX.Element; interface LanguageRendererProps { code: string; className?: string; } type ReactStyleMarkdownComponents = { [K in keyof Components]?: Extract<Components[K], FC<unknown>>; }; interface MarkdownProps { content: string; sources?: SourceData; backend?: string; components?: ReactStyleMarkdownComponents; citationComponent?: ComponentType<CitationComponentProps>; className?: string; languageRenderers?: Record<string, ComponentType<LanguageRendererProps>>; } declare function Markdown({ content, sources, backend, citationComponent: CitationComponent, className: customClassName, components, languageRenderers, }: MarkdownProps): react_jsx_runtime.JSX.Element; interface Props { language: string; value: string; className?: string; showHeader?: boolean; headerClassName?: string; codeClassName?: string; } interface languageMap { [key: string]: string | undefined; } declare const programmingLanguages: languageMap; declare const generateRandomString: (length: number, lowercase?: boolean) => string; declare const CodeBlock: FC<Props>; interface StarterQuestionsProps { questions: string[]; sendMessage: ChatContext["sendMessage"]; className?: string; } declare function StarterQuestions(props: StarterQuestionsProps): react_jsx_runtime.JSX.Element; declare function ImagePreview({ url, onRemove, }: { url: string; onRemove: () => void; }): react_jsx_runtime.JSX.Element; interface EventPartProps { className?: string; renderData?: (data: ChatEvent["data"]) => React.ReactNode; } /** * Render an event inside a ChatMessage, return null if current part is not event type * This component is useful to show an event from the assistant. * Normally, it will start with "Loading" status and then change to "Success" with a result * @param className - custom styles for the event */ declare function EventPartUI({ className, renderData }: EventPartProps): react_jsx_runtime.JSX.Element | null; interface ChatMarkdownProps extends React.PropsWithChildren { components?: MarkdownProps["components"]; citationComponent?: MarkdownProps["citationComponent"]; className?: string; languageRenderers?: MarkdownProps["languageRenderers"]; } /** * Render TextPart as a Markdown component. */ declare function MarkdownPartUI(props: ChatMarkdownProps): react_jsx_runtime.JSX.Element | null; /** * Render a list of sources inside a ChatMessage, return null if current part is not sources type * This component is useful to show a list of sources from the assistant. * @param className - custom styles for the sources */ declare function SourcesPartUI({ className }: { className?: string; }): react_jsx_runtime.JSX.Element | null; /** * Render a suggested questions part inside a ChatMessage, return null if current part is not suggested questions type * This component is useful to show a list of suggested questions from the assistant. * @param className - custom styles for the suggested questions */ declare function SuggestionPartUI({ className }: { className?: string; }): react_jsx_runtime.JSX.Element | null; interface ChatPartContext { part: MessagePart; } declare const chatPartContext: React$1.Context<ChatPartContext | null>; declare const ChatPartProvider: React$1.Provider<ChatPartContext | null>; declare function usePart(type: typeof TextPartType): TextPart | null; declare function usePart(type: typeof ArtifactPartType): ArtifactPart | null; declare function usePart(type: typeof EventPartType): EventPart | null; declare function usePart(type: typeof SourcesPartType): SourcesPart | null; declare function usePart(type: typeof SuggestionPartType): SuggestionPart | null; declare function usePart<T = MessagePart>(type: string): T | null; declare function getParts(message: Message, type: typeof TextPartType): TextPart[]; declare function getParts(message: Message, type: typeof ArtifactPartType): ArtifactPart[]; declare function getParts(message: Message, type: typeof EventPartType): EventPart[]; declare function getParts(message: Message, type: typeof SourcesPartType): SourcesPart[]; declare function getParts(message: Message, type: typeof SuggestionPartType): SuggestionPart[]; declare function getParts<T extends MessagePart>(message: Message, type: string): T[]; interface ChatInputProps extends React.PropsWithChildren { className?: string; resetUploadedFiles?: () => void; attachments?: MessagePart[]; } interface ChatInputFormProps extends React.PropsWithChildren { className?: string; } interface ChatInputFieldProps { className?: string; placeholder?: string; } interface ChatInputUploadProps { className?: string; onSuccess?: (files: File[]) => Promise<void> | void; allowedFileTypes?: FileType[]; maxFileSizeMB?: number; multiple?: boolean; } interface ChatInputSubmitProps extends React.PropsWithChildren { className?: string; disabled?: boolean; } declare function ChatInput(props: ChatInputProps): react_jsx_runtime.JSX.Element; declare namespace ChatInput { var Form: typeof ChatInputForm; var Field: typeof ChatInputField; var Upload: typeof ChatInputUpload; var Submit: typeof ChatInputSubmit; } declare function ChatInputForm(props: ChatInputFormProps): react_jsx_runtime.JSX.Element; declare function ChatInputField(props: ChatInputFieldProps): react_jsx_runtime.JSX.Element; declare function ChatInputUpload(props: ChatInputUploadProps): react_jsx_runtime.JSX.Element; declare function ChatInputSubmit(props: ChatInputSubmitProps): react_jsx_runtime.JSX.Element; interface ChatMessagesProps extends React.PropsWithChildren { className?: string; } interface ChatMessagesListProps extends React.PropsWithChildren { className?: string; } interface ChatMessagesLoadingProps extends React.PropsWithChildren { className?: string; } interface ChatMessagesEmptyProps extends React.PropsWithChildren { className?: string; heading?: string; subheading?: string; } interface ChatActionsProps extends React.PropsWithChildren { className?: string; } declare function ChatMessages(props: ChatMessagesProps): react_jsx_runtime.JSX.Element; declare namespace ChatMessages { var List: typeof ChatMessagesList; var Loading: typeof ChatMessagesLoading; var Empty: typeof ChatMessagesEmpty; var Actions: typeof ChatActions; } declare function ChatMessagesList(props: ChatMessagesListProps): react_jsx_runtime.JSX.Element; declare function ChatMessagesEmpty(props: ChatMessagesEmptyProps): react_jsx_runtime.JSX.Element | null; declare function ChatMessagesLoading(props: ChatMessagesLoadingProps): react_jsx_runtime.JSX.Element | null; declare function ChatActions(props: ChatActionsProps): react_jsx_runtime.JSX.Element | null; interface ChatMessageProps extends React.PropsWithChildren { message: Message; isLast: boolean; className?: string; } interface ChatMessageAvatarProps extends React.PropsWithChildren { className?: string; } interface ChatMessageContentProps extends React.PropsWithChildren { className?: string; } interface ChatMessageActionsProps extends React.PropsWithChildren { className?: string; } declare function ChatMessage(props: ChatMessageProps): react_jsx_runtime.JSX.Element; declare function ChatMessageAvatar(props: ChatMessageAvatarProps): react_jsx_runtime.JSX.Element | null; declare function ChatMessageContent(props: ChatMessageContentProps): react_jsx_runtime.JSX.Element; declare function ChatMessageActions(props: ChatMessageActionsProps): react_jsx_runtime.JSX.Element | null; type ComposibleChatMessagePart = typeof ChatMessageContent & { Event: typeof EventPartUI; Markdown: typeof MarkdownPartUI; Source: typeof SourcesPartUI; Suggestion: typeof SuggestionPartUI; }; type ComposibleChatMessage = typeof ChatMessage & { Avatar: typeof ChatMessageAvatar; Content: ComposibleChatMessagePart; Part: ComposibleChatMessagePart; Actions: typeof ChatMessageActions; }; declare const PrimiviteChatMessage: ComposibleChatMessage; interface ChatCanvasActionsProps { children?: React.ReactNode; className?: string; } declare function ChatCanvasActions(props: ChatCanvasActionsProps): react_jsx_runtime.JSX.Element; declare namespace ChatCanvasActions { var Close: typeof CanvasCloseButton; } declare function CanvasCloseButton(): react_jsx_runtime.JSX.Element; interface DocumentArtifactViewerProps { className?: string; children?: React.ReactNode; } declare function DocumentArtifactViewer({ className, children, }: DocumentArtifactViewerProps): react_jsx_runtime.JSX.Element | null; declare function ArtifactCard({ data, getTitle, iconMap, className, }: { data: Artifact; getTitle?: (data: Artifact) => string; iconMap?: Record<Artifact["type"], LucideIcon>; className?: string; }): react_jsx_runtime.JSX.Element; interface ChatCanvasProps { children?: React.ReactNode; className?: string; } declare function ChatCanvas({ children, className }: ChatCanvasProps): react_jsx_runtime.JSX.Element | null; declare namespace ChatCanvas { var DocumentArtifact: typeof DocumentArtifactViewer; var Artifact: typeof ArtifactCard; var Actions: typeof ChatCanvasActions; } declare const ChatProvider: React$1.Provider<ChatContext | null>; declare const useChatUI: () => ChatContext; interface ChatMessageContext { message: Message; isLast: boolean; } declare const ChatMessageProvider: React$1.Provider<ChatMessageContext | null>; declare const useChatMessage: () => ChatMessageContext; /** * StreamingMessage Class * Manages event accumulation and parsing for streaming messages * * Problem: * - During streaming, delta events contain partial text (e.g., "```py", "thon\n", "def ") * - Parsing each event individually breaks markdown/XML syntax detection * - Different event types (delta, tool call, etc.) should not be merged together * * Solution: * - Only merge **adjacent** delta events * - When a non-delta event arrives, flush the current text buffer * - Maintain two lists: finalized parts + current text parts * - Incrementally update for O(1) getParts() * * Example flow: * 1. delta1 + delta2 + delta3 → merged in buffer, parsed as TextPart(s) * 2. tool_call_event → flush buffer to finalized, append ToolCallPart to finalized * 3. delta4 + delta5 → merged in new buffer, parsed as TextPart(s) * 4. InputRequiredEvent → flush buffer to finalized, append InputRequiredPart to finalized * * Usage in chat-store: * - Create instance when streaming starts (with messageId) * - Call addEvent() for each incoming event (triggers incremental parse) * - Call getParts() to get current MessagePart[] (returns finalized + current) * - Call complete() when streaming ends (flushes remaining buffer) */ declare class StreamingMessage { private events; private currentTextBuffer; private currentTextParts; private finalizedParts; private _status; readonly messageId: string; constructor(messageId: string); /** * Get current status */ get status(): "streaming" | "completed"; /** * Add a new event and incrementally update the parsed result * Only adjacent delta events are merged together */ addEvent(event: WorkflowEvent): void; /** * Mark the streaming as completed and flush any remaining text */ complete(): void; /** * Get current MessagePart[] (returns finalized + current, O(1)) */ getParts(): MessagePart[]; /** * Get accumulated events (mainly for debugging) */ getEvents(): WorkflowEvent[]; /** * Get current text buffer (mainly for debugging) */ getTextBuffer(): string; /** * Clear all accumulated state */ clear(): void; /** * Flush the current text buffer (finalize adjacent delta events) * This is called when a non-delta event arrives or streaming completes */ private flushTextBuffer; } /** * Chat Store Types * Based on contracts/chat-store.contract.ts */ /** * Chat session state * * NOTE: sessionId conceptually equals handlerId * One chat session = one handler * (run_id exists in telemetry but not tracked in state) */ interface ChatSession { handlerId: string; workflowName: string; indexName?: string; messages: Message[]; status: "idle" | "submitted" | "streaming" | "ready" | "error"; error: Error | null; streamingMessage: StreamingMessage | null; } /** * Options for creating a chat session */ interface CreateSessionOptions { workflowName: string; handlerId?: string; indexName?: string; initialMessages?: Message[]; } /** * Chat store state and actions */ interface ChatStoreState { sessions: Record<string, ChatSession>; createSession(options: CreateSessionOptions): Promise<string>; deleteSession(handlerId: string): void; getSession(handlerId: string): ChatSession | undefined; sendMessage(handlerId: string, message: Message, opts?: ChatRequestOptions): Promise<void>; setMessages(handlerId: string, messages: Message[]): void; _appendMessage(handlerId: string, message: Message): void; _updateAssistantMessage(handlerId: string, messageId: string, parts: MessagePart[]): void; setStatus(handlerId: string, status: ChatSession["status"]): void; setError(handlerId: string, error: Error | null): void; stop(handlerId: string): Promise<void>; regenerate(handlerId: string, messageId?: string): Promise<void>; _setStreamingMessage(handlerId: string, streamingMessage: StreamingMessage | null): void; } /** * Chat Store Hook with Auto-Singleton Pattern * Provides both selector API and direct store access * Pattern: Similar to workflows/hooks/use-handler-store.ts */ declare function useChatStore(): ChatStoreState; declare function useChatStore<T>(selector: (state: ChatStoreState) => T): T; /** * useChat Hook - Bridge Chat UI to Workflow * Implements ChatHandler interface backed by Zustand store */ interface UseChatOptions { /** * Workflow name to use for this chat session */ workflowName: string; /** * Index name to use for this chat session */ indexName?: string; /** * Optional handler ID to reuse existing session * If not provided, a new session will be created */ handlerId?: string; /** * Optional initial messages to populate the chat */ initialMessages?: Message[]; /** * Callback when chat session is initialized and handlerId is available * - If handlerId is provided: fires on mount * - If no handlerId: fires when first message is sent (lazy initialization) */ onReady?: (handlerId: string) => void; /** * Callback on error */ onError?: (error: Error) => void; } /** * Hook to manage a chat session as a workflow * * Session initialization is eager by default - the session is created on mount. * If you provide a handlerId, the session will reuse that session when available. * * @example * ```tsx * // Lazy initialization - session created on first message * function MyChat() { * const chat = useChat({ * workflowName: "my-chat-workflow", * indexName: "my-index", * onReady: (handlerId) => { * // Called when first message is sent * console.log("Chat ready:", handlerId); * }, * }); * * return <ChatSection handler={chat} />; * } * * // Eager initialization - session created on mount * function MyResumableChat() { * const chat = useChat({ * workflowName: "my-chat-workflow", * handlerId: "existing-session-123", * indexName: "my-index", * onReady: (handlerId) => { * // Called immediately on mount * console.log("Chat ready:", handlerId); * }, * }); * * return <ChatSection handler={chat} />; * } * ``` */ declare function useChat(options: UseChatOptions): ChatHandler & { handlerId: string | null; }; interface UseCopyToClipboardProps { timeout?: number; } declare function useCopyToClipboard({ timeout, }: UseCopyToClipboardProps): { isCopied: boolean; copyToClipboard: (value: string) => void; }; export { type AnyPart, type ArtifactPart, ArtifactPartType, ChatCanvas, type ChatContext, ChatEvent, type ChatHandler, ChatInput, PrimiviteChatMessage as ChatMessage, type ChatMessageContext, ChatMessageProvider, ChatMessages, type ChatPartContext, ChatPartProvider, ChatProvider, type ChatRequestOptions, ChatSection, ChatSources, Citation, type CitationComponentProps, CodeBlock, type DataPart, type Document, type DocumentFile, DocumentInfo, type EventPart, type EventPartProps, EventPartType, EventPartUI, ImagePreview, type LanguageRendererProps, Markdown, MarkdownPartUI, type MarkdownProps, type Message, type MessagePart, MessageRole, type MessageRoleType, type SourceData, type SourceNode, type SourcesPart, SourcesPartType, SourcesPartUI, StarterQuestions, SuggestedQuestions, type SuggestedQuestionsData, type SuggestionPart, SuggestionPartType, SuggestionPartUI, type TextPart, TextPartType, type UseChatOptions, chatPartContext, generateRandomString, getParts, preprocessSourceNodes, programmingLanguages, useChat, useChatMessage, useChatStore, useChatUI, useCopyToClipboard, usePart };