Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

:bug: fix: fix gemini 3 pro parallel tool use

arvinxxa0cc9c335490
diff --git a/packages/builtin-tool-gtd/src/manifest.ts b/packages/builtin-tool-gtd/src/manifest.ts
index daaab78674d..3921ea92a34 100644
--- a/packages/builtin-tool-gtd/src/manifest.ts
+++ b/packages/builtin-tool-gtd/src/manifest.ts
@@ -13,7 +13,7 @@ export const GTDManifest: BuiltinToolManifest = {
description:
'Create a high-level plan document. Plans define the strategic direction (the "what" and "why"), while todos handle the actionable steps.',
name: GTDApiName.createPlan,
- humanIntervention: 'always',
+ humanIntervention: 'required',
renderDisplayControl: 'alwaysExpand',
parameters: {
properties: {
diff --git a/packages/model-runtime/src/core/streams/google/google-ai.test.ts b/packages/model-runtime/src/core/streams/google/google-ai.test.ts
index 1cfd215f893..54c1fd58c58 100644
--- a/packages/model-runtime/src/core/streams/google/google-ai.test.ts
+++ b/packages/model-runtime/src/core/streams/google/google-ai.test.ts
@@ -1083,6 +1083,177 @@ describe('GoogleGenerativeAIStream', () => {
);
});
+ it('should handle sequential tool calls with thinking in separate chunks', async () => {
+ // This test simulates a real-world scenario where Gemini returns:
+ // 1. Multiple thinking chunks (thought: true)
+ // 2. First tool call in one chunk
+ // 3. Second tool call in another chunk
+ // 4. Final empty text with finishReason
+ // Each tool call should be treated as a separate call, not concatenated
+ vi.spyOn(uuidModule, 'nanoid')
+ .mockReturnValueOnce('test')
+ .mockReturnValueOnce('tool_id_1')
+ .mockReturnValueOnce('tool_id_2');
+
+ const data = [
+ // Chunk 0-3: Thinking chunks (omitted for brevity, just showing final chunks)
+ {
+ candidates: [
+ {
+ content: {
+ parts: [
+ {
+ text: '**Planning the Solution**\n\nI\'m solidifying my plan...',
+ thought: true,
+ },
+ ],
+ role: 'model',
+ },
+ index: 0,
+ },
+ ],
+ modelVersion: 'gemini-3-pro-preview',
+ responseId: 'JMxUadDKN8KMjMcPk-LP4Qw',
+ usageMetadata: {
+ promptTokenCount: 10250,
+ totalTokenCount: 10250,
+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 10250 }],
+ },
+ },
+ // Chunk 4: First tool call (createPlan)
+ {
+ candidates: [
+ {
+ content: {
+ parts: [
+ {
+ functionCall: {
+ name: 'lobe-gtd____createPlan____builtin',
+ args: {
+ goal: 'Fix Linear API Argument Validation Error',
+ description: 'Investigate the Linear API error.',
+ context: 'The user is encountering a validation error.',
+ },
+ },
+ thoughtSignature: 'EoIYCv8XAXLI2nx+C18votz5l0A...',
+ },
+ ],
+ role: 'model',
+ },
+ index: 0,
+ },
+ ],
+ modelVersion: 'gemini-3-pro-preview',
+ responseId: 'JMxUadDKN8KMjMcPk-LP4Qw',
+ usageMetadata: {
+ promptTokenCount: 10250,
+ candidatesTokenCount: 131,
+ totalTokenCount: 11111,
+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 10250 }],
+ thoughtsTokenCount: 730,
+ },
+ },
+ // Chunk 5: Second tool call (createTodos) - different function, same streaming response
+ {
+ candidates: [
+ {
+ content: {
+ parts: [
+ {
+ functionCall: {
+ name: 'lobe-gtd____createTodos____builtin',
+ args: {
+ adds: [
+ 'Verify Linear GraphQL API requirements',
+ 'Determine if code needs to look up Team UUID',
+ 'Provide corrected code',
+ ],
+ },
+ },
+ },
+ ],
+ role: 'model',
+ },
+ index: 0,
+ },
+ ],
+ modelVersion: 'gemini-3-pro-preview',
+ responseId: 'JMxUadDKN8KMjMcPk-LP4Qw',
+ usageMetadata: {
+ promptTokenCount: 10250,
+ candidatesTokenCount: 213,
+ totalTokenCount: 11193,
+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 10250 }],
+ thoughtsTokenCount: 730,
+ },
+ },
+ // Chunk 6: Empty text with finishReason
+ {
+ candidates: [
+ {
+ content: {
+ parts: [{ text: '' }],
+ role: 'model',
+ },
+ finishReason: 'STOP',
+ index: 0,
+ },
+ ],
+ modelVersion: 'gemini-3-pro-preview',
+ responseId: 'JMxUadDKN8KMjMcPk-LP4Qw',
+ usageMetadata: {
+ promptTokenCount: 10250,
+ candidatesTokenCount: 213,
+ totalTokenCount: 11193,
+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 10250 }],
+ thoughtsTokenCount: 730,
+ },
+ },
+ ];
+
+ const mockGoogleStream = new ReadableStream({
+ start(controller) {
+ data.forEach((item) => {
+ controller.enqueue(item);
+ });
+ controller.close();
+ },
+ });
+
+ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
+
+ const chunks = await decodeStreamChunks(protocolStream);
+
+ // Verify the output contains two separate tool_calls events
+ expect(chunks).toEqual(
+ [
+ // Thinking chunk
+ 'id: chat_test',
+ 'event: reasoning_part',
+ 'data: {"content":"**Planning the Solution**\\n\\nI\'m solidifying my plan...","inReasoning":true,"partType":"text"}\n',
+
+ // First tool call (createPlan)
+ 'id: chat_test',
+ 'event: tool_calls',
+ 'data: [{"function":{"arguments":"{\\"goal\\":\\"Fix Linear API Argument Validation Error\\",\\"description\\":\\"Investigate the Linear API error.\\",\\"context\\":\\"The user is encountering a validation error.\\"}","name":"lobe-gtd____createPlan____builtin"},"id":"lobe-gtd____createPlan____builtin_0_tool_id_1","index":0,"thoughtSignature":"EoIYCv8XAXLI2nx+C18votz5l0A...","type":"function"}]\n',
+
+ // Second tool call (createTodos) - should be a SEPARATE event with index:0
+ 'id: chat_test',
+ 'event: tool_calls',
+ 'data: [{"function":{"arguments":"{\\"adds\\":[\\"Verify Linear GraphQL API requirements\\",\\"Determine if code needs to look up Team UUID\\",\\"Provide corrected code\\"]}","name":"lobe-gtd____createTodos____builtin"},"id":"lobe-gtd____createTodos____builtin_0_tool_id_2","index":0,"type":"function"}]\n',
+
+ // Stop and usage
+ 'id: chat_test',
+ 'event: stop',
+ 'data: "STOP"\n',
+
+ 'id: chat_test',
+ 'event: usage',
+ 'data: {"inputTextTokens":10250,"outputImageTokens":0,"outputReasoningTokens":730,"outputTextTokens":213,"totalInputTokens":10250,"totalOutputTokens":943,"totalTokens":11193}\n',
+ ].map((i) => i + '\n'),
+ );
+ });
+
it('should handle thoughtSignature with empty text', async () => {
vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');
diff --git a/packages/model-runtime/src/helpers/parseToolCalls.test.ts b/packages/model-runtime/src/helpers/parseToolCalls.test.ts
index d255683cb3a..9089228c2c7 100644
--- a/packages/model-runtime/src/helpers/parseToolCalls.test.ts
+++ b/packages/model-runtime/src/helpers/parseToolCalls.test.ts
@@ -92,6 +92,77 @@ describe('parseToolCalls', () => {
]);
});
+ it('should handle parallel tool calls with same index but different ids (Gemini behavior)', () => {
+ // This tests the scenario where Gemini sends multiple tool calls in separate chunks
+ // with the same index: 0 but different ids
+ const origin = [
+ {
+ id: 'get_temperature_0_abc123',
+ type: 'function',
+ function: { name: 'get_temperature', arguments: '{"location":"Paris"}' },
+ },
+ ];
+
+ // Second tool call comes with same index: 0 but different id
+ const chunk = [
+ {
+ index: 0,
+ id: 'get_temperature_0_def456',
+ type: 'function',
+ function: { name: 'get_temperature', arguments: '{"location":"London"}' },
+ },
+ ];
+
+ const result = parseToolCalls(origin, chunk);
+
+ // Should create a new tool call instead of concatenating arguments
+ expect(result).toEqual([
+ {
+ id: 'get_temperature_0_abc123',
+ type: 'function',
+ function: { name: 'get_temperature', arguments: '{"location":"Paris"}' },
+ },
+ {
+ id: 'get_temperature_0_def456',
+ type: 'function',
+ function: { name: 'get_temperature', arguments: '{"location":"London"}' },
+ },
+ ]);
+
+ // Verify arguments are NOT concatenated (the bug we're fixing)
+ expect(result[0].function.arguments).not.toContain('London');
+ expect(result[1].function.arguments).not.toContain('Paris');
+ });
+
+ it('should merge arguments when same id appears in subsequent chunks', () => {
+ const origin = [
+ {
+ id: 'tool_1',
+ type: 'function',
+ function: { name: 'func', arguments: '{"ke' },
+ },
+ ];
+
+ // Same id in subsequent chunk - should merge arguments
+ const chunk = [
+ {
+ index: 0,
+ id: 'tool_1',
+ function: { arguments: 'y":"value"}' },
+ },
+ ];
+
+ const result = parseToolCalls(origin, chunk);
+
+ expect(result).toEqual([
+ {
+ id: 'tool_1',
+ type: 'function',
+ function: { name: 'func', arguments: '{"key":"value"}' },
+ },
+ ]);
+ });
+
it('should throw error if incomplete tool calls data', () => {
const origin = [
{
diff --git a/packages/model-runtime/src/helpers/parseToolCalls.ts b/packages/model-runtime/src/helpers/parseToolCalls.ts
index cdf175e2579..77fbff59df5 100644
--- a/packages/model-runtime/src/helpers/parseToolCalls.ts
+++ b/packages/model-runtime/src/helpers/parseToolCalls.ts
@@ -11,11 +11,23 @@ export const parseToolCalls = (origin: MessageToolCall[], value: MessageToolCall
// if there is origin, we should merge the value to the origin
value.forEach(({ index, ...item }) => {
- if (!draft?.[index]) {
- // if not, we should insert it to the draft
+ // First, try to find existing tool call by id (more reliable than index for parallel tool calls)
+ const existingByIdIndex = item.id ? draft.findIndex((d) => d.id === item.id) : -1;
+
+ if (existingByIdIndex !== -1) {
+ // Found existing tool call with same id - merge arguments
+ if (item.function?.arguments) {
+ draft[existingByIdIndex].function.arguments += item.function.arguments;
+ }
+ } else if (!draft?.[index]) {
+ // No item at this index - insert new tool call
draft?.splice(index, 0, MessageToolCallSchema.parse(item));
+ } else if (item.id && draft[index].id !== item.id) {
+ // Different id at same index - this is a new parallel tool call (e.g., from Gemini)
+ // Push to end of draft instead of overwriting
+ draft.push(MessageToolCallSchema.parse(item));
} else {
- // if it is already in the draft, we should merge the arguments to the draft
+ // Same index and same id (or no id) - merge arguments
if (item.function?.arguments) {
draft[index].function.arguments += item.function.arguments;
}