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): keep Gemini and Kimi structured output typed and working (#21385)

Neko2b7b63c89438
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts
index 3f8a3589dc8..dc126a294f1 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts
@@ -24,6 +24,56 @@ describe('Anthropic generateObject', () => {
);
});
+ it('should use auto tool choice with a tool-use instruction when autoToolChoice is set', async () => {
+ const schemaRequest = await buildAnthropicGenerateObjectRequest(
+ {
+ messages: [
+ { content: 'Be concise.', role: 'system' as const },
+ { content: 'Generate data', role: 'user' as const },
+ ],
+ model: 'kimi-k2.7-code',
+ schema: {
+ name: 'result',
+ schema: { properties: { ok: { type: 'boolean' } }, type: 'object' as const },
+ strict: true,
+ },
+ },
+ { autoToolChoice: true, schemaToolChoice: 'any' },
+ );
+
+ expect(schemaRequest.requestParams.tool_choice).toEqual({ type: 'auto' });
+ expect(schemaRequest.requestParams.system).toEqual([
+ {
+ text: 'Be concise.\n\nYou must respond by calling the `result` tool. Do not reply with plain text.',
+ type: 'text',
+ },
+ ]);
+ // `strict` is only added for Claude models that reject forced tool use
+ expect((schemaRequest.requestParams.tools![0] as any).strict).toBeUndefined();
+
+ const toolsRequest = await buildAnthropicGenerateObjectRequest(
+ {
+ messages: [{ content: 'Generate data', role: 'user' as const }],
+ model: 'kimi-k2.7-code',
+ tools: [
+ {
+ function: { name: 'get_data', parameters: { properties: {}, type: 'object' } },
+ type: 'function',
+ },
+ ],
+ },
+ { autoToolChoice: true },
+ );
+
+ expect(toolsRequest.requestParams.tool_choice).toEqual({ type: 'auto' });
+ expect(toolsRequest.requestParams.system).toEqual([
+ {
+ text: 'You must respond by calling one of the provided tools. Do not reply with plain text.',
+ type: 'text',
+ },
+ ]);
+ });
+
it('should strip trailing assistant messages for models without prefill support', async () => {
const { requestParams } = await buildAnthropicGenerateObjectRequest({
messages: [
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts
index 1870f88029a..52b7efd0aee 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts
@@ -12,6 +12,13 @@ import { withUsageCost } from '../usageConverters/utils/withUsageCost';
const log = debug('lobe-model-runtime:anthropic:generate-object');
export interface AnthropicGenerateObjectConfig {
+ /**
+ * Send `tool_choice: { type: 'auto' }` plus a prompt instruction instead of a
+ * forced tool choice, for endpoints that reject `any` / `tool` in the current
+ * request (for example while thinking is enabled). Unlike the Claude path for
+ * models that reject forced tool use, this does not add `strict` to the tool.
+ */
+ autoToolChoice?: boolean;
maxTokens?: number;
requestModel?: string;
requestParams?: Pick<Anthropic.MessageCreateParamsNonStreaming, 'output_config' | 'thinking'>;
@@ -68,6 +75,7 @@ export const buildAnthropicGenerateObjectRequest = async (
const forcedToolChoiceRejected = [model, config?.requestModel].some(
(id): id is string => !!id && rejectsForcedToolChoice(id),
);
+ const useAutoToolChoice = forcedToolChoiceRejected || !!config?.autoToolChoice;
// With `tool_choice: auto` nothing forces the model to call a tool, so the
// official migration guide asks callers to state the requirement in the prompt.
// Without it the model may answer in plain text and the parser silently returns
@@ -76,8 +84,8 @@ export const buildAnthropicGenerateObjectRequest = async (
let toolUseInstruction: string | undefined;
if (tools) {
finalTools = buildAnthropicTools(tools);
- tool_choice = forcedToolChoiceRejected ? { type: 'auto' } : { type: 'any' };
- if (forcedToolChoiceRejected) {
+ tool_choice = useAutoToolChoice ? { type: 'auto' } : { type: 'any' };
+ if (useAutoToolChoice) {
toolUseInstruction =
'You must respond by calling one of the provided tools. Do not reply with plain text.';
}
@@ -102,12 +110,12 @@ export const buildAnthropicGenerateObjectRequest = async (
finalTools = [tool];
schemaToolName = tool.name;
- tool_choice = forcedToolChoiceRejected
+ tool_choice = useAutoToolChoice
? { type: 'auto' }
: config?.schemaToolChoice === 'any'
? { type: 'any' }
: { name: tool.name, type: 'tool' };
- if (forcedToolChoiceRejected) {
+ if (useAutoToolChoice) {
toolUseInstruction = `You must respond by calling the \`${tool.name}\` tool. Do not reply with plain text.`;
}
} else {
diff --git a/packages/model-runtime/src/providers/google/generateObject.schema.test.ts b/packages/model-runtime/src/providers/google/generateObject.schema.test.ts
new file mode 100644
index 00000000000..5e35a075ff1
--- /dev/null
+++ b/packages/model-runtime/src/providers/google/generateObject.schema.test.ts
@@ -0,0 +1,44 @@
+// @vitest-environment node
+import { Type as SchemaType } from '@google/genai';
+import { describe, expect, it } from 'vitest';
+
+import { convertOpenAISchemaToGoogleSchema } from './generateObject';
+
+// Regression: `anyOf` was dropped and nullable type arrays fell back to STRING,
+// so Gemini returned numbers as strings (e.g. "1" instead of 1).
+describe('convertOpenAISchemaToGoogleSchema nullable schemas', () => {
+ it('should convert a nullable anyOf to the non-null type with nullable', () => {
+ const result = convertOpenAISchemaToGoogleSchema({
+ name: 'test',
+ schema: {
+ properties: {
+ code: { anyOf: [{ enum: ['c0', 'c1'], type: 'string' }, { type: 'null' }] },
+ value: { anyOf: [{ type: 'number' }, { type: 'null' }], description: 'A number' },
+ },
+ required: ['code', 'value'],
+ type: 'object',
+ },
+ });
+
+ expect(result).toEqual({
+ properties: {
+ code: { enum: ['c0', 'c1'], nullable: true, type: SchemaType.STRING },
+ value: { description: 'A number', nullable: true, type: SchemaType.NUMBER },
+ },
+ required: ['code', 'value'],
+ type: SchemaType.OBJECT,
+ });
+ });
+
+ it('should convert a nullable type array to the non-null type with nullable', () => {
+ const result = convertOpenAISchemaToGoogleSchema({
+ name: 'test',
+ schema: {
+ properties: { count: { type: ['integer', 'null'] } },
+ type: 'object',
+ },
+ });
+
+ expect(result.properties.count).toEqual({ nullable: true, type: SchemaType.INTEGER });
+ });
+});
diff --git a/packages/model-runtime/src/providers/google/generateObject.ts b/packages/model-runtime/src/providers/google/generateObject.ts
index 07299bec672..158bb0fae52 100644
--- a/packages/model-runtime/src/providers/google/generateObject.ts
+++ b/packages/model-runtime/src/providers/google/generateObject.ts
@@ -60,15 +60,30 @@ const convertType = (type: string): SchemaType => {
*/
export const convertOpenAISchemaToGoogleSchema = (openAISchema: GenerateObjectSchema): any => {
// Check whether a schema type is (or includes) STRING / OBJECT.
-// Handles both `type: 'string'` and nullable `type: ['string', 'null']`.
-const isStringType = (t: unknown): boolean =>
- typeof t === 'string' ? t === 'string' : Array.isArray(t) && t.includes('string');
-const isObjectType = (t: unknown): boolean =>
- typeof t === 'string' ? t === 'object' : Array.isArray(t) && t.includes('object');
+ // Handles both `type: 'string'` and nullable `type: ['string', 'null']`.
+ const isStringType = (t: unknown): boolean =>
+ typeof t === 'string' ? t === 'string' : Array.isArray(t) && t.includes('string');
+ const isObjectType = (t: unknown): boolean =>
+ typeof t === 'string' ? t === 'object' : Array.isArray(t) && t.includes('object');
-const convertSchema = (schema: any): any => {
+ const convertSchema = (schema: any): any => {
if (!schema) return schema;
+ // Gemini has no `null` type: a nullable union (`anyOf: [X, { type: 'null' }]` or
+ // `type: [X, 'null']`) becomes X with `nullable: true`. Otherwise `anyOf` was dropped and
+ // the node fell back to STRING, so Gemini returned numbers as strings.
+ const { anyOf, ...rest } = schema;
+ const nonNullBranches = anyOf?.filter((branch: any) => branch?.type !== 'null');
+ if (nonNullBranches?.length === 1 && nonNullBranches.length < anyOf.length) {
+ return { ...convertSchema({ ...rest, ...nonNullBranches[0] }), nullable: true };
+ }
+ const nonNullTypes = Array.isArray(schema.type)
+ ? schema.type.filter((type: string) => type !== 'null')
+ : undefined;
+ if (nonNullTypes?.length === 1 && nonNullTypes.length < schema.type.length) {
+ return { ...convertSchema({ ...schema, type: nonNullTypes[0] }), nullable: true };
+ }
+
// convertType handles single string types; for array types (nullable)
// default to STRING which is safe for Gemini Schema proto.
const typeArg: string = Array.isArray(schema.type) ? 'string' : schema.type;
diff --git a/packages/model-runtime/src/providers/moonshot/generateObject.test.ts b/packages/model-runtime/src/providers/moonshot/generateObject.test.ts
new file mode 100644
index 00000000000..95d85f29f28
--- /dev/null
+++ b/packages/model-runtime/src/providers/moonshot/generateObject.test.ts
@@ -0,0 +1,43 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { relaxMoonshotGenerateObjectToolChoice } from './index';
+
+// Kimi rejects forced tool choices while thinking is enabled:
+// "tool_choice 'required' is incompatible with thinking enabled"
+describe('relaxMoonshotGenerateObjectToolChoice', () => {
+ const requestPayload = {
+ messages: [{ content: 'Get the result', role: 'user' }],
+ tool_choice: 'required',
+ };
+
+ it('should use auto tool choice with a tool-use instruction while thinking is enabled', () => {
+ for (const model of ['kimi-k2.7-code', 'kimi-k2.6']) {
+ const result = relaxMoonshotGenerateObjectToolChoice({ messages: [], model }, requestPayload);
+
+ expect(result.tool_choice).toBe('auto');
+ expect(result.messages).toEqual([
+ {
+ content:
+ 'You must respond by calling one of the provided tools. Do not reply with plain text.',
+ role: 'system',
+ },
+ ...requestPayload.messages,
+ ]);
+ }
+ });
+
+ it('should keep the forced tool choice when thinking is disabled or unsupported', () => {
+ const disabled = relaxMoonshotGenerateObjectToolChoice(
+ { messages: [], model: 'kimi-k2.6', thinking: { type: 'disabled' } },
+ requestPayload,
+ );
+ const plain = relaxMoonshotGenerateObjectToolChoice(
+ { messages: [], model: 'moonshot-v1-8k' },
+ requestPayload,
+ );
+
+ expect(disabled).toBe(requestPayload);
+ expect(plain).toBe(requestPayload);
+ });
+});
diff --git a/packages/model-runtime/src/providers/moonshot/index.test.ts b/packages/model-runtime/src/providers/moonshot/index.test.ts
index a1fc60c6d92..d9517489b8a 100644
--- a/packages/model-runtime/src/providers/moonshot/index.test.ts
+++ b/packages/model-runtime/src/providers/moonshot/index.test.ts
@@ -613,7 +613,7 @@ describe('LobeMoonshotAnthropicAI', () => {
});
});
- it('should use any schema tool choice for always-thinking Kimi models', async () => {
+ it('should use auto schema tool choice for always-thinking Kimi models', async () => {
await instance.generateObject({
messages: [{ content: 'Extract the result', role: 'user' }],
model: 'kimi-k3',
@@ -621,11 +621,11 @@ describe('LobeMoonshotAnthropicAI', () => {
});
const payload = getLastRequestPayload();
- expect(payload.tool_choice).toEqual({ type: 'any' });
+ expect(payload.tool_choice).toEqual({ type: 'auto' });
expect(payload.thinking).toBeUndefined();
});
- it('should enable thinking and use any tool choice for Kimi thinking-toggle models', async () => {
+ it('should enable thinking and use auto tool choice for Kimi thinking-toggle models', async () => {
await instance.generateObject({
messages: [{ content: 'Get the result', role: 'user' }],
model: 'kimi-k2.6',
@@ -643,7 +643,7 @@ describe('LobeMoonshotAnthropicAI', () => {
const payload = getLastRequestPayload();
expect(payload.thinking).toEqual({ budget_tokens: 1024, type: 'enabled' });
- expect(payload.tool_choice).toEqual({ type: 'any' });
+ expect(payload.tool_choice).toEqual({ type: 'auto' });
});
it('should explicitly enable thinking for native K2.x models', async () => {
@@ -655,7 +655,7 @@ describe('LobeMoonshotAnthropicAI', () => {
const payload = getLastRequestPayload();
expect(payload.thinking).toEqual({ budget_tokens: 1024, type: 'enabled' });
- expect(payload.tool_choice).toEqual({ type: 'any' });
+ expect(payload.tool_choice).toEqual({ type: 'auto' });
});
it('should normalize assistant history when thinking is enabled', async () => {
diff --git a/packages/model-runtime/src/providers/moonshot/index.ts b/packages/model-runtime/src/providers/moonshot/index.ts
index 0155af01d54..401930fc797 100644
--- a/packages/model-runtime/src/providers/moonshot/index.ts
+++ b/packages/model-runtime/src/providers/moonshot/index.ts
@@ -361,9 +361,10 @@ const buildMoonshotOpenAIPayload = (
};
/**
- * Kimi's Anthropic-compatible endpoint maps forced tool choices to `specified`,
- * which is incompatible with thinking mode, but accepts `{ type: "any" }`.
- * With a single schema tool this still forces structured output.
+ * Kimi rejects every forced tool choice (`tool` and `any`) while thinking is enabled
+ * (`tool_choice 'required' is incompatible with thinking enabled`), and native thinking
+ * models cannot turn thinking off, so thinking-enabled requests use `tool_choice: auto`
+ * with a prompt instruction to call the schema tool.
* K2.x thinking models also require an explicit `thinking` parameter on this
* endpoint, while K3+ uses `reasoning_effort` and must omit it.
* Thinking-enabled assistant history must use the same placeholder-block
@@ -384,7 +385,6 @@ const createMoonshotAnthropicGenerateObject = async (
const isThinkingDisabled = isThinkingToggle && thinking?.type === 'disabled';
const isThinkingModel = isNativeThinking || isThinkingToggle;
const isThinkingEnabled = isThinkingModel && !isThinkingDisabled;
- const schemaToolChoice = isThinkingDisabled ? 'tool' : 'any';
const thinkingParam = isThinkingDisabled
? ({ type: 'disabled' } as const)
: isThinkingEnabled && !isKimiReasoningEffortModel(payload.model)
@@ -416,7 +416,7 @@ const createMoonshotAnthropicGenerateObject = async (
},
}
: {}),
- ...(isThinkingModel ? { schemaToolChoice } : {}),
+ ...(isThinkingEnabled ? { autoToolChoice: true } : {}),
});
};
@@ -458,6 +458,36 @@ export const anthropicParams = createAnthropicCompatibleParams({
export const LobeMoonshotAnthropicAI = createAnthropicCompatibleRuntime(anthropicParams);
+/**
+ * Kimi's OpenAI-compatible endpoint rejects `tool_choice: 'required'` (or a named tool) while
+ * thinking is enabled, so tool-based structured output falls back to `auto` plus a prompt
+ * instruction, as on the Anthropic-compatible endpoint.
+ */
+export const relaxMoonshotGenerateObjectToolChoice = (
+ payload: GenerateObjectPayload,
+ requestPayload: any,
+) => {
+ const { model, thinking } = payload;
+ const isThinkingEnabled =
+ isKimiNativeThinkingModel(model) ||
+ (isKimiThinkingToggleModel(model) && thinking?.type !== 'disabled');
+ if (!isThinkingEnabled || !requestPayload.tool_choice || requestPayload.tool_choice === 'auto')
+ return requestPayload;
+
+ return {
+ ...requestPayload,
+ messages: [
+ {
+ content:
+ 'You must respond by calling one of the provided tools. Do not reply with plain text.',
+ role: 'system',
+ },
+ ...requestPayload.messages,
+ ],
+ tool_choice: 'auto',
+ };
+};
+
/**
* Moonshot OpenAI format runtime
*/
@@ -470,6 +500,7 @@ export const LobeMoonshotOpenAI = createOpenAICompatibleRuntime({
debug: {
chatCompletion: () => process.env.DEBUG_MOONSHOT_CHAT_COMPLETION === '1',
},
+ generateObject: { handlePayload: relaxMoonshotGenerateObjectToolChoice },
// Kimi models support prompt_cache_key for multi-turn session cache optimization.
// Docs: https://platform.kimi.com/docs/api/chat#body-one-of-0-prompt-cache-key
models: fetchMoonshotModels,