Fix tool argument parsing

This commit is contained in:
Alex Gleason committed 2025-08-28 14:33:31 -05:00
1 parent 027c4f4fd2
commit 1b04be3c46
5 files changed
+64 -67

No files matched your search

+3 -3
View File
@@ -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<ChatPaneRef, ChatPaneProps>(({
<div className="p-4 space-y-4">
{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];
+39 -40
View File
@@ -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<string, OpenAI.Chat.Completions.ChatCompletionTool>;
customTools?: Record<string, { execute: (args: unknown) => Promise<unknown> }>;
customTools?: Record<string, Tool<unknown>>;
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);
}
}
}
+21
View File
@@ -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();
}
+1 -1
View File
@@ -3,5 +3,5 @@ import type z from "zod";
export interface Tool<TParams> {
description: string;
inputSchema: z.ZodType<TParams>;
execute(args: TParams): Promise<unknown>;
execute(args: TParams): Promise<string>;
}
-23
View File
@@ -96,27 +96,4 @@ function convertZodField(field: unknown): Record<string, unknown> {
description: fieldObj._def?.description || ''
};
}
}
/**
* Execute a tool with the given arguments
*/
export async function executeTool<TParams>(
tool: Tool<TParams>,
args: unknown
): Promise<string> {
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'}`);
}
}