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.

🐛 fix(model-runtime): fix multiple Vertex AI and Moonshot runtime issues (#12595)

YuTengjing8ced872e53fd
diff --git a/packages/model-bank/src/aiModels/vertexai.ts b/packages/model-bank/src/aiModels/vertexai.ts
index 20a6e779ffc..2554a5b173e 100644
--- a/packages/model-bank/src/aiModels/vertexai.ts
+++ b/packages/model-bank/src/aiModels/vertexai.ts
@@ -213,7 +213,7 @@ const vertexaiChatModels: AIChatModelCard[] = [
},
releasedAt: '2025-11-20',
settings: {
- extendParams: ['thinkingBudget'],
+ extendParams: ['imageAspectRatio', 'imageResolution'],
searchImpl: 'params',
searchProvider: 'google',
},
diff --git a/packages/model-runtime/src/core/contextBuilders/google.test.ts b/packages/model-runtime/src/core/contextBuilders/google.test.ts
index 97e820b644e..0e67ac118a9 100644
--- a/packages/model-runtime/src/core/contextBuilders/google.test.ts
+++ b/packages/model-runtime/src/core/contextBuilders/google.test.ts
@@ -911,6 +911,92 @@ describe('google contextBuilders', () => {
]);
});
+ it('should merge consecutive functionResponse contents into a single Content for multi-tool-call turns', async () => {
+ const messages: OpenAIChatMessage[] = [
+ { content: 'What is the weather in London and Tokyo?', role: 'user' },
+ {
+ content: '',
+ role: 'assistant',
+ tool_calls: [
+ {
+ function: {
+ arguments: JSON.stringify({ location: 'London' }),
+ name: 'get_weather',
+ },
+ id: 'call_1',
+ type: 'function',
+ },
+ {
+ function: {
+ arguments: JSON.stringify({ location: 'Tokyo' }),
+ name: 'get_weather',
+ },
+ id: 'call_2',
+ type: 'function',
+ },
+ ],
+ },
+ {
+ content: '{"temperature":"14°C"}',
+ name: 'get_weather',
+ role: 'tool',
+ tool_call_id: 'call_1',
+ },
+ {
+ content: '{"temperature":"22°C"}',
+ name: 'get_weather',
+ role: 'tool',
+ tool_call_id: 'call_2',
+ },
+ ];
+
+ const contents = await buildGoogleMessages(messages);
+
+ // Function calls should be in one Content, function responses merged into one Content
+ expect(contents).toHaveLength(3);
+ expect(contents).toEqual([
+ {
+ parts: [
+ {
+ text: 'What is the weather in London and Tokyo?',
+ thoughtSignature: GEMINI_MAGIC_THOUGHT_SIGNATURE,
+ },
+ ],
+ role: 'user',
+ },
+ {
+ parts: [
+ {
+ functionCall: { args: { location: 'London' }, name: 'get_weather' },
+ thoughtSignature: GEMINI_MAGIC_THOUGHT_SIGNATURE,
+ },
+ {
+ functionCall: { args: { location: 'Tokyo' }, name: 'get_weather' },
+ thoughtSignature: GEMINI_MAGIC_THOUGHT_SIGNATURE,
+ },
+ ],
+ role: 'model',
+ },
+ {
+ parts: [
+ {
+ functionResponse: {
+ name: 'get_weather',
+ response: { result: '{"temperature":"14°C"}' },
+ },
+ },
+ {
+ functionResponse: {
+ name: 'get_weather',
+ response: { result: '{"temperature":"22°C"}' },
+ },
+ },
+ ],
+ role: 'user',
+ },
+ ]);
+ });
+
it('should correctly convert full conversation with thoughtSignature', async () => {
const messages: OpenAIChatMessage[] = [
{ content: 'system prompt', role: 'system' },
@@ -1226,6 +1312,56 @@ describe('google contextBuilders', () => {
type: 'string',
});
});
+
+ it('should strip unsupported JSON Schema keywords like examples and default', () => {
+ const tool: ChatCompletionTool = {
+ function: {
+ description: 'A tool with unsupported schema keywords',
+ name: 'mcp_tool',
+ parameters: {
+ properties: {
+ query: {
+ default: 'hello',
+ description: 'Search query',
+ examples: ['weather in London', 'latest news'],
+ type: 'string',
+ },
+ nested: {
+ properties: {
+ format: {
+ $comment: 'internal note',
+ examples: ['json', 'xml'],
+ type: 'string',
+ },
+ },
+ type: 'object',
+ },
+ },
+ type: 'object',
+ },
+ },
+ type: 'function',
+ };
+
+ const result = buildGoogleTool(tool);
+
+ // examples, default should be stripped; $comment is silently ignored by the API
+ expect(result.parameters?.properties).toEqual({
+ query: {
+ description: 'Search query',
+ type: 'string',
+ },
+ nested: {
+ properties: {
+ format: {
+ $comment: 'internal note',
+ type: 'string',
+ },
+ },
+ type: 'object',
+ },
+ });
+ });
});
describe('buildGoogleTools', () => {
diff --git a/packages/model-runtime/src/core/contextBuilders/google.ts b/packages/model-runtime/src/core/contextBuilders/google.ts
index 9f9aaee9243..105901d68ed 100644
--- a/packages/model-runtime/src/core/contextBuilders/google.ts
+++ b/packages/model-runtime/src/core/contextBuilders/google.ts
@@ -187,10 +187,29 @@ export const buildGoogleMessages = async (messages: OpenAIChatMessage[]): Promis
const contents = await Promise.all(pools);
// Filter out empty messages: contents.parts must not be empty.
- const filteredContents = contents.filter(
+ const nonEmptyContents = contents.filter(
(content: Content) => content.parts && content.parts.length > 0,
);
+ // Merge consecutive functionResponse contents into a single Content.
+ // Vertex AI requires the number of functionResponse parts to equal
+ // the number of functionCall parts in the preceding model turn.
+ const filteredContents: Content[] = [];
+ for (const content of nonEmptyContents) {
+ const isFunctionResponse =
+ content.role === 'user' && content.parts?.every((p) => p.functionResponse);
+
+ const last = filteredContents.at(-1);
+ const lastIsFunctionResponse =
+ last?.role === 'user' && last.parts?.every((p) => p.functionResponse);
+
+ if (isFunctionResponse && lastIsFunctionResponse) {
+ last!.parts = [...(last!.parts || []), ...(content.parts || [])];
+ } else {
+ filteredContents.push(content);
+ }
+ }
+
// Check if the last message is a tool message
const lastMessage = messages.at(-1);
const shouldAddMagicSignature = lastMessage?.role === 'tool';
@@ -226,6 +245,12 @@ export const buildGoogleMessages = async (messages: OpenAIChatMessage[]): Promis
return filteredContents;
};
+/**
+ * JSON Schema keywords that cause Google GenAI / Vertex AI SDK validation errors.
+ * Other unsupported keywords are silently ignored by the API, so only strip these.
+ */
+const UNSUPPORTED_SCHEMA_KEYS = new Set(['examples', 'default']);
+
/**
* Sanitize JSON Schema for Google GenAI compatibility
* Google's API doesn't support certain JSON Schema keywords like 'const'
@@ -242,6 +267,9 @@ const sanitizeSchemaForGoogle = (schema: Record<string, any>): Record<string, an
const result: Record<string, any> = {};
for (const [key, value] of Object.entries(schema)) {
+ // Strip unsupported JSON Schema keywords (e.g. examples, default, $schema)
+ if (UNSUPPORTED_SCHEMA_KEYS.has(key)) continue;
+
// Convert 'const' to 'enum' with single value (Google doesn't support 'const')
if (key === 'const') {
result['enum'] = [value];
diff --git a/packages/model-runtime/src/core/streams/index.ts b/packages/model-runtime/src/core/streams/index.ts
index 07fd65d3ef0..c95e5c9af47 100644
--- a/packages/model-runtime/src/core/streams/index.ts
+++ b/packages/model-runtime/src/core/streams/index.ts
@@ -7,4 +7,3 @@ export * from './openai';
export * from './protocol';
export * from './qwen';
export * from './spark';
-export * from './vertex-ai';
diff --git a/packages/model-runtime/src/core/streams/vertex-ai.test.ts b/packages/model-runtime/src/core/streams/vertex-ai.test.ts
index b0d2a537b29..5f8195e5323 100644
--- a/packages/model-runtime/src/core/streams/vertex-ai.test.ts
+++ b/packages/model-runtime/src/core/streams/vertex-ai.test.ts
@@ -1,9 +1,9 @@
import { describe, expect, it, vi } from 'vitest';
import * as uuidModule from '../../utils/uuid';
-import { VertexAIStream } from './vertex-ai';
+import { GoogleGenerativeAIStream } from './google';
-describe('VertexAIStream', () => {
+describe('GoogleGenerativeAIStream (Vertex AI scenarios)', () => {
it('should transform Vertex AI stream to protocol stream', async () => {
vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');
const rawChunks = [
@@ -101,7 +101,7 @@ describe('VertexAIStream', () => {
const onToolCallMock = vi.fn();
const onCompletionMock = vi.fn();
- const protocolStream = VertexAIStream(mockGoogleStream, {
+ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream, {
callbacks: {
onStart: onStartMock,
onText: onTextMock,
@@ -128,6 +128,11 @@ describe('VertexAIStream', () => {
'id: chat_1\n',
'event: text\n',
`data: "! 😊"\n\n`,
+
+ // requireTerminalEvent: no finishReason → stream parsing error
+ 'id: chat_1\n',
+ 'event: error\n',
+ `data: ${JSON.stringify({ body: { name: 'Stream parsing error', reason: 'unexpected_end' }, message: 'Stream ended unexpectedly', name: 'Stream parsing error', type: 'StreamChunkError' })}\n\n`,
]);
expect(onStartMock).toHaveBeenCalledTimes(1);
@@ -205,7 +210,7 @@ describe('VertexAIStream', () => {
const onToolCallMock = vi.fn();
const onCompletionMock = vi.fn();
- const protocolStream = VertexAIStream(mockGoogleStream, {
+ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream, {
callbacks: {
onStart: onStartMock,
onText: onTextMock,
@@ -299,7 +304,7 @@ describe('VertexAIStream', () => {
},
});
- const protocolStream = VertexAIStream(mockGoogleStream);
+ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
const decoder = new TextDecoder();
const chunks = [];
@@ -377,7 +382,7 @@ describe('VertexAIStream', () => {
},
});
- const protocolStream = VertexAIStream(mockGoogleStream);
+ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
const decoder = new TextDecoder();
const chunks = [];
@@ -388,9 +393,283 @@ describe('VertexAIStream', () => {
}
expect(chunks).toEqual(
- ['id: chat_1', 'event: text', 'data: "234"\n', 'id: chat_1', 'event: text', `data: ""\n`].map(
- (i) => i + '\n',
- ),
+ [
+ 'id: chat_1',
+ 'event: text',
+ 'data: "234"\n',
+ 'id: chat_1',
+ 'event: text',
+ `data: ""\n`,
+ // requireTerminalEvent: no finishReason → stream parsing error
+ 'id: chat_1',
+ 'event: error',
+ `data: ${JSON.stringify({ body: { name: 'Stream parsing error', reason: 'unexpected_end' }, message: 'Stream ended unexpectedly', name: 'Stream parsing error', type: 'StreamChunkError' })}\n`,
+ ].map((i) => i + '\n'),
+ );
+ });
+
+ it('should handle image generation (text + inlineData)', async () => {
+ vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');
+
+ const data = [
+ {
+ candidates: [
+ {
+ content: {
+ parts: [{ text: 'Here is the generated image:' }],
+ role: 'model',
+ },
+ index: 0,
+ },
+ ],
+ usageMetadata: {
+ promptTokenCount: 10,
+ totalTokenCount: 10,
+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 10 }],
+ },
+ modelVersion: 'gemini-3-pro-image-preview',
+ },
+ {
+ candidates: [
+ {
+ content: {
+ parts: [
+ {
+ inlineData: {
+ mimeType: 'image/png',
+ data: 'iVBORw0KGgoAAAANSUhEUg==',
+ },
+ },
+ ],
+ role: 'model',
+ },
+ finishReason: 'STOP',
+ index: 0,
+ },
+ ],
+ usageMetadata: {
+ promptTokenCount: 10,
+ candidatesTokenCount: 1120,
+ totalTokenCount: 1130,
+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 10 }],
+ candidatesTokensDetails: [{ modality: 'IMAGE', tokenCount: 1120 }],
+ },
+ modelVersion: 'gemini-3-pro-image-preview',
+ },
+ ];
+
+ const mockStream = new ReadableStream({
+ start(controller) {
+ data.forEach((item) => controller.enqueue(item));
+ controller.close();
+ },
+ });
+
+ const protocolStream = GoogleGenerativeAIStream(mockStream);
+ const decoder = new TextDecoder();
+ const chunks = [];
+
+ // @ts-ignore
+ for await (const chunk of protocolStream) {
+ chunks.push(decoder.decode(chunk, { stream: true }));
+ }
+
+ expect(chunks).toEqual(
+ [
+ // Gemini 3 model: text-only chunk also uses content_part format
+ 'id: chat_1',
+ 'event: content_part',
+ 'data: {"content":"Here is the generated image:","partType":"text"}\n',
+
+ 'id: chat_1',
+ 'event: content_part',
+ 'data: {"content":"iVBORw0KGgoAAAANSUhEUg==","mimeType":"image/png","partType":"image"}\n',
+
+ 'id: chat_1',
+ 'event: stop',
+ 'data: "STOP"\n',
+
+ 'id: chat_1',
+ 'event: usage',
+ 'data: {"inputTextTokens":10,"outputImageTokens":1120,"outputTextTokens":0,"totalInputTokens":10,"totalOutputTokens":1120,"totalTokens":1130}\n',
+ ].map((i) => i + '\n'),
+ );
+ });
+
+ it('should handle reasoning with image parts', async () => {
+ vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');
+
+ const data = [
+ {
+ candidates: [
+ {
+ content: {
+ parts: [{ text: 'Thinking about the image...', thought: true }],
+ role: 'model',
+ },
+ index: 0,
+ },
+ ],
+ usageMetadata: {
+ promptTokenCount: 5,
+ totalTokenCount: 5,
+ },
+ modelVersion: 'gemini-3-pro-image-preview',
+ },
+ {
+ candidates: [
+ {
+ content: {
+ parts: [
+ {
+ inlineData: { mimeType: 'image/jpeg', data: '/9j/4AAQ==' },
+ thought: true,
+ },
+ ],
+ role: 'model',
+ },
+ index: 0,
+ },
+ ],
+ usageMetadata: {
+ promptTokenCount: 5,
+ totalTokenCount: 5,
+ },
+ modelVersion: 'gemini-3-pro-image-preview',
+ },
+ {
+ candidates: [
+ {
+ content: {
+ parts: [
+ {
+ inlineData: { mimeType: 'image/png', data: 'finalImageData==' },
+ },
+ ],
+ role: 'model',
+ },
+ finishReason: 'STOP',
+ index: 0,
+ },
+ ],
+ usageMetadata: {
+ promptTokenCount: 5,
+ candidatesTokenCount: 1120,
+ totalTokenCount: 1425,
+ candidatesTokensDetails: [{ modality: 'IMAGE', tokenCount: 1120 }],
+ thoughtsTokenCount: 300,
+ },
+ modelVersion: 'gemini-3-pro-image-preview',
+ },
+ ];
+
+ const mockStream = new ReadableStream({
+ start(controller) {
+ data.forEach((item) => controller.enqueue(item));
+ controller.close();
+ },
+ });
+
+ const protocolStream = GoogleGenerativeAIStream(mockStream);
+ const decoder = new TextDecoder();
+ const chunks = [];
+
+ // @ts-ignore
+ for await (const chunk of protocolStream) {
+ chunks.push(decoder.decode(chunk, { stream: true }));
+ }
+
+ expect(chunks).toEqual(
+ [
+ // Reasoning text
+ 'id: chat_1',
+ 'event: reasoning_part',
+ 'data: {"content":"Thinking about the image...","inReasoning":true,"partType":"text"}\n',
+
+ // Reasoning image
+ 'id: chat_1',
+ 'event: reasoning_part',
+ 'data: {"content":"/9j/4AAQ==","inReasoning":true,"mimeType":"image/jpeg","partType":"image"}\n',
+
+ // Content image
+ 'id: chat_1',
+ 'event: content_part',
+ 'data: {"content":"finalImageData==","mimeType":"image/png","partType":"image"}\n',
+
+ // stop + usage
+ 'id: chat_1',
+ 'event: stop',
+ 'data: "STOP"\n',
+
+ 'id: chat_1',
+ 'event: usage',
+ 'data: {"outputImageTokens":1120,"outputReasoningTokens":300,"outputTextTokens":0,"totalInputTokens":5,"totalOutputTokens":1420,"totalTokens":1425}\n',
+ ].map((i) => i + '\n'),
+ );
+ });
+
+ it('should handle mixed text and image in single chunk', async () => {
+ vi.spyOn(uuidModule, 'nanoid').mockReturnValueOnce('1');
+
+ const data = [
+ {
+ candidates: [
+ {
+ content: {
+ parts: [
+ { text: 'Here is your cat picture: ' },
+ { inlineData: { mimeType: 'image/png', data: 'catImageBase64==' } },
+ ],
+ role: 'model',
+ },
+ finishReason: 'STOP',
+ index: 0,
+ },
+ ],
+ usageMetadata: {
+ promptTokenCount: 8,
+ candidatesTokenCount: 1130,
+ totalTokenCount: 1138,
+ candidatesTokensDetails: [{ modality: 'IMAGE', tokenCount: 1120 }],
+ },
+ modelVersion: 'gemini-3-pro-image-preview',
+ },
+ ];
+
+ const mockStream = new ReadableStream({
+ start(controller) {
+ data.forEach((item) => controller.enqueue(item));
+ controller.close();
+ },
+ });
+
+ const protocolStream = GoogleGenerativeAIStream(mockStream);
+ const decoder = new TextDecoder();
+ const chunks = [];
+
+ // @ts-ignore
+ for await (const chunk of protocolStream) {
+ chunks.push(decoder.decode(chunk, { stream: true }));
+ }
+
+ expect(chunks).toEqual(
+ [
+ 'id: chat_1',
+ 'event: content_part',
+ 'data: {"content":"Here is your cat picture: ","partType":"text"}\n',
+
+ 'id: chat_1',
+ 'event: content_part',
+ 'data: {"content":"catImageBase64==","mimeType":"image/png","partType":"image"}\n',
+
+ 'id: chat_1',
+ 'event: stop',
+ 'data: "STOP"\n',
+
+ 'id: chat_1',
+ 'event: usage',
+ 'data: {"outputImageTokens":1120,"outputTextTokens":10,"totalInputTokens":8,"totalOutputTokens":1130,"totalTokens":1138}\n',
+ ].map((i) => i + '\n'),
);
});
@@ -442,7 +721,7 @@ describe('VertexAIStream', () => {
},
});
- const protocolStream = VertexAIStream(mockGoogleStream);
+ const protocolStream = GoogleGenerativeAIStream(mockGoogleStream);
const decoder = new TextDecoder();
const chunks = [];
@@ -453,9 +732,19 @@ describe('VertexAIStream', () => {
}
expect(chunks).toEqual(
- ['id: chat_1', 'event: text', 'data: "234"\n', 'id: chat_1', 'event: stop', `data: ""\n`].map(
- (i) => i + '\n',
- ),
+ [
+ 'id: chat_1',
+ 'event: text',
+ 'data: "234"\n',
+ // empty candidate content → empty text (not stop)
+ 'id: chat_1',
+ 'event: text',
+ `data: ""\n`,
+ // requireTerminalEvent: no finishReason → stream parsing error
+ 'id: chat_1',
+ 'event: error',
+ `data: ${JSON.stringify({ body: { name: 'Stream parsing error', reason: 'unexpected_end' }, message: 'Stream ended unexpectedly', name: 'Stream parsing error', type: 'StreamChunkError' })}\n`,
+ ].map((i) => i + '\n'),
);
});
});
diff --git a/packages/model-runtime/src/core/streams/vertex-ai.ts b/packages/model-runtime/src/core/streams/vertex-ai.ts
deleted file mode 100644
index 1491e16c7a6..00000000000
--- a/packages/model-runtime/src/core/streams/vertex-ai.ts
+++ /dev/null
@@ -1,147 +0,0 @@
-import type { GenerateContentResponse } from '@google/genai';
-import type { GroundingSearch } from '@lobechat/types';
-
-import { nanoid } from '../../utils/uuid';
-import { convertGoogleAIUsage } from '../usageConverters/google-ai';
-import type { GoogleAIStreamOptions } from './google';
-import type { ChatPayloadForTransformStream, StreamContext, StreamProtocolChunk } from './protocol';
-import {
- createCallbacksTransformer,
- createSSEProtocolTransformer,
- createTokenSpeedCalculator,
- generateToolCallId,
-} from './protocol';
-
-const transformVertexAIStream = (
- chunk: GenerateContentResponse,
- context: StreamContext,
- payload?: ChatPayloadForTransformStream,
-): StreamProtocolChunk | StreamProtocolChunk[] => {
- // maybe need another structure to add support for multiple choices
- const candidate = chunk.candidates?.[0];
- const usageMetadata = chunk.usageMetadata;
- const usageChunks: StreamProtocolChunk[] = [];
- if (candidate?.finishReason && usageMetadata) {
- usageChunks.push(
- { data: candidate.finishReason, id: context?.id, type: 'stop' },
- {
- data: convertGoogleAIUsage(usageMetadata, payload?.pricing),
- id: context?.id,
- type: 'usage',
- },
- );
- }
-
- if (
- candidate && // First check if this is reasoning content (thought: true)
- Array.isArray(candidate.content?.parts) &&
- candidate.content.parts.length > 0
- ) {
- for (const part of candidate.content.parts) {
- if (part && part.text && part.thought === true) {
- return { data: part.text, id: context.id, type: 'reasoning' };
- }
- }
- }
-
- if (!candidate) {
- return {
- data: '',
- id: context?.id,
- type: 'text',
- };
- }
-
- if (candidate.content) {
- const part = candidate.content.parts?.[0];
-
- if (part?.functionCall) {
- const functionCall = part.functionCall;
-
- return [
- {
- data: [
- {
- function: {
- arguments: JSON.stringify(functionCall.args),
- name: functionCall.name,
- },
- id: generateToolCallId(0, functionCall.name),
- index: 0,
- type: 'function',
- },
- ],
- id: context?.id,
- type: 'tool_calls',
- },
- ...usageChunks,
- ];
- }
-
- // return the grounding
- const { groundingChunks, webSearchQueries } = candidate.groundingMetadata ?? {};
- if (groundingChunks) {
- return [
- !!part?.text ? { data: part.text, id: context?.id, type: 'text' } : undefined,
- {
- data: {
- citations: groundingChunks?.map((chunk) => ({
- // Google returns a uri processed by Google itself, so it cannot display the real favicon
- // Need to use title as a replacement
- favicon: chunk.web?.title,
- title: chunk.web?.title,
- url: chunk.web?.uri,
- })),
- searchQueries: webSearchQueries,
- } as GroundingSearch,
- id: context.id,
- type: 'grounding',
- },
- ...usageChunks,
- ].filter(Boolean) as StreamProtocolChunk[];
- }
-
- if (candidate.finishReason) {
- if (usageMetadata) {
- return [
- !!part?.text ? { data: part.text, id: context?.id, type: 'text' } : undefined,
- ...usageChunks,
- ].filter(Boolean) as StreamProtocolChunk[];
- }
- return { data: candidate.finishReason, id: context?.id, type: 'stop' };
- }
-
- return {
- data: part?.text,
- id: context?.id,
- type: 'text',
- };
- }
-
- return {
- data: '',
- id: context?.id,
- type: 'stop',
- };
-};
-
-export const VertexAIStream = (
- rawStream: ReadableStream<GenerateContentResponse>,
- { callbacks, inputStartAt, enableStreaming = true, payload }: GoogleAIStreamOptions = {},
-) => {
- const streamStack: StreamContext = { id: 'chat_' + nanoid() };
-
- const transformWithPayload: typeof transformVertexAIStream = (chunk, ctx) =>
- transformVertexAIStream(chunk, ctx, payload);
-
- return rawStream
- .pipeThrough(
- createTokenSpeedCalculator(transformWithPayload, {
- enableStreaming: enableStreaming,
- inputStartAt,
- streamStack,
- }),
- )
- .pipeThrough(createSSEProtocolTransformer((c) => c, streamStack))
- .pipeThrough(createCallbacksTransformer(callbacks));
-};
diff --git a/packages/model-runtime/src/providers/google/index.test.ts b/packages/model-runtime/src/providers/google/index.test.ts
index f0097a8317f..5f08799f841 100644
--- a/packages/model-runtime/src/providers/google/index.test.ts
+++ b/packages/model-runtime/src/providers/google/index.test.ts
@@ -617,7 +617,7 @@ describe('thinkingConfig includeThoughts logic', () => {
expect(config.thinkingConfig?.includeThoughts).toBe(true);
});
- it('should enable thinking for gemini-3-pro-image models', async () => {
+ it('should let API decide thinking for gemini-3-pro-image models without explicit params', async () => {
const mockStreamData = (async function* (): AsyncGenerator<GenerateContentResponse> {})();
vi.spyOn(instance['client'].models, 'generateContentStream').mockResolvedValue(mockStreamData);
@@ -629,7 +629,8 @@ describe('thinkingConfig includeThoughts logic', () => {
const callArgs = (instance['client'].models.generateContentStream as any).mock.calls[0];
const config = callArgs[0].config;
- expect(config.thinkingConfig?.includeThoughts).toBe(true);
+ // Gemini 3 models without explicit thinkingLevel/thinkingBudget → let API decide
+ expect(config.thinkingConfig?.includeThoughts).toBeUndefined();
});
it('should enable thinking for thinking-enabled models', async () => {
@@ -699,4 +700,4 @@ describe('models', () => {
'x-goog-api-key': apiKey,
});
});
-});
\ No newline at end of file
+});
diff --git a/packages/model-runtime/src/providers/google/index.ts b/packages/model-runtime/src/providers/google/index.ts
index 357263eb4b6..48e00daabb9 100644
--- a/packages/model-runtime/src/providers/google/index.ts
+++ b/packages/model-runtime/src/providers/google/index.ts
@@ -9,7 +9,7 @@ import debug from 'debug';
import { type LobeRuntimeAI } from '../../core/BaseAI';
import { buildGoogleMessages, buildGoogleTools } from '../../core/contextBuilders/google';
-import { GoogleGenerativeAIStream, VertexAIStream } from '../../core/streams';
+import { GoogleGenerativeAIStream } from '../../core/streams';
import { LOBE_ERROR_KEY } from '../../core/streams/google';
import {
type ChatCompletionTool,
@@ -233,8 +233,7 @@ export class LobeGoogleAI implements LobeRuntimeAI {
// Convert the response into a friendly text-stream
const pricing = await getModelPricing(model, this.provider);
- const Stream = this.isVertexAi ? VertexAIStream : GoogleGenerativeAIStream;
- const stream = Stream(prod, {
+ const stream = GoogleGenerativeAIStream(prod, {
callbacks: options?.callback,
inputStartAt,
payload: { model, pricing, provider: this.provider },
diff --git a/packages/model-runtime/src/providers/google/thinkingResolver.test.ts b/packages/model-runtime/src/providers/google/thinkingResolver.test.ts
index c9991d25b29..41c76017663 100644
--- a/packages/model-runtime/src/providers/google/thinkingResolver.test.ts
+++ b/packages/model-runtime/src/providers/google/thinkingResolver.test.ts
@@ -238,13 +238,15 @@ describe('thinkingResolver', () => {
describe('gemini-3-pro-preview (the original issue model)', () => {
const model = 'gemini-3-pro-preview';
- it('should not set thinkingBudget by default for Gemini 3 (let API decide)', () => {
+ it('should not set thinkingBudget or includeThoughts by default for Gemini 3 (let API decide)', () => {
const result = resolveGoogleThinkingConfig(model, {});
// For Gemini 3 models, when neither thinkingLevel nor thinkingBudget is set,
- // don't set any thinking params - let API use its default behavior
+ // don't set any thinking params - let API use its default behavior.
+ // includeThoughts must be undefined to avoid Vertex AI error:
+ // "include_thoughts is only enabled when thinking is enabled"
expect(result).toEqual({
- includeThoughts: true,
+ includeThoughts: undefined,
thinkingBudget: undefined,
});
});
@@ -274,12 +276,12 @@ describe('thinkingResolver', () => {
describe('gemini-3-pro-image-preview (thinking-enabled model)', () => {
const model = 'gemini-3-pro-image-preview';
- it('should not set thinkingBudget by default for Gemini 3 (let API decide)', () => {
+ it('should not set thinkingBudget or includeThoughts by default for Gemini 3 (let API decide)', () => {
const result = resolveGoogleThinkingConfig(model, {});
// For Gemini 3 models, don't set thinkingBudget by default
expect(result).toEqual({
- includeThoughts: true,
+ includeThoughts: undefined,
thinkingBudget: undefined,
});
});
@@ -349,12 +351,12 @@ describe('thinkingResolver', () => {
describe('gemini-3-flash (supports thinking and thinkingLevel)', () => {
const model = 'gemini-3-flash';
- it('should not set thinkingBudget by default for Gemini 3 (let API decide)', () => {
+ it('should not set thinkingBudget or includeThoughts by default for Gemini 3 (let API decide)', () => {
const result = resolveGoogleThinkingConfig(model, {});
// For Gemini 3 models, don't set thinkingBudget by default
expect(result).toEqual({
- includeThoughts: true,
+ includeThoughts: undefined,
thinkingBudget: undefined,
});
});
@@ -404,16 +406,29 @@ describe('thinkingResolver', () => {
expect(result.includeThoughts).toBeUndefined();
});
+
+ it('should not enable includeThoughts when thinkingLevel is set but budget defaults to 0', () => {
+ // flash-lite ignores thinkingLevel (not Gemini 3) and defaults to budget=0.
+ // Must not emit includeThoughts:true with thinkingBudget:0 — Vertex AI rejects this.
+ const result = resolveGoogleThinkingConfig(model, { thinkingLevel: 'high' });
+
+ expect(result).toEqual({
+ includeThoughts: undefined,
+ thinkingBudget: 0,
+ });
+ });
});
describe('nano-banana-pro-preview (thinking-enabled model)', () => {
const model = 'nano-banana-pro-preview';
- it('should enable includeThoughts by default', () => {
+ it('should not enable includeThoughts when thinkingBudget is undefined', () => {
const result = resolveGoogleThinkingConfig(model, {});
- // nano-banana-pro is 'other' category, so thinkingBudget is undefined
- expect(result.includeThoughts).toBe(true);
+ // nano-banana-pro is 'other' category, so thinkingBudget is undefined.
+ // Without an actual thinking budget or level, includeThoughts should not be set
+ // to avoid Vertex AI error.
+ expect(result.includeThoughts).toBeUndefined();
});
});
});
diff --git a/packages/model-runtime/src/providers/google/thinkingResolver.ts b/packages/model-runtime/src/providers/google/thinkingResolver.ts
index 3832a5facf1..60b1b055763 100644
--- a/packages/model-runtime/src/providers/google/thinkingResolver.ts
+++ b/packages/model-runtime/src/providers/google/thinkingResolver.ts
@@ -218,7 +218,10 @@ export const resolveGoogleThinkingBudget = (
};
/**
- * Determines if includeThoughts should be enabled
+ * Determines if includeThoughts should be enabled.
+ *
+ * Vertex AI rejects includeThoughts:true when thinking is not actually
+ * enabled, so we must only return true when thinking is genuinely active.
*/
const shouldIncludeThoughts = (
model: string,
@@ -227,19 +230,15 @@ const shouldIncludeThoughts = (
): boolean | undefined => {
const { thinkingBudget, thinkingLevel } = options;
- // Conditions that enable thinking:
- // 1. thinkingBudget is explicitly set (and not 0)
- // 2. thinkingLevel is explicitly set
- // 3. Model is in the thinking-enabled list
- const hasExplicitThinking = !!thinkingBudget || !!thinkingLevel;
- const isThinkingModel = isThinkingEnabledModel(model);
+ // 1. No thinking signal at all → not applicable
+ if (!thinkingBudget && !thinkingLevel && !isThinkingEnabledModel(model)) return undefined;
- // If thinking is requested AND budget is not 0, enable includeThoughts
- if ((hasExplicitThinking || isThinkingModel) && resolvedBudget !== 0) {
- return true;
- }
+ // 2. Budget resolved to a number → active only when non-zero
+ if (typeof resolvedBudget === 'number') return resolvedBudget !== 0 ? true : undefined;
- return undefined;
+ // 3. Budget is undefined (Gemini 3 default / "other" category) →
+ // only thinkingLevel can activate thinking without a numeric budget
+ return thinkingLevel ? true : undefined;
};
/**
diff --git a/packages/model-runtime/src/providers/moonshot/index.test.ts b/packages/model-runtime/src/providers/moonshot/index.test.ts
index 35509b4f5ec..6a52f14ce02 100644
--- a/packages/model-runtime/src/providers/moonshot/index.test.ts
+++ b/packages/model-runtime/src/providers/moonshot/index.test.ts
@@ -1,12 +1,13 @@
// @vitest-environment node
-import OpenAI from 'openai';
-import { Mock, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type OpenAI from 'openai';
+import type { Mock } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
+ anthropicParams,
LobeMoonshotAI,
LobeMoonshotAnthropicAI,
LobeMoonshotOpenAI,
- anthropicParams,
params,
} from './index';
@@ -70,7 +71,7 @@ describe('LobeMoonshotOpenAI', () => {
const getLastRequestPayload = () => {
const calls = ((instance as any).client.chat.completions.create as Mock).mock.calls;
- return calls[calls.length - 1]?.[0];
+ return calls.at(-1)?.[0];
};
beforeEach(() => {
@@ -280,7 +281,7 @@ describe('LobeMoonshotAnthropicAI', () => {
const getLastRequestPayload = () => {
const calls = ((instance as any).client.messages.create as Mock).mock.calls;
- return calls[calls.length - 1]?.[0];
+ return calls.at(-1)?.[0];
};
beforeEach(() => {
@@ -468,12 +469,14 @@ describe('LobeMoonshotAnthropicAI', () => {
(message: any) => message.role === 'assistant',
);
+ // forceThinking adds a text placeholder for empty content
expect(assistantMessage?.content).toEqual([
{ type: 'thinking', thinking: 'My reasoning process' },
+ { type: 'text', text: ' ' },
]);
});
- it('should not add thinking block when reasoning has signature', async () => {
+ it('should add placeholder thinking block when reasoning has signature', async () => {
await instance.chat({
messages: [
{ content: 'Hello', role: 'user' },
@@ -492,8 +495,11 @@ describe('LobeMoonshotAnthropicAI', () => {
(message: any) => message.role === 'assistant',
);
- // Should not have thinking block, just text
- expect(assistantMessage?.content).toBe('Response');
+ // forceThinking: even with invalid reasoning (has signature), a placeholder thinking block is added
+ expect(assistantMessage?.content).toEqual([
+ { type: 'thinking', thinking: ' ' },
+ { type: 'text', text: 'Response' },
+ ]);
});
it('should handle assistant message with tool_calls and reasoning', async () => {
diff --git a/packages/model-runtime/src/providers/moonshot/index.ts b/packages/model-runtime/src/providers/moonshot/index.ts
index 5b9462605d1..b3515e9af0a 100644
--- a/packages/model-runtime/src/providers/moonshot/index.ts
+++ b/packages/model-runtime/src/providers/moonshot/index.ts
@@ -48,32 +48,54 @@ const buildThinkingBlock = (reasoning: any) =>
const toContentArray = (content: any) =>
Array.isArray(content) ? content : [{ text: content, type: 'text' as const }];
-const normalizeMessagesForAnthropic = (messages: ChatStreamPayload['messages']) =>
+/**
+ * Normalize assistant messages for Anthropic format.
+ * When forceThinking is true (kimi-k2.5 with thinking enabled), every assistant
+ * message must carry a thinking block, otherwise Moonshot rejects with:
+ * "thinking is enabled but reasoning_content is missing in assistant tool call message"
+ */
+const normalizeMessagesForAnthropic = (
+ messages: ChatStreamPayload['messages'],
+ forceThinking = false,
+) =>
messages.map((message: any) => {
if (message.role !== 'assistant') return message;
const { reasoning, ...rest } = message;
const thinkingBlock = buildThinkingBlock(reasoning);
+ const effectiveBlock =
+ thinkingBlock || (forceThinking ? { thinking: ' ', type: 'thinking' as const } : null);
if (isEmptyContent(message.content)) {
const placeholder = { text: ' ', type: 'text' as const };
- return { ...rest, content: thinkingBlock ? [thinkingBlock] : [placeholder] };
+ return { ...rest, content: effectiveBlock ? [effectiveBlock, placeholder] : [placeholder] };
}
- if (!thinkingBlock) return rest;
- return { ...rest, content: [thinkingBlock, ...toContentArray(message.content)] };
+ if (!effectiveBlock) return rest;
+ return { ...rest, content: [effectiveBlock, ...toContentArray(message.content)] };
});
-// OpenAI format helpers
-const normalizeMessagesForOpenAI = (messages: ChatStreamPayload['messages']) =>
+/**
+ * Normalize assistant messages for OpenAI format.
+ * When forceReasoning is true (kimi-k2.5 with thinking enabled), every assistant
+ * message must carry reasoning_content (even as empty string), similar to DeepSeek.
+ */
+const normalizeMessagesForOpenAI = (
+ messages: ChatStreamPayload['messages'],
+ forceReasoning = false,
+) =>
messages.map((message: any) => {
if (message.role !== 'assistant') return message;
const { reasoning, ...rest } = message;
const normalized = isEmptyContent(message.content) ? { ...rest, content: ' ' } : rest;
+ const reasoningContent = hasValidReasoning(reasoning) ? reasoning.content : undefined;
- if (hasValidReasoning(reasoning)) {
- return { ...normalized, reasoning_content: reasoning.content };
+ if (forceReasoning) {
+ return { ...normalized, reasoning_content: reasoningContent ?? '' };
+ }
+ if (reasoningContent !== undefined) {
+ return { ...normalized, reasoning_content: reasoningContent };
}
return normalized;
});
@@ -93,17 +115,20 @@ const buildMoonshotAnthropicPayload = async (
)) ??
8192;
+ const isK25 = isKimiK25Model(payload.model);
+ const isThinkingEnabled = isK25 && payload.thinking?.type !== 'disabled';
+
const basePayload = await buildDefaultAnthropicPayload({
...payload,
enabledSearch: false,
max_tokens: resolvedMaxTokens,
- messages: normalizeMessagesForAnthropic(payload.messages),
+ messages: normalizeMessagesForAnthropic(payload.messages, isThinkingEnabled),
});
const tools = appendSearchTool(basePayload.tools, payload.enabledSearch);
const basePayloadWithSearch = { ...basePayload, tools };
- if (!isKimiK25Model(payload.model)) return basePayloadWithSearch;
+ if (!isK25) return basePayloadWithSearch;
const resolvedThinkingBudget = payload.thinking?.budget_tokens
? Math.min(payload.thinking.budget_tokens, resolvedMaxTokens - 1)
@@ -128,12 +153,13 @@ const buildMoonshotOpenAIPayload = (
): OpenAI.ChatCompletionCreateParamsStreaming => {
const { enabledSearch, messages, model, temperature, thinking, tools, ...rest } = payload;
- const normalizedMessages = normalizeMessagesForOpenAI(messages);
+ const isK25 = isKimiK25Model(model);
+ const isThinkingEnabled = isK25 && thinking?.type !== 'disabled';
+ const normalizedMessages = normalizeMessagesForOpenAI(messages, isThinkingEnabled);
const moonshotTools = appendSearchTool(tools, enabledSearch);
- if (isKimiK25Model(model)) {
- const thinkingParam =
- thinking?.type === 'disabled' ? { type: 'disabled' } : { type: 'enabled' };
+ if (isK25) {
+ const thinkingParam = isThinkingEnabled ? { type: 'enabled' } : { type: 'disabled' };
return {
...rest,