mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-06 00:27:24 +00:00
cleanup
This commit is contained in:
1 parent
a3d491f1a5
commit
6583e29d08
11 files changed
+144
-902
No files matched your search
@@ -1,403 +0,0 @@
|
||||
import { useState, useCallback, useRef, useEffect } from 'react';
|
||||
import OpenAI from 'openai';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
|
||||
// Use OpenAI's native message type
|
||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;
|
||||
|
||||
export interface StreamingMessage {
|
||||
role: 'assistant';
|
||||
content: string;
|
||||
tool_calls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[];
|
||||
}
|
||||
|
||||
interface UseAIChatOptions {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
tools?: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||
customTools?: Record<string, Tool<unknown>>;
|
||||
systemPrompt?: string;
|
||||
onUpdateMetadata?: (title: string, description: string) => void;
|
||||
maxSteps?: number;
|
||||
}
|
||||
|
||||
export function useAIChat({
|
||||
projectId,
|
||||
projectName,
|
||||
tools = {},
|
||||
customTools = {},
|
||||
systemPrompt,
|
||||
onUpdateMetadata,
|
||||
maxSteps = 50
|
||||
}: UseAIChatOptions) {
|
||||
const [messages, setMessages] = useState<AIMessage[]>([]);
|
||||
const [streamingMessage, setStreamingMessage] = useState<StreamingMessage | undefined>(undefined);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [sessionName, setSessionName] = useState<string>('');
|
||||
const abortControllerRef = useRef<AbortController | null>(null);
|
||||
const { settings, isConfigured, addRecentlyUsedModel } = useAISettings();
|
||||
const { fs } = useFS();
|
||||
|
||||
// Save all messages to history
|
||||
const saveMessagesToHistory = useCallback(async (allMessages: AIMessage[]) => {
|
||||
if (!sessionName) return;
|
||||
|
||||
try {
|
||||
const dotAI = new DotAI(fs, `/projects/${projectId}`);
|
||||
await dotAI.setHistory(sessionName, allMessages);
|
||||
} catch (error) {
|
||||
console.warn('Failed to save messages to history:', error);
|
||||
}
|
||||
}, [fs, projectId, sessionName]);
|
||||
|
||||
const addMessage = useCallback((message: AIMessage) => {
|
||||
setMessages(prev => {
|
||||
const newMessages = [...prev, message];
|
||||
// Save to history asynchronously with all messages
|
||||
saveMessagesToHistory(newMessages);
|
||||
return newMessages;
|
||||
});
|
||||
}, [saveMessagesToHistory]);
|
||||
|
||||
const startGeneration = useCallback(async (providerModel: string, messagesToUse?: AIMessage[]) => {
|
||||
const currentMessages = messagesToUse || messages;
|
||||
|
||||
if (!isConfigured || isLoading || currentMessages.length === 0) return;
|
||||
|
||||
// Get the last message - it should be a user message
|
||||
const lastMessage = currentMessages[currentMessages.length - 1];
|
||||
if (lastMessage.role !== 'user') return;
|
||||
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
// Create abort controller for this request
|
||||
abortControllerRef.current = new AbortController();
|
||||
|
||||
// Use all existing messages
|
||||
const modelMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [...currentMessages];
|
||||
|
||||
// Add system message if provided
|
||||
if (systemPrompt) {
|
||||
modelMessages.unshift({
|
||||
role: 'system',
|
||||
content: systemPrompt
|
||||
});
|
||||
}
|
||||
|
||||
// Parse provider and model
|
||||
const parsed = parseProviderModel(providerModel, settings.providers);
|
||||
const connectionConfig = parsed.connection;
|
||||
const modelName = parsed.model;
|
||||
|
||||
// Initialize OpenAI client with parsed connection
|
||||
const openai = new OpenAI({
|
||||
baseURL: connectionConfig.baseURL,
|
||||
apiKey: connectionConfig.apiKey,
|
||||
dangerouslyAllowBrowser: true
|
||||
});
|
||||
|
||||
// Update metadata
|
||||
if (onUpdateMetadata) {
|
||||
onUpdateMetadata('Shakespeare', `Working on ${projectName}...`);
|
||||
}
|
||||
|
||||
// Keep track of current messages for this conversation
|
||||
const conversationMessages = [...modelMessages];
|
||||
let stepCount = 0;
|
||||
|
||||
// Main loop for handling multiple steps with tool calls
|
||||
while (stepCount < maxSteps) {
|
||||
stepCount++;
|
||||
console.log(`AI Chat Step ${stepCount}/${maxSteps}`);
|
||||
|
||||
// Initialize streaming message
|
||||
setStreamingMessage({
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
tool_calls: undefined
|
||||
});
|
||||
|
||||
// Prepare chat completion options
|
||||
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
|
||||
model: modelName,
|
||||
messages: conversationMessages,
|
||||
tools: tools && Object.keys(tools).length > 0 ? Object.values(tools) : undefined,
|
||||
tool_choice: tools && Object.keys(tools).length > 0 ? 'auto' : undefined,
|
||||
stream: true
|
||||
};
|
||||
|
||||
// Generate streaming response
|
||||
const stream = await openai.chat.completions.create(completionOptions, {
|
||||
signal: abortControllerRef.current.signal
|
||||
});
|
||||
|
||||
let accumulatedContent = '';
|
||||
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
|
||||
let finishReason: string | null = null;
|
||||
let hasRecordedModel = false;
|
||||
|
||||
// Process the stream
|
||||
for await (const chunk of stream) {
|
||||
const delta = chunk.choices[0]?.delta;
|
||||
|
||||
// Track recently used model on first chunk
|
||||
if (!hasRecordedModel && providerModel) {
|
||||
addRecentlyUsedModel(providerModel);
|
||||
hasRecordedModel = true;
|
||||
}
|
||||
|
||||
if (delta?.content) {
|
||||
accumulatedContent += delta.content;
|
||||
setStreamingMessage(prev => prev ? {
|
||||
...prev,
|
||||
content: prev.content + delta.content
|
||||
} : {
|
||||
role: 'assistant',
|
||||
content: delta.content,
|
||||
tool_calls: undefined
|
||||
});
|
||||
}
|
||||
|
||||
if (delta?.tool_calls) {
|
||||
for (const toolCallDelta of delta.tool_calls) {
|
||||
const index = toolCallDelta.index;
|
||||
if (index !== undefined) {
|
||||
// Initialize tool call if it doesn't exist
|
||||
if (!accumulatedToolCalls[index]) {
|
||||
accumulatedToolCalls[index] = {
|
||||
id: toolCallDelta.id || '',
|
||||
type: 'function',
|
||||
function: {
|
||||
name: '',
|
||||
arguments: ''
|
||||
}
|
||||
} as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
||||
}
|
||||
|
||||
// Update tool call properties
|
||||
if (toolCallDelta.id) {
|
||||
accumulatedToolCalls[index].id = toolCallDelta.id;
|
||||
}
|
||||
if (toolCallDelta.function?.name && accumulatedToolCalls[index].type === 'function') {
|
||||
(accumulatedToolCalls[index] as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall).function.name = toolCallDelta.function.name;
|
||||
}
|
||||
if (toolCallDelta.function?.arguments && accumulatedToolCalls[index].type === 'function') {
|
||||
(accumulatedToolCalls[index] as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall).function.arguments += toolCallDelta.function.arguments;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update streaming message with current tool calls
|
||||
setStreamingMessage(prev => prev ? {
|
||||
...prev,
|
||||
tool_calls: accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined
|
||||
} : {
|
||||
role: 'assistant',
|
||||
content: accumulatedContent,
|
||||
tool_calls: accumulatedToolCalls.length > 0 ? accumulatedToolCalls : undefined
|
||||
});
|
||||
}
|
||||
|
||||
if (chunk.choices[0]?.finish_reason) {
|
||||
finishReason = chunk.choices[0].finish_reason;
|
||||
}
|
||||
}
|
||||
|
||||
// Create final assistant message
|
||||
const assistantMessage: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: accumulatedContent,
|
||||
...(accumulatedToolCalls.length > 0 && { tool_calls: accumulatedToolCalls })
|
||||
};
|
||||
|
||||
// Clear streaming message and add final message
|
||||
setStreamingMessage(undefined);
|
||||
addMessage(assistantMessage);
|
||||
conversationMessages.push(assistantMessage);
|
||||
|
||||
// Check if we should stop (no tool calls or finish reason is "stop")
|
||||
if (finishReason === 'stop' || !accumulatedToolCalls || accumulatedToolCalls.length === 0) {
|
||||
console.log(`AI Chat completed after ${stepCount} steps. Finish reason: ${finishReason}`);
|
||||
break;
|
||||
}
|
||||
|
||||
// Handle tool calls if present
|
||||
if (accumulatedToolCalls && accumulatedToolCalls.length > 0) {
|
||||
console.log(`Processing ${accumulatedToolCalls.length} tool calls in step ${stepCount}`);
|
||||
|
||||
for (const toolCall of accumulatedToolCalls) {
|
||||
if (toolCall.type !== 'function') continue;
|
||||
|
||||
const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall;
|
||||
const toolName = functionToolCall.function.name;
|
||||
const tool = customTools[toolName];
|
||||
|
||||
if (!tool) {
|
||||
// Tool not found
|
||||
const toolNotFoundMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content: `Tool ${toolName} not found`,
|
||||
tool_call_id: functionToolCall.id
|
||||
};
|
||||
|
||||
addMessage(toolNotFoundMessage);
|
||||
conversationMessages.push(toolNotFoundMessage);
|
||||
continue;
|
||||
}
|
||||
|
||||
let toolArgs: unknown;
|
||||
try {
|
||||
const json = JSON.parse(functionToolCall.function.arguments);
|
||||
toolArgs = tool.inputSchema.parse(json);
|
||||
} catch (parseError) {
|
||||
console.error(`Failed to parse tool arguments for ${toolName}:`, parseError);
|
||||
|
||||
const toolErrorMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content: `Error parsing arguments for tool ${toolName}: ${parseError instanceof Error ? parseError.message : 'Unknown error'}`,
|
||||
tool_call_id: functionToolCall.id
|
||||
};
|
||||
|
||||
addMessage(toolErrorMessage);
|
||||
conversationMessages.push(toolErrorMessage);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
console.log(`Executing tool: ${toolName}`, toolArgs);
|
||||
|
||||
// Execute the custom tool
|
||||
const content = await tool.execute(toolArgs);
|
||||
|
||||
// Add tool result message
|
||||
const toolResultMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content,
|
||||
tool_call_id: functionToolCall.id
|
||||
};
|
||||
|
||||
addMessage(toolResultMessage);
|
||||
conversationMessages.push(toolResultMessage);
|
||||
} catch (toolError) {
|
||||
console.error(`Tool execution error for ${toolName}:`, toolError);
|
||||
|
||||
const toolErrorMessage: AIMessage = {
|
||||
role: 'tool',
|
||||
content: `Error executing tool ${toolName}: ${toolError instanceof Error ? toolError.message : 'Unknown error'}`,
|
||||
tool_call_id: functionToolCall.id
|
||||
};
|
||||
|
||||
addMessage(toolErrorMessage);
|
||||
conversationMessages.push(toolErrorMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we reached maxSteps, log a warning
|
||||
if (stepCount >= maxSteps) {
|
||||
console.warn(`AI Chat reached maximum steps (${maxSteps}). Conversation may be incomplete.`);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('AI chat error:', error);
|
||||
|
||||
// Clear any streaming message on error
|
||||
setStreamingMessage(undefined);
|
||||
|
||||
// Add error message
|
||||
const errorMessage: AIMessage = {
|
||||
role: 'assistant',
|
||||
content: error instanceof Error ? error.message : 'Sorry, I encountered an error. Please try again.'
|
||||
};
|
||||
|
||||
addMessage(errorMessage);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
abortControllerRef.current = null;
|
||||
}
|
||||
}, [isConfigured, isLoading, addMessage, messages, settings.providers, tools, customTools, systemPrompt, onUpdateMetadata, projectName, maxSteps, addRecentlyUsedModel]);
|
||||
|
||||
// Load message history when component mounts or projectId changes
|
||||
useEffect(() => {
|
||||
const loadMessageHistory = async () => {
|
||||
try {
|
||||
const dotAI = new DotAI(fs, `/projects/${projectId}`);
|
||||
const lastSession = await dotAI.readLastSessionHistory();
|
||||
|
||||
if (lastSession) {
|
||||
setMessages(lastSession.messages);
|
||||
setSessionName(lastSession.sessionName);
|
||||
} else {
|
||||
// No history to load, start fresh
|
||||
setMessages([]);
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to load message history:', error);
|
||||
// Start fresh on any error
|
||||
setMessages([]);
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}
|
||||
};
|
||||
|
||||
loadMessageHistory();
|
||||
}, [projectId, fs]);
|
||||
|
||||
const sendMessage = useCallback(async (content: string, providerModel: string) => {
|
||||
if (!isConfigured || isLoading) return;
|
||||
|
||||
// Add user message
|
||||
const userMessage: AIMessage = {
|
||||
role: 'user',
|
||||
content
|
||||
};
|
||||
|
||||
// Calculate the new messages array that will exist after the state update
|
||||
const newMessages = [...messages, userMessage];
|
||||
|
||||
// Add the message to state
|
||||
addMessage(userMessage);
|
||||
|
||||
// Start generation with the new messages array directly
|
||||
startGeneration(providerModel, newMessages);
|
||||
}, [isConfigured, isLoading, messages, addMessage, startGeneration]);
|
||||
|
||||
const stopGeneration = useCallback(() => {
|
||||
if (abortControllerRef.current) {
|
||||
abortControllerRef.current.abort();
|
||||
}
|
||||
setStreamingMessage(undefined);
|
||||
}, []);
|
||||
|
||||
const clearMessages = useCallback(() => {
|
||||
setMessages([]);
|
||||
setStreamingMessage(undefined);
|
||||
// Start a new session when clearing messages
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}, []);
|
||||
|
||||
const startNewSession = useCallback(() => {
|
||||
setMessages([]);
|
||||
setStreamingMessage(undefined);
|
||||
setSessionName(DotAI.generateSessionName());
|
||||
}, []);
|
||||
|
||||
return {
|
||||
messages,
|
||||
streamingMessage,
|
||||
isLoading,
|
||||
sendMessage,
|
||||
startGeneration,
|
||||
stopGeneration,
|
||||
clearMessages,
|
||||
startNewSession,
|
||||
addMessage,
|
||||
isConfigured
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import { useSessionManager } from '@/hooks/useSessionManager';
|
||||
import { useSessionSubscription } from '@/hooks/useSessionSubscription';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import type { SessionState, SessionConfig, AIMessage } from '@/lib/SessionManager';
|
||||
import type OpenAI from 'openai';
|
||||
@@ -89,92 +90,53 @@ export function useAIChatSession({
|
||||
initSession();
|
||||
}, [sessionManager, projectId, projectName, tools, customTools, systemPrompt, maxSteps, generatedSessionId]);
|
||||
|
||||
// Subscribe to session updates
|
||||
useEffect(() => {
|
||||
if (!sessionId) return;
|
||||
// Update session state efficiently
|
||||
const updateSessionState = useCallback((state: SessionState) => {
|
||||
setSessionState({
|
||||
...state,
|
||||
// Only create new arrays/objects when they actually change
|
||||
messages: state.messages.slice(),
|
||||
streamingMessage: state.streamingMessage ? { ...state.streamingMessage } : undefined
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleSessionUpdate = (updatedSessionId: string, state: SessionState) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
// Create a deep copy to ensure React detects the change
|
||||
const newState = {
|
||||
...state,
|
||||
messages: [...state.messages],
|
||||
streamingMessage: state.streamingMessage ? { ...state.streamingMessage } : undefined,
|
||||
abortController: state.abortController
|
||||
};
|
||||
setSessionState(newState);
|
||||
// Subscribe to session events using shared hook
|
||||
useSessionSubscription('sessionUpdated', (updatedSessionId: string, state: SessionState) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
updateSessionState(state);
|
||||
}
|
||||
}, [sessionId, updateSessionState]);
|
||||
|
||||
useSessionSubscription('messageAdded', (updatedSessionId: string, _message: AIMessage) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
updateSessionState(session);
|
||||
}
|
||||
};
|
||||
}
|
||||
}, [sessionId, updateSessionState]);
|
||||
|
||||
const handleMessageAdded = (updatedSessionId: string, _message: AIMessage) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
// Get fresh session state and force update by creating new object
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
// Create a deep copy to ensure React detects the change
|
||||
const newState = {
|
||||
...session,
|
||||
messages: [...session.messages],
|
||||
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined,
|
||||
abortController: session.abortController
|
||||
};
|
||||
setSessionState(newState);
|
||||
}
|
||||
useSessionSubscription('streamingUpdate', (updatedSessionId: string, _content: string, _toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
updateSessionState(session);
|
||||
}
|
||||
};
|
||||
}
|
||||
}, [sessionId, updateSessionState]);
|
||||
|
||||
const handleStreamingUpdate = (updatedSessionId: string, _content: string, _toolCalls?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[]) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
// Get fresh session state and force update by creating new object
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
// Create a deep copy to ensure React detects the change
|
||||
const newState = {
|
||||
...session,
|
||||
messages: [...session.messages],
|
||||
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined,
|
||||
abortController: session.abortController
|
||||
};
|
||||
setSessionState(newState);
|
||||
}
|
||||
useSessionSubscription('loadingChanged', (updatedSessionId: string, isLoading: boolean) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
updateSessionState(session);
|
||||
}
|
||||
};
|
||||
|
||||
const handleLoadingChanged = (updatedSessionId: string, isLoading: boolean) => {
|
||||
if (updatedSessionId === sessionId) {
|
||||
// Update session state immediately and force update by creating new object
|
||||
const session = sessionManager.getSession(sessionId);
|
||||
if (session) {
|
||||
// Create a deep copy to ensure React detects the change
|
||||
const newState = {
|
||||
...session,
|
||||
messages: [...session.messages],
|
||||
streamingMessage: session.streamingMessage ? { ...session.streamingMessage } : undefined,
|
||||
abortController: session.abortController
|
||||
};
|
||||
setSessionState(newState);
|
||||
}
|
||||
|
||||
if (onUpdateMetadata) {
|
||||
if (isLoading) {
|
||||
onUpdateMetadata('Shakespeare', `Working on ${projectName}...`);
|
||||
}
|
||||
}
|
||||
if (onUpdateMetadata && isLoading) {
|
||||
onUpdateMetadata('Shakespeare', `Working on ${projectName}...`);
|
||||
}
|
||||
};
|
||||
|
||||
sessionManager.on('sessionUpdated', handleSessionUpdate);
|
||||
sessionManager.on('messageAdded', handleMessageAdded);
|
||||
sessionManager.on('streamingUpdate', handleStreamingUpdate);
|
||||
sessionManager.on('loadingChanged', handleLoadingChanged);
|
||||
|
||||
return () => {
|
||||
sessionManager.off('sessionUpdated', handleSessionUpdate);
|
||||
sessionManager.off('messageAdded', handleMessageAdded);
|
||||
sessionManager.off('streamingUpdate', handleStreamingUpdate);
|
||||
sessionManager.off('loadingChanged', handleLoadingChanged);
|
||||
};
|
||||
}, [sessionId, sessionManager, onUpdateMetadata, projectName]);
|
||||
}
|
||||
}, [sessionId, updateSessionState, onUpdateMetadata, projectName]);
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useSessionManager } from './useSessionManager';
|
||||
import type { SessionManagerEvents } from '@/lib/SessionManager';
|
||||
|
||||
/**
|
||||
* Custom hook for subscribing to SessionManager events with automatic cleanup
|
||||
*/
|
||||
export function useSessionSubscription<K extends keyof SessionManagerEvents>(
|
||||
event: K,
|
||||
handler: SessionManagerEvents[K],
|
||||
deps: React.DependencyList = []
|
||||
): void {
|
||||
const sessionManager = useSessionManager();
|
||||
|
||||
useEffect(() => {
|
||||
sessionManager.on(event, handler);
|
||||
|
||||
return () => {
|
||||
sessionManager.off(event, handler);
|
||||
};
|
||||
}, [sessionManager, event, handler, ...deps]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
}
|
||||
Reference in new issue
Block a user