diff --git a/packages/examples/package.json b/packages/examples/package.json index 76ef5fbe..550004cf 100644 --- a/packages/examples/package.json +++ b/packages/examples/package.json @@ -7,10 +7,12 @@ "./*": "./src/*.tsx" }, "dependencies": { + "@ai-sdk/react": "^2.0.87", "@icons-pack/react-simple-icons": "^13.8.0", + "@loremllm/transport": "^0.4.5", "@repo/elements": "workspace:*", "@xyflow/react": "^12.9.0", - "ai": "5.1.0-beta.22", + "ai": "5.0.87", "lucide-react": "^0.548.0", "nanoid": "^5.1.6", "react": "19.2.0", diff --git a/packages/examples/src/demo-chat-data.tsx b/packages/examples/src/demo-chat-data.tsx new file mode 100644 index 00000000..4962deb8 --- /dev/null +++ b/packages/examples/src/demo-chat-data.tsx @@ -0,0 +1,194 @@ +"use client"; + +import type { UIMessage } from "ai"; +import { + BarChartIcon, + BoxIcon, + CodeSquareIcon, + GraduationCapIcon, + NotepadTextIcon, +} from "lucide-react"; +import { nanoid } from "nanoid"; + +// Mock messages as Map of user message text -> assistant message parts +export const mockMessages = new Map([ + [ + "Can you explain how to use React hooks effectively?", + [ + { + type: "source-url", + sourceId: nanoid(), + url: "https://react.dev/reference/react", + title: "React Documentation", + }, + { + type: "source-url", + sourceId: nanoid(), + url: "https://react.dev/reference/react-dom", + title: "React DOM Documentation", + }, + { + type: "tool-mcp", + toolCallId: nanoid(), + state: "output-available", + input: { + query: "React hooks best practices", + source: "react.dev", + }, + output: `{ + "query": "React hooks best practices", + "results": [ + { + "title": "Rules of Hooks", + "url": "https://react.dev/warnings/invalid-hook-call-warning", + "snippet": "Hooks must be called at the top level of your React function components or custom hooks. Don't call hooks inside loops, conditions, or nested functions." + }, + { + "title": "useState Hook", + "url": "https://react.dev/reference/react/useState", + "snippet": "useState is a React Hook that lets you add state to your function components. It returns an array with two values: the current state and a function to update it." + }, + { + "title": "useEffect Hook", + "url": "https://react.dev/reference/react/useEffect", + "snippet": "useEffect lets you synchronize a component with external systems. It runs after render and can be used to perform side effects like data fetching." + } + ] + }`, + }, + { + type: "text", + text: `# React Hooks Best Practices + +React hooks are a powerful feature that let you use state and other React features without writing classes. Here are some tips for using them effectively: + +## Rules of Hooks + +1. **Only call hooks at the top level** of your component or custom hooks +2. **Don't call hooks inside loops, conditions, or nested functions** + +## Common Hooks + +- **useState**: For local component state +- **useEffect**: For side effects like data fetching +- **useContext**: For consuming context +- **useReducer**: For complex state logic +- **useCallback**: For memoizing functions +- **useMemo**: For memoizing values + +## Example of useState and useEffect + +\`\`\`jsx +function ProfilePage({ userId }) { + const [user, setUser] = useState(null); + + useEffect(() => { + // This runs after render and when userId changes + fetchUser(userId).then(userData => { + setUser(userData); + }); + }, [userId]); + + return user ? : ; +} +\`\`\` + +Would you like me to explain any specific hook in more detail?`, + }, + ], + ], + [ + "Yes, could you explain useCallback and useMemo in more detail? When should I use one over the other?", + [ + { + type: "reasoning", + text: `The user is asking for a detailed explanation of useCallback and useMemo. I should provide a clear and concise explanation of each hook's purpose and how they differ. + +The useCallback hook is used to memoize functions to prevent unnecessary re-renders of child components that receive functions as props. + +The useMemo hook is used to memoize values to avoid expensive recalculations on every render. + +Both hooks help with performance optimization, but they serve different purposes.`, + }, + { + type: "text", + text: `## useCallback vs useMemo + +Both hooks help with *performance optimization*, but they serve different purposes: + +### useCallback + +\`useCallback\` memoizes **functions** to prevent unnecessary re-renders of child components that receive functions as props. + +\`\`\`jsx +// Without useCallback - a new function is created on every render +const handleClick = () => { + console.log(count); +}; + +// With useCallback - the function is only recreated when dependencies change +const handleClick = useCallback(() => { + console.log(count); +}, [count]); +\`\`\` + +### useMemo + +\`useMemo\` memoizes **values** to avoid expensive recalculations on every render. + +\`\`\`jsx +// Without useMemo - expensive calculation runs on every render +const sortedList = expensiveSort(items); + +// With useMemo - calculation only runs when items change +const sortedList = useMemo(() => expensiveSort(items), [items]); +\`\`\` + +### When to use which? + +- Use **useCallback** when: + - Passing callbacks to optimized child components that rely on reference equality + - Working with event handlers that you pass to child components + +- Use **useMemo** when: + - You have computationally expensive calculations + - You want to avoid recreating objects that are used as dependencies for other hooks + +### Performance Note + +Don't overuse these hooks! They come with their own overhead. Only use them when you have identified a genuine performance issue. + +### ~~Deprecated Methods~~ + +Note that ~~class-based lifecycle methods~~ like \`componentDidMount\` are now replaced by the \`useEffect\` hook in modern React development.`, + }, + ], + ], +]); + +export const userMessageTexts = Array.from(mockMessages.keys()); + +export const suggestions = [ + { icon: BarChartIcon, text: "Analyze data", color: "#76d0eb" }, + { icon: BoxIcon, text: "Surprise me", color: "#76d0eb" }, + { icon: NotepadTextIcon, text: "Summarize text", color: "#ea8444" }, + { icon: CodeSquareIcon, text: "Code", color: "#6c71ff" }, + { icon: GraduationCapIcon, text: "Get advice", color: "#76d0eb" }, + { icon: null, text: "More" }, +]; + +export const mockResponses = [ + "That's a great question! Let me help you understand this concept better. The key thing to remember is that proper implementation requires careful consideration of the underlying principles and best practices in the field.", + "I'd be happy to explain this topic in detail. From my understanding, there are several important factors to consider when approaching this problem. Let me break it down step by step for you.", + "This is an interesting topic that comes up frequently. The solution typically involves understanding the core concepts and applying them in the right context. Here's what I recommend...", + "Great choice of topic! This is something that many developers encounter. The approach I'd suggest is to start with the fundamentals and then build up to more complex scenarios.", + "That's definitely worth exploring. From what I can see, the best way to handle this is to consider both the theoretical aspects and practical implementation details.", +]; + +export const getLastUserMessageText = (messages: UIMessage[]) => { + const lastUserMessage = [...messages] + .reverse() + .find((msg) => msg.role === "user"); + const textPart = lastUserMessage?.parts.find((p) => p.type === "text"); + return textPart && "text" in textPart ? textPart.text : ""; +}; diff --git a/packages/examples/src/demo-chatgpt.tsx b/packages/examples/src/demo-chatgpt.tsx index 01b48350..dc8fdd75 100644 --- a/packages/examples/src/demo-chatgpt.tsx +++ b/packages/examples/src/demo-chatgpt.tsx @@ -1,13 +1,7 @@ "use client"; -import { - Branch, - BranchMessages, - BranchNext, - BranchPage, - BranchPrevious, - BranchSelector, -} from "@repo/elements/branch"; +import { useChat } from "@ai-sdk/react"; +import { StaticChatTransport } from "@loremllm/transport"; import { Conversation, ConversationContent, @@ -35,6 +29,13 @@ import { SourcesTrigger, } from "@repo/elements/sources"; import { Suggestion, Suggestions } from "@repo/elements/suggestion"; +import { + Tool, + ToolContent, + ToolHeader, + ToolInput, + ToolOutput, +} from "@repo/elements/tool"; import { DropdownMenu, DropdownMenuContent, @@ -45,509 +46,76 @@ import { cn } from "@repo/shadcn-ui/lib/utils"; import type { ToolUIPart } from "ai"; import { AudioWaveformIcon, - BarChartIcon, - BoxIcon, CameraIcon, - CodeSquareIcon, FileIcon, GlobeIcon, - GraduationCapIcon, ImageIcon, - NotepadTextIcon, PaperclipIcon, ScreenShareIcon, } from "lucide-react"; -import { nanoid } from "nanoid"; -import { useCallback, useEffect, useState } from "react"; +import { useEffect, useState } from "react"; import { toast } from "sonner"; - -type MessageType = { - key: string; - from: "user" | "assistant"; - sources?: { href: string; title: string }[]; - versions: { - id: string; - content: string; - }[]; - reasoning?: { - content: string; - duration: number; - }; - tools?: { - name: string; - description: string; - status: ToolUIPart["state"]; - parameters: Record; - result: string | undefined; - error: string | undefined; - }[]; - avatar: string; - name: string; - isReasoningComplete?: boolean; - isContentComplete?: boolean; - isReasoningStreaming?: boolean; -}; - -const mockMessages: MessageType[] = [ - { - avatar: "", - key: nanoid(), - from: "user", - versions: [ - { - id: nanoid(), - content: "Can you explain how to use React hooks effectively?", - }, - ], - name: "Hayden Bleasel", - }, - { - avatar: "", - key: nanoid(), - from: "assistant", - sources: [ - { - href: "https://react.dev/reference/react", - title: "React Documentation", - }, - { - href: "https://react.dev/reference/react-dom", - title: "React DOM Documentation", - }, - ], - tools: [ - { - name: "mcp", - description: "Searching React documentation", - status: "input-available", - parameters: { - query: "React hooks best practices", - source: "react.dev", - }, - result: `{ - "query": "React hooks best practices", - "results": [ - { - "title": "Rules of Hooks", - "url": "https://react.dev/warnings/invalid-hook-call-warning", - "snippet": "Hooks must be called at the top level of your React function components or custom hooks. Don't call hooks inside loops, conditions, or nested functions." - }, - { - "title": "useState Hook", - "url": "https://react.dev/reference/react/useState", - "snippet": "useState is a React Hook that lets you add state to your function components. It returns an array with two values: the current state and a function to update it." - }, - { - "title": "useEffect Hook", - "url": "https://react.dev/reference/react/useEffect", - "snippet": "useEffect lets you synchronize a component with external systems. It runs after render and can be used to perform side effects like data fetching." - } - ] -}`, - error: undefined, - }, - ], - versions: [ - { - id: nanoid(), - content: `# React Hooks Best Practices - -React hooks are a powerful feature that let you use state and other React features without writing classes. Here are some tips for using them effectively: - -## Rules of Hooks - -1. **Only call hooks at the top level** of your component or custom hooks -2. **Don't call hooks inside loops, conditions, or nested functions** - -## Common Hooks - -- **useState**: For local component state -- **useEffect**: For side effects like data fetching -- **useContext**: For consuming context -- **useReducer**: For complex state logic -- **useCallback**: For memoizing functions -- **useMemo**: For memoizing values - -## Example of useState and useEffect - -\`\`\`jsx -function ProfilePage({ userId }) { - const [user, setUser] = useState(null); - - useEffect(() => { - // This runs after render and when userId changes - fetchUser(userId).then(userData => { - setUser(userData); - }); - }, [userId]); - - return user ? : ; -} -\`\`\` - -Would you like me to explain any specific hook in more detail?`, - }, - ], - name: "OpenAI", - }, - { - avatar: "", - key: nanoid(), - from: "user", - versions: [ - { - id: nanoid(), - content: - "Yes, could you explain useCallback and useMemo in more detail? When should I use one over the other?", - }, - { - id: nanoid(), - content: - "I'm particularly interested in understanding the performance implications of useCallback and useMemo. Could you break down when each is most appropriate?", - }, - { - id: nanoid(), - content: - "Thanks for the overview! Could you dive deeper into the specific use cases where useCallback and useMemo make the biggest difference in React applications?", - }, - ], - name: "Hayden Bleasel", - }, - { - avatar: "", - key: nanoid(), - from: "assistant", - reasoning: { - content: `The user is asking for a detailed explanation of useCallback and useMemo. I should provide a clear and concise explanation of each hook's purpose and how they differ. - -The useCallback hook is used to memoize functions to prevent unnecessary re-renders of child components that receive functions as props. - -The useMemo hook is used to memoize values to avoid expensive recalculations on every render. - -Both hooks help with performance optimization, but they serve different purposes.`, - duration: 10, - }, - versions: [ - { - id: nanoid(), - content: `## useCallback vs useMemo - -Both hooks help with *performance optimization*, but they serve different purposes: - -### useCallback - -\`useCallback\` memoizes **functions** to prevent unnecessary re-renders of child components that receive functions as props. - -\`\`\`jsx -// Without useCallback - a new function is created on every render -const handleClick = () => { - console.log(count); -}; - -// With useCallback - the function is only recreated when dependencies change -const handleClick = useCallback(() => { - console.log(count); -}, [count]); -\`\`\` - -### useMemo - -\`useMemo\` memoizes **values** to avoid expensive recalculations on every render. - -\`\`\`jsx -// Without useMemo - expensive calculation runs on every render -const sortedList = expensiveSort(items); - -// With useMemo - calculation only runs when items change -const sortedList = useMemo(() => expensiveSort(items), [items]); -\`\`\` - -### When to use which? - -- Use **useCallback** when: - - Passing callbacks to optimized child components that rely on reference equality - - Working with event handlers that you pass to child components - -- Use **useMemo** when: - - You have computationally expensive calculations - - You want to avoid recreating objects that are used as dependencies for other hooks - -### Performance Note - -Don't overuse these hooks! They come with their own overhead. Only use them when you have identified a genuine performance issue. - -### ~~Deprecated Methods~~ - -Note that ~~class-based lifecycle methods~~ like \`componentDidMount\` are now replaced by the \`useEffect\` hook in modern React development.`, - }, - ], - name: "OpenAI", - }, -]; - -const suggestions = [ - { icon: BarChartIcon, text: "Analyze data", color: "#76d0eb" }, - { icon: BoxIcon, text: "Surprise me", color: "#76d0eb" }, - { icon: NotepadTextIcon, text: "Summarize text", color: "#ea8444" }, - { icon: CodeSquareIcon, text: "Code", color: "#6c71ff" }, - { icon: GraduationCapIcon, text: "Get advice", color: "#76d0eb" }, - { icon: null, text: "More" }, -]; - -const mockResponses = [ - "That's a great question! Let me help you understand this concept better. The key thing to remember is that proper implementation requires careful consideration of the underlying principles and best practices in the field.", - "I'd be happy to explain this topic in detail. From my understanding, there are several important factors to consider when approaching this problem. Let me break it down step by step for you.", - "This is an interesting topic that comes up frequently. The solution typically involves understanding the core concepts and applying them in the right context. Here's what I recommend...", - "Great choice of topic! This is something that many developers encounter. The approach I'd suggest is to start with the fundamentals and then build up to more complex scenarios.", - "That's definitely worth exploring. From what I can see, the best way to handle this is to consider both the theoretical aspects and practical implementation details.", -]; +import { + getLastUserMessageText, + mockMessages, + mockResponses, + suggestions, + userMessageTexts, +} from "./demo-chat-data"; const Example = () => { const [text, setText] = useState(""); const [useWebSearch, setUseWebSearch] = useState(false); const [useMicrophone, setUseMicrophone] = useState(false); - const [status, setStatus] = useState< - "submitted" | "streaming" | "ready" | "error" - >("ready"); - const [messages, setMessages] = useState([]); - const [streamingMessageId, setStreamingMessageId] = useState( - null - ); - - const streamReasoning = async ( - messageKey: string, - versionId: string, - reasoningContent: string - ) => { - const words = reasoningContent.split(" "); - let currentContent = ""; - - for (let i = 0; i < words.length; i++) { - currentContent += (i > 0 ? " " : "") + words[i]; - - setMessages((prev) => - prev.map((msg) => { - if (msg.key === messageKey) { - return { - ...msg, - reasoning: msg.reasoning - ? { ...msg.reasoning, content: currentContent } - : undefined, - }; - } - return msg; - }) - ); - - await new Promise((resolve) => - setTimeout(resolve, Math.random() * 30 + 20) - ); - } - - // Mark reasoning as complete - setMessages((prev) => - prev.map((msg) => { - if (msg.key === messageKey) { - return { - ...msg, - isReasoningComplete: true, - isReasoningStreaming: false, - }; - } - return msg; - }) - ); - }; - - const streamContent = async ( - messageKey: string, - versionId: string, - content: string - ) => { - const words = content.split(" "); - let currentContent = ""; - - for (let i = 0; i < words.length; i++) { - currentContent += (i > 0 ? " " : "") + words[i]; - - setMessages((prev) => - prev.map((msg) => { - if (msg.key === messageKey) { - return { - ...msg, - versions: msg.versions.map((v) => - v.id === versionId ? { ...v, content: currentContent } : v - ), - }; - } - return msg; - }) - ); - await new Promise((resolve) => - setTimeout(resolve, Math.random() * 50 + 25) - ); - } - - // Mark content as complete - setMessages((prev) => - prev.map((msg) => { - if (msg.key === messageKey) { - return { ...msg, isContentComplete: true }; + const { messages, sendMessage } = useChat({ + id: "demo-chatgpt", + transport: new StaticChatTransport({ + chunkDelayMs: [20, 50], + async *mockResponse({ messages }) { + const lastUserMessageText = getLastUserMessageText(messages); + + // If we already have a mock response for the user message: + const assistantParts = mockMessages.get(lastUserMessageText); + if (assistantParts) { + for (const part of assistantParts) yield part; + return; } - return msg; - }) - ); - }; - - const streamResponse = useCallback( - async ( - messageKey: string, - versionId: string, - content: string, - reasoning?: { content: string; duration: number } - ) => { - setStatus("streaming"); - setStreamingMessageId(versionId); - - // First stream the reasoning if it exists - if (reasoning) { - await streamReasoning(messageKey, versionId, reasoning.content); - await new Promise((resolve) => setTimeout(resolve, 500)); // Pause between reasoning and content - } - - // Then stream the content - await streamContent(messageKey, versionId, content); - - setStatus("ready"); - setStreamingMessageId(null); - }, - [] - ); - - const streamMessage = useCallback( - async (message: MessageType) => { - if (message.from === "user") { - setMessages((prev) => [...prev, message]); - return; - } - - // Add empty assistant message with reasoning structure - const newMessage = { - ...message, - versions: message.versions.map((v) => ({ ...v, content: "" })), - reasoning: message.reasoning - ? { ...message.reasoning, content: "" } - : undefined, - isReasoningComplete: false, - isContentComplete: false, - isReasoningStreaming: !!message.reasoning, - }; - setMessages((prev) => [...prev, newMessage]); - - // Get the first version for streaming - const firstVersion = message.versions[0]; - if (!firstVersion) return; - - // Stream the response - await streamResponse( - newMessage.key, - firstVersion.id, - firstVersion.content, - message.reasoning - ); - }, - [streamResponse] - ); - - const addUserMessage = useCallback( - (content: string) => { - const userMessage: MessageType = { - key: `user-${Date.now()}`, - from: "user", - versions: [ - { - id: `user-${Date.now()}`, - content, - }, - ], - name: "User", - avatar: "", - }; - - setMessages((prev) => [...prev, userMessage]); - - setTimeout(() => { - const assistantMessageKey = `assistant-${Date.now()}`; - const assistantMessageId = `version-${Date.now()}`; + // Default response for user messages that aren't structurally defined const randomResponse = mockResponses[Math.floor(Math.random() * mockResponses.length)]; - // Create reasoning for some responses - const shouldHaveReasoning = Math.random() > 0.5; - const reasoning = shouldHaveReasoning - ? { - content: - "Let me think about this question carefully. I need to provide a comprehensive and helpful response that addresses the user's needs while being clear and concise.", - duration: 3, - } - : undefined; + if (Math.random() > 0.5) { + yield { + type: "reasoning", + text: "Let me think about this question carefully. I need to provide a comprehensive and helpful response that addresses the user's needs while being clear and concise.", + }; + } - const assistantMessage: MessageType = { - key: assistantMessageKey, - from: "assistant", - versions: [ - { - id: assistantMessageId, - content: "", - }, - ], - name: "Assistant", - avatar: "", - reasoning: reasoning ? { ...reasoning, content: "" } : undefined, - isReasoningComplete: false, - isContentComplete: false, - isReasoningStreaming: !!reasoning, + yield { + type: "text", + text: randomResponse, }; - - setMessages((prev) => [...prev, assistantMessage]); - streamResponse( - assistantMessageKey, - assistantMessageId, - randomResponse, - reasoning - ); - }, 500); + }, + }), + onFinish: ({ messages }) => { + // When finishing a message, send the next message in the list if it exists + const lastUserMessageText = getLastUserMessageText(messages); + const lastUserMessageTextIndex = userMessageTexts.indexOf(lastUserMessageText); + const nextMessageTextIndex = lastUserMessageTextIndex !== -1 ? lastUserMessageTextIndex + 1 : null; + if (nextMessageTextIndex !== null && userMessageTexts[nextMessageTextIndex]) { + sendMessage({ text: userMessageTexts[nextMessageTextIndex] }); + } }, - [streamResponse] - ); + }); + // Initialize with first user message useEffect(() => { - // Reset state on mount to ensure fresh component - setMessages([]); - - const processMessages = async () => { - for (let i = 0; i < mockMessages.length; i++) { - await streamMessage(mockMessages[i]); - - if (i < mockMessages.length - 1) { - await new Promise((resolve) => setTimeout(resolve, 1000)); - } - } - }; - - // Small delay to ensure state is reset before starting - const timer = setTimeout(() => { - processMessages(); - }, 100); - - // Cleanup function to cancel any ongoing operations - return () => { - clearTimeout(timer); - setMessages([]); - }; - }, [streamMessage]); + if (messages.length === 0 && userMessageTexts.length > 0) { + sendMessage({ text: userMessageTexts[0] }); + } + }, [messages.length, sendMessage, userMessageTexts]); const handleSubmit = (message: PromptInputMessage) => { const hasText = Boolean(message.text); @@ -557,8 +125,7 @@ const Example = () => { return; } - setStatus("submitted"); - addUserMessage(message.text || "Sent with attachments"); + sendMessage({ text: message.text || "Sent with attachments" }); setText(""); }; @@ -569,73 +136,90 @@ const Example = () => { }; const handleSuggestionClick = (suggestion: string) => { - setStatus("submitted"); - addUserMessage(suggestion); + sendMessage({ text: suggestion }); }; return (
- {messages.map(({ versions, ...message }) => ( - - - {versions.map((version) => ( - -
- {message.sources?.length && ( - - - - {message.sources.map((source) => ( - - ))} - - - )} - {message.reasoning && ( - { + const sources = message.parts.filter( + (p) => p.type === "source-url" + ); + const reasoningParts = message.parts.filter( + (p) => p.type === "reasoning" + ); + const toolParts = message.parts.filter((p) => + p.type.startsWith("tool-") + ); + const textParts = message.parts.filter((p) => p.type === "text"); + + return ( + +
+ {sources.length > 0 && ( + + + + {sources.map((source, i) => ( + + ))} + + + )} + {toolParts.map((toolPart, i) => { + if (toolPart.type.startsWith("tool-")) { + const tool = toolPart as ToolUIPart; + return ( + - - - {message.reasoning.content} - - + + + + + + + ); + } + return null; + })} + {reasoningParts.map((reasoningPart, i) => ( + + + {reasoningPart.text} + + ))} + {textParts.map((textPart, i) => ( + - {version.content} - - )} -
-
- ))} - - {versions.length > 1 && ( - - - - - - )} - - ))} + key={`${message.id}-text-${i}`} + > + {textPart.text} + + ))} +
+
+ ); + })}
diff --git a/packages/examples/src/demo-claude.tsx b/packages/examples/src/demo-claude.tsx index 67a88fe8..39a1062b 100644 --- a/packages/examples/src/demo-claude.tsx +++ b/packages/examples/src/demo-claude.tsx @@ -1,13 +1,7 @@ "use client"; -import { - Branch, - BranchMessages, - BranchNext, - BranchPage, - BranchPrevious, - BranchSelector, -} from "@repo/elements/branch"; +import { useChat } from "@ai-sdk/react"; +import { StaticChatTransport } from "@loremllm/transport"; import { Conversation, ConversationContent, @@ -40,6 +34,13 @@ import { SourcesContent, SourcesTrigger, } from "@repo/elements/sources"; +import { + Tool, + ToolContent, + ToolHeader, + ToolInput, + ToolOutput, +} from "@repo/elements/tool"; import { DropdownMenu, DropdownMenuContent, @@ -57,235 +58,14 @@ import { ScreenShareIcon, Settings2Icon, } from "lucide-react"; -import { nanoid } from "nanoid"; -import { useCallback, useEffect, useState } from "react"; +import { useEffect, useState } from "react"; import { toast } from "sonner"; - -type MessageType = { - key: string; - from: "user" | "assistant"; - sources?: { href: string; title: string }[]; - versions: { - id: string; - content: string; - }[]; - reasoning?: { - content: string; - duration: number; - }; - tools?: { - name: string; - description: string; - status: ToolUIPart["state"]; - parameters: Record; - result: string | undefined; - error: string | undefined; - }[]; - avatar: string; - name: string; - isReasoningComplete?: boolean; - isContentComplete?: boolean; - isReasoningStreaming?: boolean; -}; - -const mockMessages: MessageType[] = [ - { - key: nanoid(), - from: "user", - versions: [ - { - id: nanoid(), - content: "Can you explain how to use React hooks effectively?", - }, - ], - avatar: "https://github.com/haydenbleasel.png", - name: "Hayden Bleasel", - }, - { - key: nanoid(), - from: "assistant", - sources: [ - { - href: "https://react.dev/reference/react", - title: "React Documentation", - }, - { - href: "https://react.dev/reference/react-dom", - title: "React DOM Documentation", - }, - ], - tools: [ - { - name: "mcp", - description: "Searching React documentation", - status: "input-available", - parameters: { - query: "React hooks best practices", - source: "react.dev", - }, - result: `{ - "query": "React hooks best practices", - "results": [ - { - "title": "Rules of Hooks", - "url": "https://react.dev/warnings/invalid-hook-call-warning", - "snippet": "Hooks must be called at the top level of your React function components or custom hooks. Don't call hooks inside loops, conditions, or nested functions." - }, - { - "title": "useState Hook", - "url": "https://react.dev/reference/react/useState", - "snippet": "useState is a React Hook that lets you add state to your function components. It returns an array with two values: the current state and a function to update it." - }, - { - "title": "useEffect Hook", - "url": "https://react.dev/reference/react/useEffect", - "snippet": "useEffect lets you synchronize a component with external systems. It runs after render and can be used to perform side effects like data fetching." - } - ] -}`, - error: undefined, - }, - ], - versions: [ - { - id: nanoid(), - content: `# React Hooks Best Practices - -React hooks are a powerful feature that let you use state and other React features without writing classes. Here are some tips for using them effectively: - -## Rules of Hooks - -1. **Only call hooks at the top level** of your component or custom hooks -2. **Don't call hooks inside loops, conditions, or nested functions** - -## Common Hooks - -- **useState**: For local component state -- **useEffect**: For side effects like data fetching -- **useContext**: For consuming context -- **useReducer**: For complex state logic -- **useCallback**: For memoizing functions -- **useMemo**: For memoizing values - -## Example of useState and useEffect - -\`\`\`jsx -function ProfilePage({ userId }) { - const [user, setUser] = useState(null); - - useEffect(() => { - // This runs after render and when userId changes - fetchUser(userId).then(userData => { - setUser(userData); - }); - }, [userId]); - - return user ? : ; -} -\`\`\` - -Would you like me to explain any specific hook in more detail?`, - }, - ], - avatar: "https://github.com/openai.png", - name: "OpenAI", - }, - { - key: nanoid(), - from: "user", - versions: [ - { - id: nanoid(), - content: - "Yes, could you explain useCallback and useMemo in more detail? When should I use one over the other?", - }, - { - id: nanoid(), - content: - "I'm particularly interested in understanding the performance implications of useCallback and useMemo. Could you break down when each is most appropriate?", - }, - { - id: nanoid(), - content: - "Thanks for the overview! Could you dive deeper into the specific use cases where useCallback and useMemo make the biggest difference in React applications?", - }, - ], - avatar: "https://github.com/haydenbleasel.png", - name: "Hayden Bleasel", - }, - { - key: nanoid(), - from: "assistant", - reasoning: { - content: `The user is asking for a detailed explanation of useCallback and useMemo. I should provide a clear and concise explanation of each hook's purpose and how they differ. - -The useCallback hook is used to memoize functions to prevent unnecessary re-renders of child components that receive functions as props. - -The useMemo hook is used to memoize values to avoid expensive recalculations on every render. - -Both hooks help with performance optimization, but they serve different purposes.`, - duration: 10, - }, - versions: [ - { - id: nanoid(), - content: `## useCallback vs useMemo - -Both hooks help with _performance optimization_, but they serve different purposes: - -### useCallback - -\`useCallback\` memoizes **functions** to prevent unnecessary re-renders of child components that receive functions as props. - -\`\`\`jsx -// Without useCallback - a new function is created on every render -const handleClick = () => { - console.log(count); -}; - -// With useCallback - the function is only recreated when dependencies change -const handleClick = useCallback(() => { - console.log(count); -}, [count]); -\`\`\` - -### useMemo - -\`useMemo\` memoizes __values__ to avoid expensive recalculations on every render. - -\`\`\`jsx -// Without useMemo - expensive calculation runs on every render -const sortedList = expensiveSort(items); - -// With useMemo - calculation only runs when items change -const sortedList = useMemo(() => expensiveSort(items), [items]); -\`\`\` - -### When to use which? - -- Use **useCallback** when: - - Passing callbacks to optimized child components that rely on reference equality - - Working with event handlers that you pass to child components - -- Use **useMemo** when: - - You have computationally expensive calculations - - You want to avoid recreating objects that are used as dependencies for other hooks - -### Performance Note - -Don't overuse these hooks! They come with their own overhead. Only use them when you have identified a genuine performance issue. - -### ~~Common Mistakes~~ - -Avoid these ~~anti-patterns~~ when using hooks: -- ~~Calling hooks conditionally~~ - Always call hooks at the top level -- Using \`useEffect\` without proper dependency arrays`, - }, - ], - avatar: "https://github.com/openai.png", - name: "OpenAI", - }, -]; +import { + getLastUserMessageText, + mockMessages, + mockResponses, + userMessageTexts, +} from "./demo-chat-data"; const models = [ { id: "claude-3-opus", name: "Claude 3 Opus" }, @@ -293,261 +73,58 @@ const models = [ { id: "claude-3-haiku", name: "Claude 3 Haiku" }, ]; -const mockResponses = [ - "That's a great question! Let me help you understand this concept better. The key thing to remember is that proper implementation requires careful consideration of the underlying principles and best practices in the field.", - "I'd be happy to explain this topic in detail. From my understanding, there are several important factors to consider when approaching this problem. Let me break it down step by step for you.", - "This is an interesting topic that comes up frequently. The solution typically involves understanding the core concepts and applying them in the right context. Here's what I recommend...", - "Great choice of topic! This is something that many developers encounter. The approach I'd suggest is to start with the fundamentals and then build up to more complex scenarios.", - "That's definitely worth exploring. From what I can see, the best way to handle this is to consider both the theoretical aspects and practical implementation details.", -]; - const Example = () => { const [model, setModel] = useState(models[0].id); const [text, setText] = useState(""); - const [useWebSearch, setUseWebSearch] = useState(false); - const [useMicrophone, setUseMicrophone] = useState(false); - const [status, setStatus] = useState< - "submitted" | "streaming" | "ready" | "error" - >("ready"); - const [messages, setMessages] = useState([]); - const [streamingMessageId, setStreamingMessageId] = useState( - null - ); - - const streamReasoning = async ( - messageKey: string, - versionId: string, - reasoningContent: string - ) => { - const words = reasoningContent.split(" "); - let currentContent = ""; - for (let i = 0; i < words.length; i++) { - currentContent += (i > 0 ? " " : "") + words[i]; - - setMessages((prev) => - prev.map((msg) => { - if (msg.key === messageKey) { - return { - ...msg, - reasoning: msg.reasoning - ? { ...msg.reasoning, content: currentContent } - : undefined, - }; - } - return msg; - }) - ); - - await new Promise((resolve) => - setTimeout(resolve, Math.random() * 30 + 20) - ); - } - - // Mark reasoning as complete - setMessages((prev) => - prev.map((msg) => { - if (msg.key === messageKey) { - return { - ...msg, - isReasoningComplete: true, - isReasoningStreaming: false, - }; - } - return msg; - }) - ); - }; - - const streamContent = async ( - messageKey: string, - versionId: string, - content: string - ) => { - const words = content.split(" "); - let currentContent = ""; - - for (let i = 0; i < words.length; i++) { - currentContent += (i > 0 ? " " : "") + words[i]; - - setMessages((prev) => - prev.map((msg) => { - if (msg.key === messageKey) { - return { - ...msg, - versions: msg.versions.map((v) => - v.id === versionId ? { ...v, content: currentContent } : v - ), - }; - } - return msg; - }) - ); - - await new Promise((resolve) => - setTimeout(resolve, Math.random() * 50 + 25) - ); - } - - // Mark content as complete - setMessages((prev) => - prev.map((msg) => { - if (msg.key === messageKey) { - return { ...msg, isContentComplete: true }; + const { messages, sendMessage, status } = useChat({ + id: "demo-claude", + transport: new StaticChatTransport({ + chunkDelayMs: [20, 50], + async *mockResponse({ messages }) { + const lastUserMessageText = getLastUserMessageText(messages); + + // If we already have a mock response for the user message: + const assistantParts = mockMessages.get(lastUserMessageText); + if (assistantParts) { + for (const part of assistantParts) yield part; + return; } - return msg; - }) - ); - }; - const streamResponse = useCallback( - async ( - messageKey: string, - versionId: string, - content: string, - reasoning?: { content: string; duration: number } - ) => { - setStatus("streaming"); - setStreamingMessageId(versionId); - - // First stream the reasoning if it exists - if (reasoning) { - await streamReasoning(messageKey, versionId, reasoning.content); - await new Promise((resolve) => setTimeout(resolve, 500)); // Pause between reasoning and content - } - - // Then stream the content - await streamContent(messageKey, versionId, content); - - setStatus("ready"); - setStreamingMessageId(null); - }, - [] - ); - - const streamMessage = useCallback( - async (message: MessageType) => { - if (message.from === "user") { - setMessages((prev) => [...prev, message]); - return; - } - - // Add empty assistant message with reasoning structure - const newMessage = { - ...message, - versions: message.versions.map((v) => ({ ...v, content: "" })), - reasoning: message.reasoning - ? { ...message.reasoning, content: "" } - : undefined, - isReasoningComplete: false, - isContentComplete: false, - isReasoningStreaming: !!message.reasoning, - }; - - setMessages((prev) => [...prev, newMessage]); - - // Get the first version for streaming - const firstVersion = message.versions[0]; - if (!firstVersion) return; - - // Stream the response - await streamResponse( - newMessage.key, - firstVersion.id, - firstVersion.content, - message.reasoning - ); - }, - [streamResponse] - ); - - const addUserMessage = useCallback( - (content: string) => { - const userMessage: MessageType = { - key: `user-${Date.now()}`, - from: "user", - versions: [ - { - id: `user-${Date.now()}`, - content, - }, - ], - avatar: "https://github.com/haydenbleasel.png", - name: "User", - }; - - setMessages((prev) => [...prev, userMessage]); - - setTimeout(() => { - const assistantMessageKey = `assistant-${Date.now()}`; - const assistantMessageId = `version-${Date.now()}`; + // Default response for user messages that aren't structurally defined const randomResponse = mockResponses[Math.floor(Math.random() * mockResponses.length)]; - // Create reasoning for some responses - const shouldHaveReasoning = Math.random() > 0.5; - const reasoning = shouldHaveReasoning - ? { - content: - "Let me think about this question carefully. I need to provide a comprehensive and helpful response that addresses the user's needs while being clear and concise.", - duration: 3, - } - : undefined; + if (Math.random() > 0.5) { + yield { + type: "reasoning", + text: "Let me think about this question carefully. I need to provide a comprehensive and helpful response that addresses the user's needs while being clear and concise.", + }; + } - const assistantMessage: MessageType = { - key: assistantMessageKey, - from: "assistant", - versions: [ - { - id: assistantMessageId, - content: "", - }, - ], - avatar: "https://github.com/openai.png", - name: "Assistant", - reasoning: reasoning ? { ...reasoning, content: "" } : undefined, - isReasoningComplete: false, - isContentComplete: false, - isReasoningStreaming: !!reasoning, + yield { + type: "text", + text: randomResponse, }; - - setMessages((prev) => [...prev, assistantMessage]); - streamResponse( - assistantMessageKey, - assistantMessageId, - randomResponse, - reasoning - ); - }, 500); + }, + }), + onFinish: ({ messages }) => { + // When finishing a message, send the next message in the list if it exists + const lastUserMessageText = getLastUserMessageText(messages); + const lastUserMessageTextIndex = userMessageTexts.indexOf(lastUserMessageText); + const nextMessageTextIndex = lastUserMessageTextIndex !== -1 ? lastUserMessageTextIndex + 1 : null; + if (nextMessageTextIndex !== null && userMessageTexts[nextMessageTextIndex]) { + sendMessage({ text: userMessageTexts[nextMessageTextIndex] }); + } }, - [streamResponse] - ); + }); + // Initialize with first user message useEffect(() => { - // Reset state on mount to ensure fresh component - setMessages([]); - - const processMessages = async () => { - for (let i = 0; i < mockMessages.length; i++) { - await streamMessage(mockMessages[i]); - - if (i < mockMessages.length - 1) { - await new Promise((resolve) => setTimeout(resolve, 1000)); - } - } - }; - - // Small delay to ensure state is reset before starting - const timer = setTimeout(() => { - processMessages(); - }, 100); - - // Cleanup function to cancel any ongoing operations - return () => { - clearTimeout(timer); - setMessages([]); - }; - }, [streamMessage]); + if (messages.length === 0 && userMessageTexts.length > 0) { + sendMessage({ text: userMessageTexts[0] }); + } + }, [messages.length, sendMessage, userMessageTexts]); const handleSubmit = (message: PromptInputMessage) => { const hasText = Boolean(message.text); @@ -557,8 +134,7 @@ const Example = () => { return; } - setStatus("submitted"); - addUserMessage(message.text || "Sent with attachments"); + sendMessage({ text: message.text || "Sent with attachments" }); setText(""); }; @@ -568,92 +144,108 @@ const Example = () => { }); }; - const handleSuggestionClick = (suggestion: string) => { - setStatus("submitted"); - addUserMessage(suggestion); - }; - return (
- {messages.map(({ versions, ...message }) => ( - - - {versions.map((version) => ( - -
- {message.sources?.length && ( - - - - {message.sources.map((source) => ( - - ))} - - - )} - {message.reasoning && ( - - - - {message.reasoning.content} - - - )} - {(message.from === "user" || - message.isReasoningComplete || - !message.reasoning) && ( - { + const sources = message.parts.filter( + (p) => p.type === "source-url" + ); + const reasoningParts = message.parts.filter( + (p) => p.type === "reasoning" + ); + const toolParts = message.parts.filter((p) => + p.type.startsWith("tool-") + ); + const textParts = message.parts.filter((p) => p.type === "text"); + + return ( + +
+ {sources.length > 0 && ( + + + + {sources.map((source, i) => ( + + ))} + + + )} + {toolParts.map((toolPart, i) => { + if (toolPart.type.startsWith("tool-")) { + const tool = toolPart as ToolUIPart; + return ( + -
- {message.from === "user" && ( - - )} -
- {version.content} -
-
- + + + + + +
+ ); + } + return null; + })} + {reasoningParts.map((reasoningPart, i) => ( + + + {reasoningPart.text} + + ))} + {textParts.map((textPart, i) => ( + - - ))} - - {versions.length > 1 && ( - - - - - - )} - - ))} + key={`${message.id}-text-${i}`} + > +
+ {message.role === "user" && ( + + )} +
+ {textPart.text} +
+
+
+ ))} +
+
+ ); + })}
; - result: string | undefined; - error: string | undefined; - }[]; - avatar: string; - name: string; - isReasoningComplete?: boolean; - isContentComplete?: boolean; - isReasoningStreaming?: boolean; -}; +import { + getLastUserMessageText, + mockMessages, + mockResponses, + userMessageTexts, +} from "./demo-chat-data"; const models = [ { id: "grok-3", name: "Grok-3" }, { id: "grok-2-1212", name: "Grok-2-1212" }, ]; -const mockMessages: MessageType[] = [ - { - avatar: "", - key: nanoid(), - from: "user", - versions: [ - { - id: nanoid(), - content: "Can you explain how to use React hooks effectively?", - }, - ], - name: "Hayden Bleasel", - }, - { - avatar: "", - key: nanoid(), - from: "assistant", - sources: [ - { - href: "https://react.dev/reference/react", - title: "React Documentation", - }, - { - href: "https://react.dev/reference/react-dom", - title: "React DOM Documentation", - }, - ], - tools: [ - { - name: "mcp", - description: "Searching React documentation", - status: "input-available", - parameters: { - query: "React hooks best practices", - source: "react.dev", - }, - result: `{ - "query": "React hooks best practices", - "results": [ - { - "title": "Rules of Hooks", - "url": "https://react.dev/warnings/invalid-hook-call-warning", - "snippet": "Hooks must be called at the top level of your React function components or custom hooks. Don't call hooks inside loops, conditions, or nested functions." - }, - { - "title": "useState Hook", - "url": "https://react.dev/reference/react/useState", - "snippet": "useState is a React Hook that lets you add state to your function components. It returns an array with two values: the current state and a function to update it." - }, - { - "title": "useEffect Hook", - "url": "https://react.dev/reference/react/useEffect", - "snippet": "useEffect lets you synchronize a component with external systems. It runs after render and can be used to perform side effects like data fetching." - } - ] -}`, - error: undefined, - }, - ], - versions: [ - { - id: nanoid(), - content: `# React Hooks Best Practices - -React hooks are a powerful feature that let you use state and other React features without writing classes. Here are some tips for using them effectively: - -## Rules of Hooks - -1. **Only call hooks at the top level** of your component or custom hooks -2. **Don't call hooks inside loops, conditions, or nested functions** - -## Common Hooks - -- **useState**: For local component state -- **useEffect**: For side effects like data fetching -- **useContext**: For consuming context -- **useReducer**: For complex state logic -- **useCallback**: For memoizing functions -- **useMemo**: For memoizing values - -## Example of useState and useEffect - -\`\`\`jsx -function ProfilePage({ userId }) { - const [user, setUser] = useState(null); - - useEffect(() => { - // This runs after render and when userId changes - fetchUser(userId).then(userData => { - setUser(userData); - }); - }, [userId]); - - return user ? : ; -} -\`\`\` - -Would you like me to explain any specific hook in more detail?`, - }, - ], - name: "OpenAI", - }, - { - avatar: "", - key: nanoid(), - from: "user", - versions: [ - { - id: nanoid(), - content: - "Yes, could you explain useCallback and useMemo in more detail? When should I use one over the other?", - }, - { - id: nanoid(), - content: - "I'm particularly interested in understanding the performance implications of useCallback and useMemo. Could you break down when each is most appropriate?", - }, - { - id: nanoid(), - content: - "Thanks for the overview! Could you dive deeper into the specific use cases where useCallback and useMemo make the biggest difference in React applications?", - }, - ], - name: "Hayden Bleasel", - }, - { - avatar: "", - key: nanoid(), - from: "assistant", - reasoning: { - content: `The user is asking for a detailed explanation of useCallback and useMemo. I should provide a clear and concise explanation of each hook's purpose and how they differ. - -The useCallback hook is used to memoize functions to prevent unnecessary re-renders of child components that receive functions as props. - -The useMemo hook is used to memoize values to avoid expensive recalculations on every render. - -Both hooks help with performance optimization, but they serve different purposes.`, - duration: 10, - }, - versions: [ - { - id: nanoid(), - content: `## useCallback vs useMemo - -Both hooks help with **performance optimization**, but they serve _different purposes_: - -### useCallback - -\`useCallback\` memoizes __functions__ to prevent unnecessary re-renders of child components that receive functions as props. - -\`\`\`jsx -// Without useCallback - a new function is created on every render -const handleClick = () => { - console.log(count); -}; - -// With useCallback - the function is only recreated when dependencies change -const handleClick = useCallback(() => { - console.log(count); -}, [count]); -\`\`\` - -### useMemo - -\`useMemo\` memoizes *values* to avoid expensive recalculations on every render. - -\`\`\`jsx -// Without useMemo - expensive calculation runs on every render -const sortedList = expensiveSort(items); - -// With useMemo - calculation only runs when items change -const sortedList = useMemo(() => expensiveSort(items), [items]); -\`\`\` - -### When to use which? - -- Use **useCallback** when: - - Passing callbacks to optimized child components that rely on reference equality - - Working with event handlers that you pass to child components - -- Use **useMemo** when: - - You have computationally expensive calculations - - You want to avoid recreating objects that are used as dependencies for other hooks - -### Performance Note - -Don't overuse these hooks! They come with their own overhead. Only use them when you have identified a genuine performance issue. - -### ~~Legacy Patterns~~ - -Remember that these ~~outdated approaches~~ should be avoided: -- ~~Class components for simple state~~ - Use \`useState\` instead -- ~~Manual event listener cleanup~~ - Let \`useEffect\` handle it`, - }, - ], - name: "OpenAI", - }, -]; - -const mockResponses = [ - "That's a great question! Let me help you understand this concept better. The key thing to remember is that proper implementation requires careful consideration of the underlying principles and best practices in the field.", - "I'd be happy to explain this topic in detail. From my understanding, there are several important factors to consider when approaching this problem. Let me break it down step by step for you.", - "This is an interesting topic that comes up frequently. The solution typically involves understanding the core concepts and applying them in the right context. Here's what I recommend...", - "Great choice of topic! This is something that many developers encounter. The approach I'd suggest is to start with the fundamentals and then build up to more complex scenarios.", - "That's definitely worth exploring. From what I can see, the best way to handle this is to consider both the theoretical aspects and practical implementation details.", -]; - const Example = () => { const [model, setModel] = useState(models[0].id); const [text, setText] = useState(""); const [useWebSearch, setUseWebSearch] = useState(false); const [useMicrophone, setUseMicrophone] = useState(false); - const [status, setStatus] = useState< - "submitted" | "streaming" | "ready" | "error" - >("ready"); - const [messages, setMessages] = useState([]); - const [streamingMessageId, setStreamingMessageId] = useState( - null - ); - const streamReasoning = async ( - messageKey: string, - versionId: string, - reasoningContent: string - ) => { - const words = reasoningContent.split(" "); - let currentContent = ""; - - for (let i = 0; i < words.length; i++) { - currentContent += (i > 0 ? " " : "") + words[i]; - - setMessages((prev) => - prev.map((msg) => { - if (msg.key === messageKey) { - return { - ...msg, - reasoning: msg.reasoning - ? { ...msg.reasoning, content: currentContent } - : undefined, - }; - } - return msg; - }) - ); - - await new Promise((resolve) => - setTimeout(resolve, Math.random() * 30 + 20) - ); - } - - // Mark reasoning as complete - setMessages((prev) => - prev.map((msg) => { - if (msg.key === messageKey) { - return { - ...msg, - isReasoningComplete: true, - isReasoningStreaming: false, - }; - } - return msg; - }) - ); - }; - - const streamContent = async ( - messageKey: string, - versionId: string, - content: string - ) => { - const words = content.split(" "); - let currentContent = ""; - - for (let i = 0; i < words.length; i++) { - currentContent += (i > 0 ? " " : "") + words[i]; - - setMessages((prev) => - prev.map((msg) => { - if (msg.key === messageKey) { - return { - ...msg, - versions: msg.versions.map((v) => - v.id === versionId ? { ...v, content: currentContent } : v - ), - }; - } - return msg; - }) - ); - - await new Promise((resolve) => - setTimeout(resolve, Math.random() * 50 + 25) - ); - } - - // Mark content as complete - setMessages((prev) => - prev.map((msg) => { - if (msg.key === messageKey) { - return { ...msg, isContentComplete: true }; + const { messages, sendMessage } = useChat({ + id: "demo-grok", + transport: new StaticChatTransport({ + chunkDelayMs: [20, 50], + async *mockResponse({ messages }) { + const lastUserMessageText = getLastUserMessageText(messages); + + // If we already have a mock response for the user message: + const assistantParts = mockMessages.get(lastUserMessageText); + if (assistantParts) { + for (const part of assistantParts) yield part; + return; } - return msg; - }) - ); - }; - - const streamResponse = useCallback( - async ( - messageKey: string, - versionId: string, - content: string, - reasoning?: { content: string; duration: number } - ) => { - setStatus("streaming"); - setStreamingMessageId(versionId); - - // First stream the reasoning if it exists - if (reasoning) { - await streamReasoning(messageKey, versionId, reasoning.content); - await new Promise((resolve) => setTimeout(resolve, 500)); // Pause between reasoning and content - } - - // Then stream the content - await streamContent(messageKey, versionId, content); - - setStatus("ready"); - setStreamingMessageId(null); - }, - [] - ); - - const streamMessage = useCallback( - async (message: MessageType) => { - if (message.from === "user") { - setMessages((prev) => [...prev, message]); - return; - } - - // Add empty assistant message with reasoning structure - const newMessage = { - ...message, - versions: message.versions.map((v) => ({ ...v, content: "" })), - reasoning: message.reasoning - ? { ...message.reasoning, content: "" } - : undefined, - isReasoningComplete: false, - isContentComplete: false, - isReasoningStreaming: !!message.reasoning, - }; - - setMessages((prev) => [...prev, newMessage]); - - // Get the first version for streaming - const firstVersion = message.versions[0]; - if (!firstVersion) return; - // Stream the response - await streamResponse( - newMessage.key, - firstVersion.id, - firstVersion.content, - message.reasoning - ); - }, - [streamResponse] - ); - - const addUserMessage = useCallback( - (content: string) => { - const userMessage: MessageType = { - key: `user-${Date.now()}`, - from: "user", - versions: [ - { - id: `user-${Date.now()}`, - content, - }, - ], - avatar: "", - name: "User", - }; - - setMessages((prev) => [...prev, userMessage]); - - setTimeout(() => { - const assistantMessageKey = `assistant-${Date.now()}`; - const assistantMessageId = `version-${Date.now()}`; + // Default response for user messages that aren't structurally defined const randomResponse = mockResponses[Math.floor(Math.random() * mockResponses.length)]; - // Create reasoning for some responses - const shouldHaveReasoning = Math.random() > 0.5; - const reasoning = shouldHaveReasoning - ? { - content: - "Let me think about this question carefully. I need to provide a comprehensive and helpful response that addresses the user's needs while being clear and concise.", - duration: 3, - } - : undefined; + if (Math.random() > 0.5) { + yield { + type: "reasoning", + text: "Let me think about this question carefully. I need to provide a comprehensive and helpful response that addresses the user's needs while being clear and concise.", + }; + } - const assistantMessage: MessageType = { - key: assistantMessageKey, - from: "assistant", - versions: [ - { - id: assistantMessageId, - content: "", - }, - ], - name: "Assistant", - avatar: "", - reasoning: reasoning ? { ...reasoning, content: "" } : undefined, - isReasoningComplete: false, - isContentComplete: false, - isReasoningStreaming: !!reasoning, + yield { + type: "text", + text: randomResponse, }; - - setMessages((prev) => [...prev, assistantMessage]); - streamResponse( - assistantMessageKey, - assistantMessageId, - randomResponse, - reasoning - ); - }, 500); + }, + }), + onFinish: ({ messages }) => { + // When finishing a message, send the next message in the list if it exists + const lastUserMessageText = getLastUserMessageText(messages); + const lastUserMessageTextIndex = userMessageTexts.indexOf(lastUserMessageText); + const nextMessageTextIndex = lastUserMessageTextIndex !== -1 ? lastUserMessageTextIndex + 1 : null; + if (nextMessageTextIndex !== null && userMessageTexts[nextMessageTextIndex]) { + sendMessage({ text: userMessageTexts[nextMessageTextIndex] }); + } }, - [streamResponse] - ); + }); + // Initialize with first user message useEffect(() => { - // Reset state on mount to ensure fresh component - setMessages([]); - - const processMessages = async () => { - for (let i = 0; i < mockMessages.length; i++) { - await streamMessage(mockMessages[i]); - - if (i < mockMessages.length - 1) { - await new Promise((resolve) => setTimeout(resolve, 1000)); - } - } - }; - - // Small delay to ensure state is reset before starting - const timer = setTimeout(() => { - processMessages(); - }, 100); - - // Cleanup function to cancel any ongoing operations - return () => { - clearTimeout(timer); - setMessages([]); - }; - }, [streamMessage]); + if (messages.length === 0 && userMessageTexts.length > 0) { + sendMessage({ text: userMessageTexts[0] }); + } + }, [messages.length, sendMessage, userMessageTexts]); const handleSubmit = (message: PromptInputMessage) => { const hasText = Boolean(message.text); @@ -557,8 +136,7 @@ const Example = () => { return; } - setStatus("submitted"); - addUserMessage(message.text || "Sent with attachments"); + sendMessage({ text: message.text || "Sent with attachments" }); setText(""); }; @@ -568,74 +146,87 @@ const Example = () => { }); }; - const handleSuggestionClick = (suggestion: string) => { - setStatus("submitted"); - addUserMessage(suggestion); - }; - return (
- {messages.map(({ versions, ...message }) => ( - - - {versions.map((version) => ( - -
- {message.sources?.length && ( - - - - {message.sources.map((source) => ( - - ))} - - - )} - {message.reasoning && ( - - - - {message.reasoning.content} - - - )} - {(message.from === "user" || - message.isReasoningComplete || - !message.reasoning) && ( - { + const sources = message.parts.filter( + (p) => p.type === "source-url" + ); + const reasoningParts = message.parts.filter( + (p) => p.type === "reasoning" + ); + const toolParts = message.parts.filter((p) => + p.type.startsWith("tool-") + ); + const textParts = message.parts.filter((p) => p.type === "text"); + + return ( + +
+ {sources.length > 0 && ( + + + + {sources.map((source, i) => ( + + ))} + + + )} + {toolParts.map((toolPart, i) => { + if (toolPart.type.startsWith("tool-")) { + const tool = toolPart as ToolUIPart; + return ( + - {version.content} - + + + + + + + ); + } + return null; + })} + {reasoningParts.map((reasoningPart, i) => ( + + + {reasoningPart.text} + + ))} + {textParts.map((textPart, i) => ( + - - ))} - - {versions.length > 1 && ( - - - - - - )} - - ))} + key={`${message.id}-text-${i}`} + > + {textPart.text} + + ))} +
+
+ ); + })} diff --git a/packages/examples/src/queue.tsx b/packages/examples/src/queue.tsx index aa8b4963..8d395f74 100644 --- a/packages/examples/src/queue.tsx +++ b/packages/examples/src/queue.tsx @@ -33,13 +33,14 @@ const sampleMessages: QueueMessage[] = [ }, { id: "msg-3", - parts: [{ type: "text", text: "Update the default logo to this png." }, + parts: [ + { type: "text", text: "Update the default logo to this png." }, { - type: "file", - url: "https://github.com/haydenbleasel.png", - filename: "setup-guide.png", - mediaType: "image/png", - } + type: "file", + url: "https://github.com/haydenbleasel.png", + filename: "setup-guide.png", + mediaType: "image/png", + }, ], }, { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b37e7723..99fc4bee 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -49,7 +49,7 @@ importers: version: link:../../packages/shadcn-ui '@vercel/analytics': specifier: ^1.5.0 - version: 1.5.0(next@16.0.0(@opentelemetry/api@1.9.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(react@19.2.0) + version: 1.5.0(next@16.0.0(@babel/core@7.28.4)(@opentelemetry/api@1.9.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(react@19.2.0) '@vercel/microfrontends': specifier: ^2.1.0 version: 2.1.0(@vercel/analytics@1.5.0(next@16.0.0(@opentelemetry/api@1.9.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(react@19.2.0))(@vercel/speed-insights@1.2.0(next@16.0.0(@opentelemetry/api@1.9.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(react@19.2.0))(next@16.0.0(@opentelemetry/api@1.9.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(react-dom@19.2.0(react@19.2.0))(react@19.2.0)(vite@7.1.2(@types/node@24.9.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.1)) @@ -128,7 +128,7 @@ importers: dependencies: '@vercel/analytics': specifier: ^1.5.0 - version: 1.5.0(next@16.0.0(@opentelemetry/api@1.9.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(react@19.2.0) + version: 1.5.0(next@16.0.0(@babel/core@7.28.4)(@opentelemetry/api@1.9.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(react@19.2.0) mcp-handler: specifier: ^1.0.3 version: 1.0.3(@modelcontextprotocol/sdk@1.17.5)(next@16.0.0(@babel/core@7.28.4)(@opentelemetry/api@1.9.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0)) @@ -254,9 +254,15 @@ importers: packages/examples: dependencies: + '@ai-sdk/react': + specifier: ^2.0.87 + version: 2.0.87(react@19.2.0)(zod@4.1.12) '@icons-pack/react-simple-icons': specifier: ^13.8.0 version: 13.8.0(react@19.2.0) + '@loremllm/transport': + specifier: ^0.4.5 + version: 0.4.5(ai@5.0.87(zod@4.1.12)) '@repo/elements': specifier: workspace:* version: link:../elements @@ -264,8 +270,8 @@ importers: specifier: ^12.9.0 version: 12.9.0(@types/react@19.2.2)(immer@10.1.3)(react-dom@19.2.0(react@19.2.0))(react@19.2.0) ai: - specifier: 5.1.0-beta.22 - version: 5.1.0-beta.22(zod@4.1.12) + specifier: 5.0.87 + version: 5.0.87(zod@4.1.12) lucide-react: specifier: ^0.548.0 version: 0.548.0(react@19.2.0) @@ -380,16 +386,42 @@ packages: peerDependencies: zod: ^3.25.76 || ^4.1.8 + '@ai-sdk/gateway@2.0.6': + resolution: {integrity: sha512-FmhR6Tle09I/RUda8WSPpJ57mjPWzhiVVlB50D+k+Qf/PBW0CBtnbAUxlNSR5v+NIZNLTK3C56lhb23ntEdxhQ==} + engines: {node: '>=18'} + peerDependencies: + zod: ^3.25.76 || ^4.1.8 + + '@ai-sdk/provider-utils@3.0.16': + resolution: {integrity: sha512-lsWQY9aDXHitw7C1QRYIbVGmgwyT98TF3MfM8alNIXKpdJdi+W782Rzd9f1RyOfgRmZ08gJ2EYNDhWNK7RqpEA==} + engines: {node: '>=18'} + peerDependencies: + zod: ^3.25.76 || ^4.1.8 + '@ai-sdk/provider-utils@3.1.0-beta.7': resolution: {integrity: sha512-9D7UvfrOqvvLqIKM19hg4xnyd3+RLOzMOy0yJ5JZRg9foexNf5fLVpHSN4hy+6m3cHTUhJ02l3DfbdwKf/ww+w==} engines: {node: '>=18'} peerDependencies: zod: ^3.25.76 || ^4.1.8 + '@ai-sdk/provider@2.0.0': + resolution: {integrity: sha512-6o7Y2SeO9vFKB8lArHXehNuusnpddKPk7xqL7T2/b+OvXMRIXUO1rR4wcv1hAFUAT9avGZshty3Wlua/XA7TvA==} + engines: {node: '>=18'} + '@ai-sdk/provider@2.1.0-beta.5': resolution: {integrity: sha512-gu/aV+8iTb0IjHmFO6eDuevp4E0fbtXqSj0RcKPttgedAbWY3uMe+vVgfe/j3bfbQfN7FjGkFDLS0xIirga7pA==} engines: {node: '>=18'} + '@ai-sdk/react@2.0.87': + resolution: {integrity: sha512-uuM/FU2bT+DDQzL6YcwdQWZ5aKdT0QYsZzCNwM4jag4UQkryYJJ+CBpo2u3hZr4PaIIuL7TZzGMCzDN/UigQ9Q==} + engines: {node: '>=18'} + peerDependencies: + react: ^18 || ^19 || ^19.0.0-rc + zod: ^3.25.76 || ^4.1.8 + peerDependenciesMeta: + zod: + optional: true + '@alloc/quick-lru@5.2.0': resolution: {integrity: sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==} engines: {node: '>=10'} @@ -1122,6 +1154,11 @@ packages: '@jridgewell/trace-mapping@0.3.30': resolution: {integrity: sha512-GQ7Nw5G2lTu/BtHTKfXhKHok2WGetd4XYcVKGx00SjAk8GMwgJM3zr6zORiPGuOE+/vkc90KtTosSSvaCjKb2Q==} + '@loremllm/transport@0.4.5': + resolution: {integrity: sha512-KODYFFYCd7RcAcxxSy1fbAi0PjSSKmZWbnPELvE+l/B+Dep5EGDcwb4YUSrYqfxJLiPrMV4gtvk6RrmAVnaFOw==} + peerDependencies: + ai: ^5.x.x + '@manypkg/find-root@1.1.0': resolution: {integrity: sha512-mki5uBvhHzO8kYYix/WRy2WX8S3B5wdVSc9D6KcU5lQNglP2yt58/VfLuAK49glRXChosY8ap2oJ1qgma3GUVA==} @@ -2633,6 +2670,12 @@ packages: resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==} engines: {node: '>= 14'} + ai@5.0.87: + resolution: {integrity: sha512-9Cjx7o8IY9zAczigX0Tk/BaQwjPe/M6DpEjejKSBNrf8mOPIvyM+pJLqJSC10IsKci3FPsnaizJeJhoetU1Wfw==} + engines: {node: '>=18'} + peerDependencies: + zod: ^3.25.76 || ^4.1.8 + ai@5.1.0-beta.22: resolution: {integrity: sha512-7z/PMSEQRes1aXywA5POKhoDxXD25CAT7Al2ObYFiQPudhL8GXd9wlXcbUBaz1+Smg4WHKR4f83iOv9jwyubvQ==} engines: {node: '>=18'} @@ -5264,6 +5307,11 @@ packages: resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} engines: {node: '>=8'} + swr@2.3.6: + resolution: {integrity: sha512-wfHRmHWk/isGNMwlLGlZX5Gzz/uTgo0o2IRuTMcf4CPuPFJZlq0rDaKUx+ozB5nBOReNV1kiOyzMfj+MBMikLw==} + peerDependencies: + react: ^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + symbol-tree@3.2.4: resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==} @@ -5281,6 +5329,10 @@ packages: resolution: {integrity: sha512-wK0Ri4fOGjv/XPy8SBHZChl8CM7uMc5VML7SqiQ0zG7+J5Vr+RMQDoHa2CNT6KHUnTGIXH34UDMkPzAUyapBZg==} engines: {node: '>=8'} + throttleit@2.1.0: + resolution: {integrity: sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw==} + engines: {node: '>=18'} + tiktok-video-element@0.1.1: resolution: {integrity: sha512-BaiVzvNz2UXDKTdSrXzrNf4q6Ecc+/utYUh7zdEu2jzYcJVDoqYbVfUl0bCfMoOeeAqg28vD/yN63Y3E9jOrlA==} @@ -5846,6 +5898,20 @@ snapshots: '@vercel/oidc': 3.0.3 zod: 4.1.12 + '@ai-sdk/gateway@2.0.6(zod@4.1.12)': + dependencies: + '@ai-sdk/provider': 2.0.0 + '@ai-sdk/provider-utils': 3.0.16(zod@4.1.12) + '@vercel/oidc': 3.0.3 + zod: 4.1.12 + + '@ai-sdk/provider-utils@3.0.16(zod@4.1.12)': + dependencies: + '@ai-sdk/provider': 2.0.0 + '@standard-schema/spec': 1.0.0 + eventsource-parser: 3.0.6 + zod: 4.1.12 + '@ai-sdk/provider-utils@3.1.0-beta.7(zod@4.1.12)': dependencies: '@ai-sdk/provider': 2.1.0-beta.5 @@ -5853,10 +5919,24 @@ snapshots: eventsource-parser: 3.0.6 zod: 4.1.12 + '@ai-sdk/provider@2.0.0': + dependencies: + json-schema: 0.4.0 + '@ai-sdk/provider@2.1.0-beta.5': dependencies: json-schema: 0.4.0 + '@ai-sdk/react@2.0.87(react@19.2.0)(zod@4.1.12)': + dependencies: + '@ai-sdk/provider-utils': 3.0.16(zod@4.1.12) + ai: 5.0.87(zod@4.1.12) + react: 19.2.0 + swr: 2.3.6(react@19.2.0) + throttleit: 2.1.0 + optionalDependencies: + zod: 4.1.12 + '@alloc/quick-lru@5.2.0': {} '@antfu/install-pkg@1.1.0': @@ -6646,6 +6726,10 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 + '@loremllm/transport@0.4.5(ai@5.0.87(zod@4.1.12))': + dependencies: + ai: 5.0.87(zod@4.1.12) + '@manypkg/find-root@1.1.0': dependencies: '@babel/runtime': 7.28.4 @@ -8069,7 +8153,7 @@ snapshots: '@ungap/structured-clone@1.3.0': {} - '@vercel/analytics@1.5.0(next@16.0.0(@opentelemetry/api@1.9.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(react@19.2.0)': + '@vercel/analytics@1.5.0(next@16.0.0(@babel/core@7.28.4)(@opentelemetry/api@1.9.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(react@19.2.0)': optionalDependencies: next: 16.0.0(@babel/core@7.28.4)(@opentelemetry/api@1.9.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0) react: 19.2.0 @@ -8089,7 +8173,7 @@ snapshots: path-to-regexp: 6.2.1 semver: 7.7.2 optionalDependencies: - '@vercel/analytics': 1.5.0(next@16.0.0(@opentelemetry/api@1.9.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(react@19.2.0) + '@vercel/analytics': 1.5.0(next@16.0.0(@babel/core@7.28.4)(@opentelemetry/api@1.9.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(react@19.2.0) '@vercel/speed-insights': 1.2.0(next@16.0.0(@opentelemetry/api@1.9.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(react@19.2.0) next: 16.0.0(@babel/core@7.28.4)(@opentelemetry/api@1.9.0)(react-dom@19.2.0(react@19.2.0))(react@19.2.0) react: 19.2.0 @@ -8259,6 +8343,14 @@ snapshots: agent-base@7.1.4: {} + ai@5.0.87(zod@4.1.12): + dependencies: + '@ai-sdk/gateway': 2.0.6(zod@4.1.12) + '@ai-sdk/provider': 2.0.0 + '@ai-sdk/provider-utils': 3.0.16(zod@4.1.12) + '@opentelemetry/api': 1.9.0 + zod: 4.1.12 + ai@5.1.0-beta.22(zod@4.1.12): dependencies: '@ai-sdk/gateway': 1.1.0-beta.16(zod@4.1.12) @@ -11539,6 +11631,12 @@ snapshots: dependencies: has-flag: 4.0.0 + swr@2.3.6(react@19.2.0): + dependencies: + dequal: 2.0.3 + react: 19.2.0 + use-sync-external-store: 1.5.0(react@19.2.0) + symbol-tree@3.2.4: optional: true @@ -11550,6 +11648,8 @@ snapshots: term-size@2.2.1: {} + throttleit@2.1.0: {} + tiktok-video-element@0.1.1: {} tiny-invariant@1.3.3: {}