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(moonshot): support structured output with thinking (#17729)

YuTengjingda14aeb125a6
diff --git a/packages/model-runtime/src/providers/moonshot/index.test.ts b/packages/model-runtime/src/providers/moonshot/index.test.ts
index b6e8c28b0d5..9d0c6b55792 100644
--- a/packages/model-runtime/src/providers/moonshot/index.test.ts
+++ b/packages/model-runtime/src/providers/moonshot/index.test.ts
@@ -664,6 +664,106 @@ describe('LobeMoonshotAnthropicAI', () => {
});
});
+ describe('generateObject', () => {
+ const schema = {
+ name: 'extract_result',
+ schema: {
+ properties: { result: { type: 'string' as const } },
+ required: ['result'],
+ type: 'object' as const,
+ },
+ };
+
+ beforeEach(() => {
+ ((instance as any).client.messages.create as Mock).mockResolvedValue({
+ content: [{ input: { result: 'ok' }, name: 'extract_result', type: 'tool_use' }],
+ });
+ });
+
+ it('should use any schema tool choice for always-thinking Kimi models', async () => {
+ await instance.generateObject({
+ messages: [{ content: 'Extract the result', role: 'user' }],
+ model: 'kimi-k3',
+ schema,
+ });
+
+ const payload = getLastRequestPayload();
+ expect(payload.tool_choice).toEqual({ type: 'any' });
+ expect(payload.thinking).toBeUndefined();
+ });
+
+ it('should enable thinking and use any tool choice for Kimi thinking-toggle models', async () => {
+ await instance.generateObject({
+ messages: [{ content: 'Get the result', role: 'user' }],
+ model: 'kimi-k2.6',
+ tools: [
+ {
+ function: {
+ description: 'Get a result',
+ name: 'get_result',
+ parameters: { properties: {}, type: 'object' },
+ },
+ type: 'function',
+ },
+ ],
+ });
+
+ const payload = getLastRequestPayload();
+ expect(payload.thinking).toEqual({ budget_tokens: 1024, type: 'enabled' });
+ expect(payload.tool_choice).toEqual({ type: 'any' });
+ });
+
+ it('should explicitly enable thinking for native K2.x models', async () => {
+ await instance.generateObject({
+ messages: [{ content: 'Extract the result', role: 'user' }],
+ model: 'kimi-k2.7-code',
+ schema,
+ });
+
+ const payload = getLastRequestPayload();
+ expect(payload.thinking).toEqual({ budget_tokens: 1024, type: 'enabled' });
+ expect(payload.tool_choice).toEqual({ type: 'any' });
+ });
+
+ it('should normalize assistant history when thinking is enabled', async () => {
+ await instance.generateObject({
+ messages: [
+ { content: 'Initial question', role: 'user' },
+ { content: 'Previous answer', role: 'assistant' },
+ { content: 'Extract the result', role: 'user' },
+ ],
+ model: 'kimi-k2.7-code',
+ schema,
+ });
+
+ const payload = getLastRequestPayload();
+ expect(payload.messages).toEqual([
+ { content: 'Initial question', role: 'user' },
+ {
+ content: [
+ { thinking: ' ', type: 'thinking' },
+ { text: 'Previous answer', type: 'text' },
+ ],
+ role: 'assistant',
+ },
+ { content: 'Extract the result', role: 'user' },
+ ]);
+ });
+
+ it('should preserve forced schema tool choice when Kimi thinking is disabled', async () => {
+ await instance.generateObject({
+ messages: [{ content: 'Extract the result', role: 'user' }],
+ model: 'kimi-k2.6',
+ schema,
+ thinking: { budget_tokens: 0, type: 'disabled' },
+ });
+
+ const payload = getLastRequestPayload();
+ expect(payload.thinking).toEqual({ type: 'disabled' });
+ expect(payload.tool_choice).toEqual({ name: 'extract_result', type: 'tool' });
+ });
+ });
+
describe('handlePayload', () => {
describe('empty assistant messages', () => {
it('should replace empty string assistant message with a space', async () => {
diff --git a/packages/model-runtime/src/providers/moonshot/index.ts b/packages/model-runtime/src/providers/moonshot/index.ts
index c9573039680..2910e9eb70e 100644
--- a/packages/model-runtime/src/providers/moonshot/index.ts
+++ b/packages/model-runtime/src/providers/moonshot/index.ts
@@ -1,5 +1,6 @@
import type Anthropic from '@anthropic-ai/sdk';
import type { ChatModelCard } from '@lobechat/types';
+import type { Pricing } from 'model-bank';
import { ModelProvider } from 'model-bank';
import type OpenAI from 'openai';
@@ -8,10 +9,12 @@ import {
createAnthropicCompatibleParams,
createAnthropicCompatibleRuntime,
} from '../../core/anthropicCompatibleFactory';
+import type { AnthropicGenerateObjectConfig } from '../../core/anthropicCompatibleFactory/generateObject';
+import { createAnthropicGenerateObject } from '../../core/anthropicCompatibleFactory/generateObject';
import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';
import type { CreateRouterRuntimeOptions } from '../../core/RouterRuntime';
import { createRouterRuntime } from '../../core/RouterRuntime';
-import type { ChatStreamPayload } from '../../types';
+import type { ChatStreamPayload, GenerateObjectOptions, GenerateObjectPayload } from '../../types';
import { getModelPropertyWithFallback } from '../../utils/getFallbackModelProperty';
import { MODEL_LIST_CONFIGS, processModelList } from '../../utils/modelParse';
import { sanitizeAnthropicThinkingParts } from '../../utils/sanitizeAnthropicThinkingParts';
@@ -296,6 +299,66 @@ const buildMoonshotOpenAIPayload = (
} as OpenAI.ChatCompletionCreateParamsStreaming;
};
+/**
+ * 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.
+ * 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
+ * normalization as chat requests before the generic Anthropic conversion.
+ * https://platform.kimi.com/docs/guide/kimi-k2-7-code-quickstart
+ * https://platform.kimi.com/docs/guide/claude-code-kimi
+ */
+const createMoonshotAnthropicGenerateObject = async (
+ client: Anthropic,
+ payload: GenerateObjectPayload,
+ options?: GenerateObjectOptions,
+ pricing?: Pricing,
+ config?: AnthropicGenerateObjectConfig,
+) => {
+ const { thinking } = payload;
+ const isThinkingToggle = isKimiThinkingToggleModel(payload.model);
+ const isNativeThinking = isKimiNativeThinkingModel(payload.model);
+ 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)
+ ? ({
+ budget_tokens: Math.min(
+ thinking?.budget_tokens || 1024,
+ (config?.maxTokens ?? 64_000) - 1,
+ ),
+ type: 'enabled',
+ } as const)
+ : undefined;
+ const normalizedPayload = isThinkingEnabled
+ ? {
+ ...payload,
+ messages: normalizeMessagesForAnthropic(
+ payload.messages as ChatStreamPayload['messages'],
+ true,
+ ) as GenerateObjectPayload['messages'],
+ }
+ : payload;
+
+ return createAnthropicGenerateObject(client, normalizedPayload, options, pricing, {
+ ...config,
+ ...(thinkingParam
+ ? {
+ requestParams: {
+ ...config?.requestParams,
+ thinking: thinkingParam,
+ },
+ }
+ : {}),
+ ...(isThinkingModel ? { schemaToolChoice } : {}),
+ });
+};
+
/**
* Fetch Moonshot models from the API using OpenAI client
*/
@@ -328,6 +391,7 @@ export const anthropicParams = createAnthropicCompatibleParams({
debug: {
chatCompletion: () => process.env.DEBUG_MOONSHOT_CHAT_COMPLETION === '1',
},
+ generateObject: createMoonshotAnthropicGenerateObject,
provider: ModelProvider.Moonshot,
});