useAIChat: infinite while-loop

This commit is contained in:
Alex Gleason committed 2025-08-24 17:03:38 -05:00
1 parent 5875771de3
commit bc0bb5d5a3
1 file changed
+103 -73
+103 -73
View File
@@ -14,6 +14,7 @@ interface UseAIChatOptions {
customTools?: Record<string, { execute: (args: unknown) => Promise<unknown> }>; customTools?: Record<string, { execute: (args: unknown) => Promise<unknown> }>;
systemPrompt?: string; systemPrompt?: string;
onUpdateMetadata?: (title: string, description: string) => void; onUpdateMetadata?: (title: string, description: string) => void;
maxSteps?: number;
} }
export function useAIChat({ export function useAIChat({
@@ -22,7 +23,8 @@ export function useAIChat({
tools = {}, tools = {},
customTools = {}, customTools = {},
systemPrompt, systemPrompt,
onUpdateMetadata onUpdateMetadata,
maxSteps = 50
}: UseAIChatOptions) { }: UseAIChatOptions) {
const [messages, setMessages] = useState<AIMessage[]>([]); const [messages, setMessages] = useState<AIMessage[]>([]);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
@@ -120,102 +122,130 @@ export function useAIChat({
onUpdateMetadata('Shakespeare', `Working on ${projectName}...`); onUpdateMetadata('Shakespeare', `Working on ${projectName}...`);
} }
// Prepare chat completion options // Keep track of current messages for this conversation
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = { const currentMessages = [...modelMessages];
model: settings.model, let stepCount = 0;
messages: modelMessages,
tools: tools ? Object.values(tools) : undefined,
tool_choice: tools && Object.keys(tools).length > 0 ? 'auto' : undefined
};
// Generate response // Main loop for handling multiple steps with tool calls
const completion = await openai.chat.completions.create(completionOptions, { while (stepCount < maxSteps) {
signal: abortControllerRef.current.signal stepCount++;
}); console.log(`AI Chat Step ${stepCount}/${maxSteps}`);
const response = completion.choices[0]; // Prepare chat completion options
if (!response) { const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
throw new Error('No response from AI'); model: settings.model,
} messages: currentMessages,
tools: tools ? Object.values(tools) : undefined,
tool_choice: tools && Object.keys(tools).length > 0 ? 'auto' : undefined
};
const responseMessage = response.message; // Generate response
const completion = await openai.chat.completions.create(completionOptions, {
signal: abortControllerRef.current.signal
});
// Add assistant message const response = completion.choices[0];
const assistantMessage: AIMessage = { if (!response) {
role: 'assistant', throw new Error('No response from AI');
content: responseMessage.content || '', }
...(responseMessage.tool_calls && { tool_calls: responseMessage.tool_calls })
};
addMessage(assistantMessage); const responseMessage = response.message;
// Handle tool calls if present // Add assistant message
if (responseMessage.tool_calls && responseMessage.tool_calls.length > 0) { const assistantMessage: AIMessage = {
for (const toolCall of responseMessage.tool_calls) { role: 'assistant',
if (toolCall.type !== 'function') continue; content: responseMessage.content || '',
...(responseMessage.tool_calls && { tool_calls: responseMessage.tool_calls })
};
const toolName = toolCall.function.name; addMessage(assistantMessage);
let toolArgs; currentMessages.push(assistantMessage);
try { // Check if we should stop (no tool calls or finish reason is "stop")
toolArgs = JSON.parse(toolCall.function.arguments); if (response.finish_reason === 'stop' || !responseMessage.tool_calls || responseMessage.tool_calls.length === 0) {
} catch (parseError) { console.log(`AI Chat completed after ${stepCount} steps. Finish reason: ${response.finish_reason}`);
console.error(`Failed to parse tool arguments for ${toolName}:`, parseError); break;
}
const toolErrorMessage: AIMessage = { // Handle tool calls if present
role: 'tool', if (responseMessage.tool_calls && responseMessage.tool_calls.length > 0) {
content: `Error parsing arguments for tool ${toolName}: ${parseError instanceof Error ? parseError.message : 'Unknown error'}`, console.log(`Processing ${responseMessage.tool_calls.length} tool calls in step ${stepCount}`);
tool_call_id: toolCall.id
};
addMessage(toolErrorMessage); for (const toolCall of responseMessage.tool_calls) {
continue; if (toolCall.type !== 'function') continue;
}
const toolName = toolCall.function.name;
let toolArgs;
// Execute tool if it exists in customTools
if (customTools && customTools[toolName]) {
try { try {
console.log(`Executing tool: ${toolName}`, toolArgs); toolArgs = JSON.parse(toolCall.function.arguments);
} catch (parseError) {
// Execute the custom tool console.error(`Failed to parse tool arguments for ${toolName}:`, parseError);
const tool = customTools[toolName];
const result = await tool.execute(toolArgs);
// Convert result to string
const resultString = typeof result === 'string' ? result : JSON.stringify(result, null, 2);
// Add tool result message
const toolResultMessage: AIMessage = {
role: 'tool',
content: resultString,
tool_call_id: toolCall.id
};
addMessage(toolResultMessage);
} catch (toolError) {
console.error(`Tool execution error for ${toolName}:`, toolError);
const toolErrorMessage: AIMessage = { const toolErrorMessage: AIMessage = {
role: 'tool', role: 'tool',
content: `Error executing tool ${toolName}: ${toolError instanceof Error ? toolError.message : 'Unknown error'}`, content: `Error parsing arguments for tool ${toolName}: ${parseError instanceof Error ? parseError.message : 'Unknown error'}`,
tool_call_id: toolCall.id tool_call_id: toolCall.id
}; };
addMessage(toolErrorMessage); addMessage(toolErrorMessage);
currentMessages.push(toolErrorMessage);
continue;
} }
} else {
// Tool not found
const toolNotFoundMessage: AIMessage = {
role: 'tool',
content: `Tool ${toolName} not found`,
tool_call_id: toolCall.id
};
addMessage(toolNotFoundMessage); // Execute tool if it exists in customTools
if (customTools && customTools[toolName]) {
try {
console.log(`Executing tool: ${toolName}`, toolArgs);
// Execute the custom tool
const tool = customTools[toolName];
const result = await tool.execute(toolArgs);
// Convert result to string
const resultString = typeof result === 'string' ? result : JSON.stringify(result, null, 2);
// Add tool result message
const toolResultMessage: AIMessage = {
role: 'tool',
content: resultString,
tool_call_id: toolCall.id
};
addMessage(toolResultMessage);
currentMessages.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: toolCall.id
};
addMessage(toolErrorMessage);
currentMessages.push(toolErrorMessage);
}
} else {
// Tool not found
const toolNotFoundMessage: AIMessage = {
role: 'tool',
content: `Tool ${toolName} not found`,
tool_call_id: toolCall.id
};
addMessage(toolNotFoundMessage);
currentMessages.push(toolNotFoundMessage);
}
} }
} }
} }
// If we reached maxSteps, log a warning
if (stepCount >= maxSteps) {
console.warn(`AI Chat reached maximum steps (${maxSteps}). Conversation may be incomplete.`);
}
} catch (error) { } catch (error) {
console.error('AI chat error:', error); console.error('AI chat error:', error);
@@ -230,7 +260,7 @@ export function useAIChat({
setIsLoading(false); setIsLoading(false);
abortControllerRef.current = null; abortControllerRef.current = null;
} }
}, [isConfigured, isLoading, addMessage, messages, settings.baseUrl, settings.apiKey, settings.model, tools, customTools, systemPrompt, onUpdateMetadata, projectName]); }, [isConfigured, isLoading, addMessage, messages, settings.baseUrl, settings.apiKey, settings.model, tools, customTools, systemPrompt, onUpdateMetadata, projectName, maxSteps]);
const stopGeneration = useCallback(() => { const stopGeneration = useCallback(() => {
if (abortControllerRef.current) { if (abortControllerRef.current) {