From 1b04be3c46fedefef2f9d9c9fa097f6385c5d0e9 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 28 Aug 2025 14:33:31 -0500 Subject: [PATCH] Fix tool argument parsing --- src/components/Shakespeare/ChatPane.tsx | 6 +- src/hooks/useAIChat.ts | 79 ++++++++++++------------- src/lib/ai-messages.ts | 21 +++++++ src/lib/tools/Tool.ts | 2 +- src/lib/tools/openai-adapter.ts | 23 ------- 5 files changed, 64 insertions(+), 67 deletions(-) create mode 100644 src/lib/ai-messages.ts diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 0a798aa4..ed526e2f 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -32,7 +32,7 @@ import { toolToOpenAI } from '@/lib/tools/openai-adapter'; import { Tool } from '@/lib/tools/Tool'; import OpenAI from 'openai'; import { makeSystemPrompt } from '@/lib/system'; - +import { assistantContentEmpty } from '@/lib/ai-messages'; interface ChatPaneProps { projectId: string; @@ -281,13 +281,13 @@ export const ChatPane = forwardRef(({
{messages.map((message, index) => { // Skip assistant messages with no content - if (message.role === 'assistant' && !message.content) { + if (message.role === 'assistant' && assistantContentEmpty(message.content)) { return null; } // Find the corresponding tool call for tool messages let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined; - if (message.role === 'tool' && 'tool_call_id' in message) { + if (message.role === 'tool') { // Look backwards to find the assistant message with matching tool call for (let i = index - 1; i >= 0; i--) { const prevMessage = messages[i]; diff --git a/src/hooks/useAIChat.ts b/src/hooks/useAIChat.ts index 6725bf34..ca195032 100644 --- a/src/hooks/useAIChat.ts +++ b/src/hooks/useAIChat.ts @@ -4,6 +4,7 @@ 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; @@ -18,7 +19,7 @@ interface UseAIChatOptions { projectId: string; projectName: string; tools?: Record; - customTools?: Record Promise }>; + customTools?: Record>; systemPrompt?: string; onUpdateMetadata?: (title: string, description: string) => void; maxSteps?: number; @@ -234,10 +235,25 @@ export function useAIChat({ const functionToolCall = toolCall as OpenAI.Chat.Completions.ChatCompletionMessageFunctionToolCall; const toolName = functionToolCall.function.name; - let toolArgs; + 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 { - toolArgs = JSON.parse(functionToolCall.function.arguments); + const json = JSON.parse(functionToolCall.function.arguments); + toolArgs = tool.inputSchema.parse(json); } catch (parseError) { console.error(`Failed to parse tool arguments for ${toolName}:`, parseError); @@ -252,49 +268,32 @@ export function useAIChat({ continue; } - // Execute tool if it exists in customTools - if (customTools && customTools[toolName]) { - try { - console.log(`Executing tool: ${toolName}`, toolArgs); + try { + console.log(`Executing tool: ${toolName}`, toolArgs); - // Execute the custom tool - const tool = customTools[toolName]; - const result = await tool.execute(toolArgs); + // Execute the custom tool + const content = 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: 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); - } - } else { - // Tool not found - const toolNotFoundMessage: AIMessage = { + // Add tool result message + const toolResultMessage: AIMessage = { role: 'tool', - content: `Tool ${toolName} not found`, + content, tool_call_id: functionToolCall.id }; - addMessage(toolNotFoundMessage); - conversationMessages.push(toolNotFoundMessage); + 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); } } } diff --git a/src/lib/ai-messages.ts b/src/lib/ai-messages.ts new file mode 100644 index 00000000..a9142e4b --- /dev/null +++ b/src/lib/ai-messages.ts @@ -0,0 +1,21 @@ +import OpenAI from "openai"; + +export function assistantContentEmpty( + content: OpenAI.ChatCompletionAssistantMessageParam['content'], +): boolean { + if (!content) return true; + const text: string[] = []; + + if (typeof content === 'string') { + text.push(content); + } else if (Array.isArray(content)) { + for (const part of content) { + if (part.type === 'text') { + text.push(part.text); + } + } + } + + const result = text.join('\n\n'); + return !result.trim(); +} \ No newline at end of file diff --git a/src/lib/tools/Tool.ts b/src/lib/tools/Tool.ts index cbb208e5..451c87af 100644 --- a/src/lib/tools/Tool.ts +++ b/src/lib/tools/Tool.ts @@ -3,5 +3,5 @@ import type z from "zod"; export interface Tool { description: string; inputSchema: z.ZodType; - execute(args: TParams): Promise; + execute(args: TParams): Promise; } diff --git a/src/lib/tools/openai-adapter.ts b/src/lib/tools/openai-adapter.ts index d4a0b398..acdab324 100644 --- a/src/lib/tools/openai-adapter.ts +++ b/src/lib/tools/openai-adapter.ts @@ -96,27 +96,4 @@ function convertZodField(field: unknown): Record { description: fieldObj._def?.description || '' }; } -} - -/** - * Execute a tool with the given arguments - */ -export async function executeTool( - tool: Tool, - args: unknown -): Promise { - try { - // Parse and validate arguments using the tool's schema - const validatedArgs = tool.inputSchema.parse(args); - const result = await tool.execute(validatedArgs); - - // Convert result to string for the AI - if (typeof result === 'string') { - return result; - } - - return JSON.stringify(result, null, 2); - } catch (error) { - throw new Error(`Tool execution failed: ${error instanceof Error ? error.message : 'Unknown error'}`); - } } \ No newline at end of file