From 1551442c7d37b6dafd9e019915cd791872db9dff Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Fri, 22 Aug 2025 16:55:16 -0500 Subject: [PATCH] Improve useStreamingChat types --- src/components/Shakespeare/ChatPane.tsx | 2 +- src/components/ai/StreamingMessageItem.tsx | 119 ++++++++------- src/hooks/useStreamingChat.ts | 166 +++++++++------------ src/lib/messageConversion.ts | 108 ++------------ 4 files changed, 152 insertions(+), 243 deletions(-) diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 9cafb4f9..27e70f01 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -203,7 +203,7 @@ BASE_DOMAIN=nostrdeploy.com`); if (!messages.length) { addMessage({ id: generateId(), - role: 'assistant', + role: 'assistant' as const, content: `Hello! I'm here to help you build "${projectName}". I can help you edit files, add new features, and build your Nostr website. What would you like to work on?`, timestamp: Date.now() }); diff --git a/src/components/ai/StreamingMessageItem.tsx b/src/components/ai/StreamingMessageItem.tsx index df805b38..6268163b 100644 --- a/src/components/ai/StreamingMessageItem.tsx +++ b/src/components/ai/StreamingMessageItem.tsx @@ -3,12 +3,11 @@ import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; import { Bot, User, Square } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Response } from '@/components/ai-elements/response'; -import { StreamingMessage } from '@/hooks/useStreamingChat'; +import { ChatMessage } from '@/hooks/useStreamingChat'; import { AssistantContent } from '@/components/ai/AssistantContent'; -import { CoreToolMessage } from 'ai'; interface StreamingMessageItemProps { - message: StreamingMessage; + message: ChatMessage; userDisplayName?: string; userProfileImage?: string; isCurrentlyStreaming?: boolean; @@ -48,10 +47,10 @@ export const StreamingMessageItem = memo(({
- {message.role === 'user' ? userDisplayName : 'Assistant'} + {message.role === 'user' ? userDisplayName : message.role === 'assistant' ? 'Assistant' : 'System'} - {message.role === 'user' ? 'User' : 'AI'} + {message.role === 'user' ? 'User' : message.role === 'assistant' ? 'AI' : 'System'} {isCurrentlyStreaming && onStopStreaming && (
diff --git a/src/hooks/useStreamingChat.ts b/src/hooks/useStreamingChat.ts index 1aa72d59..159f16fa 100644 --- a/src/hooks/useStreamingChat.ts +++ b/src/hooks/useStreamingChat.ts @@ -1,22 +1,12 @@ import { useState, useCallback, useRef } from 'react'; import { createOpenAICompatible } from '@ai-sdk/openai-compatible'; import { streamText, ModelMessage, generateId, Tool, stepCountIs } from 'ai'; +import type { TextPart, ToolCallPart, ToolResultPart } from 'ai'; import { useAISettings } from '@/hooks/useAISettings'; -export interface StreamingMessage { +// Extend ModelMessage with additional UI state +export type ChatMessage = ModelMessage & { id: string; - role: 'user' | 'assistant' | 'tool'; - content: string; - toolCalls?: Array<{ - id: string; - toolName: string; - input: unknown; - }>; - toolResults?: Array<{ - toolCallId: string; - toolName: string; - output: unknown; - }>; isStreaming?: boolean; timestamp?: number; } @@ -37,38 +27,18 @@ export function useStreamingChat({ onStepFinish, onUpdateMetadata }: UseStreamingChatOptions) { - const [messages, setMessages] = useState([]); + const [messages, setMessages] = useState([]); const [isStreaming, setIsStreaming] = useState(false); const [currentStreamingMessageId, setCurrentStreamingMessageId] = useState(null); const abortControllerRef = useRef(null); const { settings, isConfigured } = useAISettings(); - // Convert StreamingMessage to ModelMessage for AI SDK - const convertToModelMessages = useCallback((streamingMessages: StreamingMessage[]): ModelMessage[] => { - const modelMessages: ModelMessage[] = []; - - for (const msg of streamingMessages) { - if (msg.role === 'user') { - modelMessages.push({ - role: 'user', - content: msg.content - }); - } else if (msg.role === 'assistant') { - // For assistant messages, just use text content for now - // Tool calls will be handled by the AI SDK automatically - if (msg.content) { - modelMessages.push({ - role: 'assistant', - content: msg.content - }); - } - } - } - - return modelMessages; + // Convert ChatMessage to ModelMessage for AI SDK + const convertToModelMessages = useCallback((chatMessages: ChatMessage[]): ModelMessage[] => { + return chatMessages.map(({ id, isStreaming, timestamp, ...modelMessage }) => modelMessage as ModelMessage); }, []); - const addMessage = useCallback((message: StreamingMessage) => { + const addMessage = useCallback((message: ChatMessage) => { setMessages(prev => { const messageMap = new Map(prev.map(m => [m.id, m])); messageMap.set(message.id, message); @@ -76,11 +46,11 @@ export function useStreamingChat({ }); }, []); - const updateMessage = useCallback((id: string, updates: Partial | ((prev: StreamingMessage) => Partial)) => { + const updateMessage = useCallback((id: string, updates: Partial | ((prev: ChatMessage) => Partial)) => { setMessages(prev => prev.map(msg => { if (msg.id === id) { const updatesObj = typeof updates === 'function' ? updates(msg) : updates; - return { ...msg, ...updatesObj }; + return { ...msg, ...updatesObj } as ChatMessage; } return msg; })); @@ -90,7 +60,7 @@ export function useStreamingChat({ if (!isConfigured || isStreaming) return; // Add user message - const userMessage: StreamingMessage = { + const userMessage: ChatMessage = { id: generateId(), role: 'user', content, @@ -138,32 +108,7 @@ export function useStreamingChat({ }); } - // Handle tool calls and results - if (stepResult.toolCalls && stepResult.toolCalls.length > 0) { - // Update the current message with tool calls - if (currentAssistantMessageId) { - updateMessage(currentAssistantMessageId, { - toolCalls: stepResult.toolCalls.map(tc => ({ - id: tc.toolCallId, - toolName: tc.toolName, - input: tc.input - })) - }); - } - } - - if (stepResult.toolResults && stepResult.toolResults.length > 0) { - // Add tool results to the current assistant message - if (currentAssistantMessageId) { - updateMessage(currentAssistantMessageId, { - toolResults: stepResult.toolResults.map(tr => ({ - toolCallId: tr.toolCallId, - toolName: tr.toolName, - output: tr.output - })) - }); - } - } + // Tool calls and results are now handled in the streaming chunks // Update metadata if callback provided if (onUpdateMetadata && stepResult.toolCalls && stepResult.toolCalls.length > 0) { @@ -192,7 +137,7 @@ export function useStreamingChat({ // Create new assistant message if we don't have one for this step if (!currentAssistantMessageId) { currentAssistantMessageId = generateId(); - const assistantMessage: StreamingMessage = { + const assistantMessage: ChatMessage = { id: currentAssistantMessageId, role: 'assistant', content: '', @@ -204,10 +149,31 @@ export function useStreamingChat({ } // Update the current message with new text - updateMessage(currentAssistantMessageId, (prev) => ({ - content: (prev.content || '') + chunk.text, - isStreaming: true - })); + updateMessage(currentAssistantMessageId, (prev) => { + const currentContent = prev.content; + if (typeof currentContent === 'string') { + return { + content: currentContent + chunk.text, + isStreaming: true + }; + } else { + // If content is an array, find the last text part or add a new one + const content = Array.isArray(currentContent) ? + currentContent.filter((part): part is TextPart | ToolCallPart | ToolResultPart => + part.type === 'text' || part.type === 'tool-call' || part.type === 'tool-result' + ) : []; + const lastPart = content[content.length - 1]; + if (lastPart && lastPart.type === 'text') { + lastPart.text += chunk.text; + } else { + content.push({ type: 'text' as const, text: chunk.text }); + } + return { + content, + isStreaming: true + }; + } + }); break; } @@ -215,7 +181,7 @@ export function useStreamingChat({ // Create new assistant message if we don't have one for this step if (!currentAssistantMessageId) { currentAssistantMessageId = generateId(); - const assistantMessage: StreamingMessage = { + const assistantMessage: ChatMessage = { id: currentAssistantMessageId, role: 'assistant', content: '', @@ -227,32 +193,46 @@ export function useStreamingChat({ } // Add tool call to current message - updateMessage(currentAssistantMessageId, (prev) => ({ - toolCalls: [ - ...(prev.toolCalls || []), - { - id: chunk.toolCallId, - toolName: chunk.toolName, - input: chunk.input - } - ] - })); + updateMessage(currentAssistantMessageId, (prev) => { + const currentContent = prev.content; + const content: Array = Array.isArray(currentContent) ? + currentContent.filter((part): part is TextPart | ToolCallPart | ToolResultPart => + part.type === 'text' || part.type === 'tool-call' || part.type === 'tool-result' + ) : + typeof currentContent === 'string' && currentContent ? [{ type: 'text' as const, text: currentContent }] : []; + + content.push({ + type: 'tool-call' as const, + toolCallId: chunk.toolCallId, + toolName: chunk.toolName, + input: chunk.input + }); + + return { content }; + }); break; } case 'tool-result': { // Add tool result to current message if (currentAssistantMessageId) { - updateMessage(currentAssistantMessageId, (prev) => ({ - toolResults: [ - ...(prev.toolResults || []), - { - toolCallId: chunk.toolCallId, - toolName: chunk.toolName, - output: chunk.output - } - ] - })); + updateMessage(currentAssistantMessageId, (prev) => { + const currentContent = prev.content; + const content: Array = Array.isArray(currentContent) ? + currentContent.filter((part): part is TextPart | ToolCallPart | ToolResultPart => + part.type === 'text' || part.type === 'tool-call' || part.type === 'tool-result' + ) : + typeof currentContent === 'string' && currentContent ? [{ type: 'text' as const, text: currentContent }] : []; + + content.push({ + type: 'tool-result' as const, + toolCallId: chunk.toolCallId, + toolName: chunk.toolName, + output: chunk.output + }); + + return { content }; + }); } break; } diff --git a/src/lib/messageConversion.ts b/src/lib/messageConversion.ts index 1107c1c0..d6a31d44 100644 --- a/src/lib/messageConversion.ts +++ b/src/lib/messageConversion.ts @@ -1,114 +1,36 @@ import { ModelMessage, generateId } from 'ai'; -import { StreamingMessage } from '@/hooks/useStreamingChat'; +import { ChatMessage } from '@/hooks/useStreamingChat'; /** - * Convert ModelMessage array to StreamingMessage array + * Convert ModelMessage array to ChatMessage array * This is useful when loading chat history from storage */ -export function convertModelMessagesToStreamingMessages(modelMessages: ModelMessage[]): StreamingMessage[] { - const streamingMessages: StreamingMessage[] = []; - - for (const msg of modelMessages) { - if (msg.role === 'user') { - streamingMessages.push({ - id: generateId(), - role: 'user', - content: typeof msg.content === 'string' ? msg.content : msg.content.map(part => { - if (part.type === 'text') return part.text; - return ''; - }).join(''), - timestamp: Date.now() - }); - } else if (msg.role === 'assistant') { - const streamingMessage: StreamingMessage = { - id: generateId(), - role: 'assistant', - content: '', - timestamp: Date.now() - }; - - if (typeof msg.content === 'string') { - streamingMessage.content = msg.content; - } else if (Array.isArray(msg.content)) { - // Extract text content - const textParts = msg.content.filter(part => part.type === 'text'); - streamingMessage.content = textParts.map(part => part.text).join(''); - - // Extract tool calls - const toolCalls = msg.content.filter(part => part.type === 'tool-call'); - if (toolCalls.length > 0) { - streamingMessage.toolCalls = toolCalls.map(tc => ({ - id: tc.toolCallId, - toolName: tc.toolName, - input: tc.input - })); - } - } - - streamingMessages.push(streamingMessage); - } else if (msg.role === 'tool') { - // Tool results are typically integrated into the assistant message - // but we can create a separate tool message if needed - if (Array.isArray(msg.content)) { - const toolResults = msg.content.map(result => ({ - toolCallId: result.toolCallId, - toolName: result.toolName, - output: result.output - })); - - streamingMessages.push({ - id: generateId(), - role: 'tool', - content: '', - toolResults, - timestamp: Date.now() - }); - } - } - } - - return streamingMessages; +export function convertModelMessagesToChatMessages(modelMessages: ModelMessage[]): ChatMessage[] { + return modelMessages.map(msg => ({ + ...msg, + id: generateId(), + timestamp: Date.now() + })); } /** - * Convert StreamingMessage array to ModelMessage array + * Convert ChatMessage array to ModelMessage array * This is useful when saving chat history to storage or sending to AI */ -export function convertStreamingMessagesToModelMessages(streamingMessages: StreamingMessage[]): ModelMessage[] { - const modelMessages: ModelMessage[] = []; - - for (const msg of streamingMessages) { - if (msg.role === 'user') { - modelMessages.push({ - role: 'user', - content: msg.content - }); - } else if (msg.role === 'assistant') { - // For assistant messages, just use text content for now - // Tool calls will be handled by the AI SDK automatically during streaming - if (msg.content) { - modelMessages.push({ - role: 'assistant', - content: msg.content - }); - } - } - // Skip tool messages as they're handled differently in the streaming context - } - - return modelMessages; +export function convertChatMessagesToModelMessages(chatMessages: ChatMessage[]): ModelMessage[] { + return chatMessages.map(({ id, isStreaming, timestamp, ...modelMessage }) => modelMessage); } /** * Save chat history as ModelMessage array (for persistence) */ -export function prepareChatHistoryForStorage(streamingMessages: StreamingMessage[]): ModelMessage[] { - return convertStreamingMessagesToModelMessages(streamingMessages); +export function prepareChatHistoryForStorage(chatMessages: ChatMessage[]): ModelMessage[] { + return convertChatMessagesToModelMessages(chatMessages); } /** * Load chat history from ModelMessage array (from persistence) */ -export function loadChatHistoryFromStorage(modelMessages: ModelMessage[]): StreamingMessage[] { - return convertModelMessagesToStreamingMessages(modelMessages); +export function loadChatHistoryFromStorage(modelMessages: ModelMessage[]): ChatMessage[] { + return convertModelMessagesToChatMessages(modelMessages); } \ No newline at end of file