From 9c55040e47e76af8b7e2864b82fa30505545dcb5 Mon Sep 17 00:00:00 2001 From: centdix <40307056+centdix@users.noreply.github.com> Date: Thu, 1 May 2025 15:36:22 +0200 Subject: [PATCH] fix: Ai Chat: do not send tools if empty + respond even if tool fails (#5692) * do not send tools if empty * respond to user request even if tool call fails * remove test line * add missing await --- .../src/lib/components/copilot/chat/core.ts | 43 +++++++++++-------- frontend/src/lib/components/copilot/lib.ts | 2 +- 2 files changed, 27 insertions(+), 18 deletions(-) diff --git a/frontend/src/lib/components/copilot/chat/core.ts b/frontend/src/lib/components/copilot/chat/core.ts index ee0b67c710..990c4489e2 100644 --- a/frontend/src/lib/components/copilot/chat/core.ts +++ b/frontend/src/lib/components/copilot/chat/core.ts @@ -487,6 +487,31 @@ async function callTool( } } +async function processToolCall( + toolCall: ChatCompletionMessageToolCall, + messages: ChatCompletionMessageParam[], + lang: ScriptLang | 'bunnative' +) { + try { + const args = JSON.parse(toolCall.function.arguments) + let result = '' + try { + result = await callTool(toolCall.function.name, args, lang, get(workspaceStore) ?? '') + } catch (err) { + console.error(err) + result = + 'Error while calling tool, MUST tell the user to check the browser console for more details, and then respond as much as possible to the original request' + } + messages.push({ + role: 'tool', + tool_call_id: toolCall.id, + content: result + }) + } catch (err) { + console.error(err) + } +} + export async function chatRequest( messages: ChatCompletionMessageParam[], abortController: AbortController, @@ -554,23 +579,7 @@ export async function chatRequest( tool_calls: toolCalls }) for (const toolCall of toolCalls) { - try { - const args = JSON.parse(toolCall.function.arguments) - const result = await callTool( - toolCall.function.name, - args, - lang, - get(workspaceStore) ?? '' - ) - messages.push({ - role: 'tool', - tool_call_id: toolCall.id, - content: result - }) - } catch (err) { - console.error(err) - throw new Error('Error while calling tool') - } + await processToolCall(toolCall, messages, lang) } } else { break diff --git a/frontend/src/lib/components/copilot/lib.ts b/frontend/src/lib/components/copilot/lib.ts index a55361a51a..d11e160fcf 100644 --- a/frontend/src/lib/components/copilot/lib.ts +++ b/frontend/src/lib/components/copilot/lib.ts @@ -385,7 +385,7 @@ function getProviderAndCompletionConfig({ : { model: modelProvider.model, temperature: 0, - tools + ...(tools && tools.length > 0 ? { tools } : {}) }), max_tokens: getModelMaxTokens(modelProvider.model), messages: processedMessages,