Improve useStreamingChat types

This commit is contained in:
Alex Gleason committed 2025-08-22 16:55:16 -05:00
1 parent c7fa293969
commit 1551442c7d
4 files changed
+152 -243

No files matched your search

+1 -1
View File
@@ -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()
});
+63 -56
View File
@@ -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(({
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-1">
<span className="font-medium text-sm">
{message.role === 'user' ? userDisplayName : 'Assistant'}
{message.role === 'user' ? userDisplayName : message.role === 'assistant' ? 'Assistant' : 'System'}
</span>
<span className="text-xs text-muted-foreground">
{message.role === 'user' ? 'User' : 'AI'}
{message.role === 'user' ? 'User' : message.role === 'assistant' ? 'AI' : 'System'}
</span>
{isCurrentlyStreaming && onStopStreaming && (
<Button
@@ -68,12 +67,15 @@ export const StreamingMessageItem = memo(({
<div className="text-sm">
{message.role === 'user' ? (
<div className="whitespace-pre-wrap break-words">
{message.content}
{typeof message.content === 'string' ? message.content :
Array.isArray(message.content) ?
message.content.map(part => part.type === 'text' ? part.text : '').join('') :
''}
</div>
) : message.role === 'assistant' ? (
<div>
{/* Text content */}
{message.content && (
{/* Handle assistant content */}
{typeof message.content === 'string' ? (
<div className="mb-2">
{message.isStreaming ? (
<Response>{message.content}</Response>
@@ -86,60 +88,65 @@ export const StreamingMessageItem = memo(({
<span className="inline-block w-2 h-4 bg-current animate-pulse ml-1" />
)}
</div>
)}
{/* Tool calls */}
{message.toolCalls && message.toolCalls.length > 0 && (
) : Array.isArray(message.content) ? (
<div className="space-y-2">
{message.toolCalls.map((toolCall) => {
// Create a mock CoreToolMessage for compatibility with AssistantContent
const mockToolResults: CoreToolMessage[] = message.toolResults ? [
{
role: 'tool',
content: message.toolResults
.filter(result => result.toolCallId === toolCall.id)
.map(result => ({
type: 'tool-result' as const,
toolCallId: result.toolCallId,
toolName: result.toolName,
output: {
type: 'text' as const,
value: typeof result.output === 'string' ? result.output : JSON.stringify(result.output)
}
}))
}
] : [];
return (
<AssistantContent
key={toolCall.id}
content={[
{
type: 'tool-call',
toolCallId: toolCall.id,
toolName: toolCall.toolName,
input: toolCall.input
}
]}
toolResults={mockToolResults}
/>
);
{message.content.map((part, index) => {
if (part.type === 'text') {
return (
<div key={index} className="mb-2">
{message.isStreaming ? (
<Response>{part.text}</Response>
) : (
<div className="prose prose-sm max-w-none dark:prose-invert">
<Response>{part.text}</Response>
</div>
)}
</div>
);
} else if (part.type === 'tool-call') {
return (
<AssistantContent
key={index}
content={[part]}
toolResults={[]}
/>
);
} else if (part.type === 'tool-result') {
return (
<AssistantContent
key={index}
content={[]}
toolResults={[{
role: 'tool',
content: [part]
}]}
/>
);
}
return null;
})}
{message.isStreaming && (
<span className="inline-block w-2 h-4 bg-current animate-pulse ml-1" />
)}
</div>
)}
{/* Streaming indicator for when there's no content yet */}
{message.isStreaming && !message.content && !message.toolCalls?.length && (
<div className="flex items-center gap-2 text-muted-foreground">
<div className="flex space-x-1">
<div className="h-1 w-1 bg-current rounded-full animate-bounce [animation-delay:-0.3s]"></div>
<div className="h-1 w-1 bg-current rounded-full animate-bounce [animation-delay:-0.15s]"></div>
<div className="h-1 w-1 bg-current rounded-full animate-bounce"></div>
) : (
/* Streaming indicator for when there's no content yet */
message.isStreaming && (
<div className="flex items-center gap-2 text-muted-foreground">
<div className="flex space-x-1">
<div className="h-1 w-1 bg-current rounded-full animate-bounce [animation-delay:-0.3s]"></div>
<div className="h-1 w-1 bg-current rounded-full animate-bounce [animation-delay:-0.15s]"></div>
<div className="h-1 w-1 bg-current rounded-full animate-bounce"></div>
</div>
<span className="text-xs">Thinking...</span>
</div>
<span className="text-xs">Thinking...</span>
</div>
)
)}
</div>
) : message.role === 'system' ? (
<div className="whitespace-pre-wrap break-words text-muted-foreground">
{typeof message.content === 'string' ? message.content : ''}
</div>
) : null}
</div>
</div>
+73 -93
View File
@@ -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<StreamingMessage[]>([]);
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [isStreaming, setIsStreaming] = useState(false);
const [currentStreamingMessageId, setCurrentStreamingMessageId] = useState<string | null>(null);
const abortControllerRef = useRef<AbortController | null>(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<StreamingMessage> | ((prev: StreamingMessage) => Partial<StreamingMessage>)) => {
const updateMessage = useCallback((id: string, updates: Partial<ChatMessage> | ((prev: ChatMessage) => Partial<ChatMessage>)) => {
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<TextPart | ToolCallPart | ToolResultPart> = 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<TextPart | ToolCallPart | ToolResultPart> = 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;
}
+15 -93
View File
@@ -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);
}