π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(moonshot): support Kimi K3 (official API contract + model card) (#17267)
YuTengjinga74f1801c7d9
diff --git a/packages/model-bank/src/aiModels/moonshot.ts b/packages/model-bank/src/aiModels/moonshot.tsindex a8424e1add0..17f0150410f 100644--- a/packages/model-bank/src/aiModels/moonshot.ts+++ b/packages/model-bank/src/aiModels/moonshot.ts@@ -1,7 +1,40 @@import type { AIChatModelCard } from '../types/aiModel';-// https://platform.kimi.com/docs/pricing/chat+// https://platform.kimi.ai/docs/pricing/chatconst moonshotChatModels: AIChatModelCard[] = [+ {+ abilities: {+ functionCall: true,+ reasoning: true,+ structuredOutput: true,+ video: true,+ vision: true,+ },+ contextWindowTokens: 1_048_576,+ description:+ "Kimi K3 is Kimi's most capable model to date, with 2.8 trillion parameters. Built on Kimi Delta Attention and Attention Residuals, it offers native visual understanding and a 1M-token context window for frontier intelligence scenarios such as software engineering, knowledge work, and deep reasoning. Reasoning is always on, configured via the top-level reasoning_effort field.",+ displayName: 'Kimi K3',+ enabled: true,+ family: 'kimi',+ generation: 'kimi-k3',+ id: 'kimi-k3',+ maxOutput: 131_072,+ pricing: {+ currency: 'USD',+ units: [+ { name: 'textInput_cacheRead', rate: 0.3, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textInput', rate: 3, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'textOutput', rate: 15, strategy: 'fixed', unit: 'millionTokens' },+ ],+ },+ releasedAt: '2026-07-16',+ settings: {+ // K3 fixes sampling params server-side (temperature=1, top_p=0.95, penalties=0)+ // and the API docs advise against sending them+ disabledParams: ['frequency_penalty', 'presence_penalty', 'temperature', 'top_p'],+ },+ type: 'chat',+ },{abilities: {functionCall: true,diff --git a/packages/model-bank/src/modelProviders/moonshot.ts b/packages/model-bank/src/modelProviders/moonshot.tsindex 97bf72b1b2a..f5c2c4ebe7a 100644--- a/packages/model-bank/src/modelProviders/moonshot.ts+++ b/packages/model-bank/src/modelProviders/moonshot.ts@@ -2,7 +2,9 @@ import type { ModelProviderCard } from '@/types/llm';const Moonshot: ModelProviderCard = {chatModels: [],- checkModel: 'kimi-k2.5',+ // kimi-k2.5 is closed to new accounts since the K3 launch (fully retired on+ // 2026-08-31), which would fail connectivity checks for new API keys+ checkModel: 'kimi-k2.6',description:'Moonshot, from Moonshot AI (Beijing Moonshot Technology), offers multiple NLP models for use cases like content creation, research, recommendations, and medical analysis, with strong long-context and complex generation support.',id: 'moonshot',diff --git a/packages/model-runtime/src/providers/moonshot/index.test.ts b/packages/model-runtime/src/providers/moonshot/index.test.tsindex f4ea0dc7d16..a270d1a41a1 100644--- a/packages/model-runtime/src/providers/moonshot/index.test.ts+++ b/packages/model-runtime/src/providers/moonshot/index.test.ts@@ -23,8 +23,8 @@ const defaultOpenAIBaseURL = 'https://api.moonshot.cn/v1';const anthropicBaseURL = 'https://api.moonshot.cn/anthropic';// Mock the console.error and console.warn to avoid polluting test output-vi.spyOn(console, 'error').mockImplementation(() => { });-vi.spyOn(console, 'warn').mockImplementation(() => { });+vi.spyOn(console, 'error').mockImplementation(() => {});+vi.spyOn(console, 'warn').mockImplementation(() => {});beforeEach(() => {loadModelsMock.mockResolvedValue([]);@@ -371,6 +371,65 @@ describe('LobeMoonshotOpenAI', () => {const payload = getLastRequestPayload();expect(payload.thinking).toEqual({ keep: 'all', type: 'enabled' });});++ it('should not send thinking/temperature/top_p/penalties for kimi-k3', async () => {+ await instance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'kimi-k3',+ temperature: 0.5,+ top_p: 0.8,+ });++ const payload = getLastRequestPayload();+ // K3 reasoning is always on with server-fixed sampling; the docs say not to+ // send thinking/temperature/top_p/penalties.+ expect(payload.thinking).toBeUndefined();+ expect(payload.temperature).toBeUndefined();+ expect(payload.top_p).toBeUndefined();+ expect(payload.frequency_penalty).toBeUndefined();+ expect(payload.presence_penalty).toBeUndefined();+ });++ it('should rename max_tokens to max_completion_tokens for kimi-k3', async () => {+ await instance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'kimi-k3',+ max_tokens: 4096,+ });++ const payload = getLastRequestPayload();+ expect(payload.max_completion_tokens).toBe(4096);+ expect(payload.max_tokens).toBeUndefined();+ });++ it('should pass through reasoning_effort for kimi-k3', async () => {+ await instance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'kimi-k3',+ reasoning_effort: 'max',+ } as any);++ const payload = getLastRequestPayload();+ expect(payload.reasoning_effort).toBe('max');+ });++ it('should force reasoning_content on assistant messages for kimi-k3', async () => {+ await instance.chat({+ messages: [+ { content: 'Hello', role: 'user' },+ { content: 'Response', role: 'assistant' },+ { content: 'Follow-up', role: 'user' },+ ],+ model: 'kimi-k3',+ });++ const payload = getLastRequestPayload();+ const assistantMessage = payload.messages.find(+ (message: any) => message.role === 'assistant',+ );++ expect(assistantMessage?.reasoning_content).toBe('');+ });});describe('kimi-k2-thinking native thinking models', () => {@@ -845,6 +904,44 @@ describe('LobeMoonshotAnthropicAI', () => {});});+ describe('kimi-k3 reasoning effort models', () => {+ it('should not send thinking/temperature/top_p for kimi-k3', async () => {+ await instance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'kimi-k3',+ temperature: 0.5,+ });++ const payload = getLastRequestPayload();+ // K3 has no `thinking` param (reasoning always on) and temperature/top_p are+ // server-fixed; the docs advise not to send them.+ expect(payload.thinking).toBeUndefined();+ expect(payload.temperature).toBeUndefined();+ expect(payload.top_p).toBeUndefined();+ });++ it('should force thinking block on assistant messages for kimi-k3', async () => {+ await instance.chat({+ messages: [+ { content: 'Hello', role: 'user' },+ { content: 'Response', role: 'assistant' },+ { content: 'Follow-up', role: 'user' },+ ],+ model: 'kimi-k3',+ });++ const payload = getLastRequestPayload();+ const assistantMessage = payload.messages.find(+ (message: any) => message.role === 'assistant',+ );++ expect(assistantMessage?.content).toEqual([+ { type: 'thinking', thinking: ' ' },+ { type: 'text', text: 'Response' },+ ]);+ });+ });+describe('interleaved thinking', () => {it('should convert reasoning to thinking block for assistant messages', async () => {await instance.chat({diff --git a/packages/model-runtime/src/providers/moonshot/index.ts b/packages/model-runtime/src/providers/moonshot/index.tsindex 4cd2ff71e5b..974be3efd4e 100644--- a/packages/model-runtime/src/providers/moonshot/index.ts+++ b/packages/model-runtime/src/providers/moonshot/index.ts@@ -17,6 +17,7 @@ import { MODEL_LIST_CONFIGS, processModelList } from '../../utils/modelParse';import {isKimiNativeThinkingModel,isKimiPreserveThinkingModel,+ isKimiReasoningEffortModel,isKimiThinkingToggleModel,} from './kimiModelId';@@ -73,7 +74,7 @@ const toContentArray = (content: any) =>/*** Normalize assistant messages for Anthropic format.- * When forceThinking is true (kimi-k2.x family with thinking enabled), every assistant+ * When forceThinking is true (kimi thinking family 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"*/@@ -100,7 +101,7 @@ const normalizeMessagesForAnthropic = (/*** Normalize assistant messages for OpenAI format.- * When forceReasoning is true (kimi-k2.x family with thinking enabled), every assistant+ * When forceReasoning is true (kimi thinking family with thinking enabled), every assistant* message must carry reasoning_content (even as empty string), similar to DeepSeek.*/const normalizeMessagesForOpenAI = (@@ -124,7 +125,7 @@ const normalizeMessagesForOpenAI = (});/**- * Build Moonshot Anthropic format payload with special handling for kimi-k2.x thinking toggle+ * Build Moonshot Anthropic format payload with special handling for the kimi thinking toggle*/const buildMoonshotAnthropicPayload = async (payload: ChatStreamPayload,@@ -138,10 +139,10 @@ const buildMoonshotAnthropicPayload = async ()) ??8192;- const isK2Family = isKimiThinkingToggleModel(payload.model);+ const isThinkingToggle = isKimiThinkingToggleModel(payload.model);const isNativeThinking = isKimiNativeThinkingModel(payload.model);const isThinkingEnabled =- isNativeThinking || (isK2Family && payload.thinking?.type !== 'disabled');+ isNativeThinking || (isThinkingToggle && payload.thinking?.type !== 'disabled');const basePayload = await buildDefaultAnthropicPayload({...payload,@@ -153,7 +154,17 @@ const buildMoonshotAnthropicPayload = async (const tools = appendSearchTool(basePayload.tools, payload.enabledSearch);const basePayloadWithSearch = { ...basePayload, tools };- if (!isK2Family && !isNativeThinking) return basePayloadWithSearch;+ // K3+ has no `thinking` param (reasoning is always on, strength is the top-level+ // OpenAI-style `reasoning_effort`) and temperature/top_p are server-fixed β the docs+ // advise not to send them. Reasoning replay is already enforced via+ // normalizeMessagesForAnthropic above (isNativeThinking covers k3+).+ // https://platform.kimi.ai/docs/guide/kimi-k3-quickstart+ if (isKimiReasoningEffortModel(payload.model)) {+ const { temperature: _temperature, top_p: _topP, ...effortBase } = basePayloadWithSearch;+ return effortBase;+ }++ if (!isThinkingToggle && !isNativeThinking) return basePayloadWithSearch;const resolvedThinkingBudget = payload.thinking?.budget_tokens? Math.min(payload.thinking.budget_tokens, resolvedMaxTokens - 1)@@ -163,8 +174,8 @@ const buildMoonshotAnthropicPayload = async (? {budget_tokens: resolvedThinkingBudget,type: 'enabled' as const,- // Only inject keep:'all' for kimi-k2.6; kimi-k2.5 does not support it and- // kimi-k2.7-code always has Preserved Thinking active (no need to pass the param)+ // Inject keep:'all' only for models that accept the param (kimi-k2.6 and assumed+ // k3+); kimi-k2.5 rejects it and kimi-k2.7-code always has Preserved Thinking active...(payload.preserveThinking && isKimiPreserveThinkingModel(payload.model)? { keep: 'all' as const }: {}),@@ -186,19 +197,43 @@ const buildMoonshotOpenAIPayload = (): OpenAI.ChatCompletionCreateParamsStreaming => {const { enabledSearch, messages, model, temperature, thinking, tools, ...rest } = payload;- const isK2Family = isKimiThinkingToggleModel(model);+ const isThinkingToggle = isKimiThinkingToggleModel(model);const isNativeThinking = isKimiNativeThinkingModel(model);- const isThinkingEnabled = isNativeThinking || (isK2Family && thinking?.type !== 'disabled');+ const isThinkingEnabled = isNativeThinking || (isThinkingToggle && thinking?.type !== 'disabled');const normalizedMessages = normalizeMessagesForOpenAI(messages, isThinkingEnabled);const moonshotTools = appendSearchTool(tools, enabledSearch);- if (isK2Family || isNativeThinking) {+ // K3+ replaced the `thinking` param with the top-level OpenAI-style `reasoning_effort`+ // (currently only 'max', which is also the server default β passed through from the+ // payload as-is) and fixes temperature/top_p/n/penalties server-side; the docs advise+ // not to send them. `max_tokens` is documented as `max_completion_tokens` (default+ // 131072, up to 1048576). https://platform.kimi.ai/docs/guide/kimi-k3-quickstart+ if (isKimiReasoningEffortModel(model)) {+ const {+ frequency_penalty: _frequencyPenalty,+ max_tokens,+ presence_penalty: _presencePenalty,+ top_p: _topP,+ ...effortRest+ } = rest;++ return {+ ...effortRest,+ ...(max_tokens === undefined ? {} : { max_completion_tokens: max_tokens }),+ messages: normalizedMessages,+ model,+ stream: payload.stream ?? true,+ tools: moonshotTools?.length ? moonshotTools : undefined,+ } as any;+ }++ if (isThinkingToggle || isNativeThinking) {const thinkingParam =isNativeThinking || thinking?.type !== 'disabled'? {type: 'enabled',- // Only inject keep:'all' for kimi-k2.6; kimi-k2.5 does not support it and- // kimi-k2.7-code always has Preserved Thinking active (no need to pass the param)+ // Inject keep:'all' only for models that accept the param (kimi-k2.6 and assumed+ // k3+); kimi-k2.5 rejects it and kimi-k2.7-code always has Preserved Thinking active...(payload.preserveThinking && isKimiPreserveThinkingModel(model)? { keep: 'all' }: {}),diff --git a/packages/model-runtime/src/providers/moonshot/kimiModelId.test.ts b/packages/model-runtime/src/providers/moonshot/kimiModelId.test.tsindex 5012b4a1b5e..c799de63c0f 100644--- a/packages/model-runtime/src/providers/moonshot/kimiModelId.test.ts+++ b/packages/model-runtime/src/providers/moonshot/kimiModelId.test.ts@@ -4,6 +4,8 @@ import {isKimiAlwaysPreserveThinkingModel,isKimiNativeThinkingModel,isKimiPreserveThinkingModel,+ isKimiReasoningEffortModel,+ isKimiReasoningModel,isKimiThinkingToggleModel,parseKimiModelId,} from './kimiModelId';@@ -49,6 +51,38 @@ describe('parseKimiModelId', () => {});});+ it('should parse Kimi K3 generation ids', () => {+ expect(parseKimiModelId('kimi-k3')).toEqual({+ family: 'k',+ majorVersion: 3,+ normalizedModelId: 'kimi-k3',+ source: 'moonshot',+ });++ expect(parseKimiModelId('kimi-k3.1')).toEqual({+ family: 'k',+ majorVersion: 3,+ minorVersion: 1,+ normalizedModelId: 'kimi-k3.1',+ source: 'moonshot',+ });++ expect(parseKimiModelId('kimi-k3-code')).toEqual({+ family: 'k',+ majorVersion: 3,+ normalizedModelId: 'kimi-k3-code',+ source: 'moonshot',+ variant: 'code',+ });++ expect(parseKimiModelId('moonshotai/kimi-k3')).toEqual({+ family: 'k',+ majorVersion: 3,+ normalizedModelId: 'kimi-k3',+ source: 'openRouter',+ });+ });+it('should return undefined for non-Kimi ids', () => {expect(parseKimiModelId('claude-sonnet-4-5')).toBeUndefined();});@@ -65,6 +99,14 @@ describe('isKimiThinkingToggleModel', () => {expect(isKimiThinkingToggleModel('kimi-k2-thinking')).toBe(false);expect(isKimiThinkingToggleModel('kimi-k2-turbo-preview')).toBe(false);});++ it('should return false for the whole Kimi K3 generation (native thinking, no toggle)', () => {+ expect(isKimiThinkingToggleModel('kimi-k3')).toBe(false);+ expect(isKimiThinkingToggleModel('kimi-k3.1')).toBe(false);+ expect(isKimiThinkingToggleModel('moonshotai/kimi-k3')).toBe(false);+ expect(isKimiThinkingToggleModel('kimi-k3-code')).toBe(false);+ expect(isKimiThinkingToggleModel('kimi-k3-thinking')).toBe(false);+ });});describe('isKimiNativeThinkingModel', () => {@@ -80,6 +122,17 @@ describe('isKimiNativeThinkingModel', () => {expect(isKimiNativeThinkingModel('kimi-k2.5')).toBe(false);expect(isKimiNativeThinkingModel('kimi-k2.6')).toBe(false);});++ it('should treat Kimi K3 -code and -thinking variants as native thinking', () => {+ expect(isKimiNativeThinkingModel('kimi-k3-code')).toBe(true);+ expect(isKimiNativeThinkingModel('kimi-k3-thinking')).toBe(true);+ });++ it('should return true for bare Kimi K3 generation ids (K3 always thinks)', () => {+ expect(isKimiNativeThinkingModel('kimi-k3')).toBe(true);+ expect(isKimiNativeThinkingModel('kimi-k3.1')).toBe(true);+ expect(isKimiNativeThinkingModel('moonshotai/kimi-k3')).toBe(true);+ });});describe('isKimiAlwaysPreserveThinkingModel', () => {@@ -89,7 +142,14 @@ describe('isKimiAlwaysPreserveThinkingModel', () => {expect(isKimiAlwaysPreserveThinkingModel('kimi-k2.8-code-preview')).toBe(true);});- it('should return false for switchable and non-code Kimi models', () => {+ it('should return true for the whole Kimi K3 generation', () => {+ expect(isKimiAlwaysPreserveThinkingModel('kimi-k3')).toBe(true);+ expect(isKimiAlwaysPreserveThinkingModel('kimi-k3.1')).toBe(true);+ expect(isKimiAlwaysPreserveThinkingModel('kimi-k3-code')).toBe(true);+ expect(isKimiAlwaysPreserveThinkingModel('kimi-k3-thinking')).toBe(true);+ });++ it('should return false for switchable and non-code Kimi K2 models', () => {expect(isKimiAlwaysPreserveThinkingModel('kimi-k2.6')).toBe(false);expect(isKimiAlwaysPreserveThinkingModel('kimi-k2-thinking')).toBe(false);});@@ -100,9 +160,50 @@ describe('isKimiPreserveThinkingModel', () => {expect(isKimiPreserveThinkingModel('kimi-k2.6')).toBe(true);});+ it('should return false for the whole Kimi K3 generation (no thinking param at all)', () => {+ expect(isKimiPreserveThinkingModel('kimi-k3')).toBe(false);+ expect(isKimiPreserveThinkingModel('kimi-k3.1')).toBe(false);+ // K3 code always has Preserved Thinking active, so the param is redundant+ expect(isKimiPreserveThinkingModel('kimi-k3-code')).toBe(false);+ });+it('should return false for other Kimi models', () => {expect(isKimiPreserveThinkingModel('kimi-k2.5')).toBe(false);expect(isKimiPreserveThinkingModel('kimi-k2.7-code')).toBe(false);expect(isKimiPreserveThinkingModel('kimi-k2-thinking')).toBe(false);});});++describe('isKimiReasoningModel', () => {+ it('should return true for dot-versioned Kimi K2 models and later generations', () => {+ expect(isKimiReasoningModel('kimi-k2.5')).toBe(true);+ expect(isKimiReasoningModel('kimi-k2.6')).toBe(true);+ expect(isKimiReasoningModel('kimi-k2.7-code')).toBe(true);+ expect(isKimiReasoningModel('kimi-k3')).toBe(true);+ expect(isKimiReasoningModel('kimi-k3.1')).toBe(true);+ expect(isKimiReasoningModel('kimi-k3-code')).toBe(true);+ expect(isKimiReasoningModel('moonshotai/kimi-k3')).toBe(true);+ });++ it('should return false for legacy K2 ids without a minor version and non-Kimi models', () => {+ expect(isKimiReasoningModel('kimi-k2-0711-preview')).toBe(false);+ expect(isKimiReasoningModel('kimi-k2-thinking')).toBe(false);+ expect(isKimiReasoningModel('moonshot-v1-8k')).toBe(false);+ });+});++describe('isKimiReasoningEffortModel', () => {+ it('should return true for the whole Kimi K3 generation', () => {+ expect(isKimiReasoningEffortModel('kimi-k3')).toBe(true);+ expect(isKimiReasoningEffortModel('kimi-k3.1')).toBe(true);+ expect(isKimiReasoningEffortModel('kimi-k3-code')).toBe(true);+ expect(isKimiReasoningEffortModel('moonshotai/kimi-k3')).toBe(true);+ });++ it('should return false for Kimi K2 and legacy models', () => {+ expect(isKimiReasoningEffortModel('kimi-k2.6')).toBe(false);+ expect(isKimiReasoningEffortModel('kimi-k2.7-code')).toBe(false);+ expect(isKimiReasoningEffortModel('kimi-k2-thinking')).toBe(false);+ expect(isKimiReasoningEffortModel('moonshot-v1-8k')).toBe(false);+ });+});diff --git a/packages/model-runtime/src/providers/moonshot/kimiModelId.ts b/packages/model-runtime/src/providers/moonshot/kimiModelId.tsindex 3ed34b04364..778f6c76be4 100644--- a/packages/model-runtime/src/providers/moonshot/kimiModelId.ts+++ b/packages/model-runtime/src/providers/moonshot/kimiModelId.ts@@ -60,44 +60,97 @@ export const parseKimiModelId = (model: string): ParsedKimiModelId | undefined =const hasVariant = (parsed: ParsedKimiModelId, variant: string): boolean =>parsed.variant === variant || !!parsed.variant?.startsWith(`${variant}-`);+/**+ * Whether the parsed model is at or after a given kimi generation, e.g.+ * `isAtLeastGeneration(parsed, 2, 6)` matches k2.6, k2.7, k3, k3.1...+ * Legacy ids without a minor version (kimi-k2-0711-preview) count as minor 0.+ */+const isAtLeastGeneration = (parsed: ParsedKimiModelId, major: number, minor = 0): boolean =>+ parsed.majorVersion > major ||+ (parsed.majorVersion === major && (parsed.minorVersion ?? 0) >= minor);++/**+ * Models whose thinking is always on and cannot be disabled: the legacy+ * `-thinking` variants (kimi-k2-thinking), `-code` variants since k2.7+ * (kimi-k2.7-code errors on `thinking: {type: 'disabled'}`), and the entire+ * k3+ generation ("K3 always runs with thinking enabled").+ * Docs: https://platform.kimi.com/docs/guide/kimi-k3-quickstart+ */export const isKimiNativeThinkingModel = (model: string): boolean => {const parsed = parseKimiModelId(model);if (!parsed) return false;- if (parsed.majorVersion !== 2) return false;+ if (parsed.majorVersion >= 3) return true;+ if (parsed.majorVersion < 2) return false;if (hasVariant(parsed, 'thinking')) return true;- return (- hasVariant(parsed, 'code') && parsed.minorVersion !== undefined && parsed.minorVersion >= 7- );+ return hasVariant(parsed, 'code') && isAtLeastGeneration(parsed, 2, 7);+};++/**+ * Models (k3+) that configure reasoning strength via the top-level+ * OpenAI-style `reasoning_effort` field. The K2.x `thinking` param does not+ * apply to them and must not be sent.+ * Docs: https://platform.kimi.com/docs/api/models-overview+ */+export const isKimiReasoningEffortModel = (model: string): boolean => {+ const parsed = parseKimiModelId(model);+ if (!parsed) return false;++ return parsed.majorVersion >= 3;};+/**+ * Models that must round-trip the complete assistant message (including+ * `reasoning_content`) across turns with no opt-out: `-code` variants since+ * kimi-k2.7-code (Preserved Thinking always active) and the whole k3++ * generation.+ */export const isKimiAlwaysPreserveThinkingModel = (model: string): boolean => {const parsed = parseKimiModelId(model);if (!parsed) return false;- return (- parsed.majorVersion === 2 &&- hasVariant(parsed, 'code') &&- parsed.minorVersion !== undefined &&- parsed.minorVersion >= 7- );+ if (parsed.majorVersion >= 3) return true;++ return hasVariant(parsed, 'code') && isAtLeastGeneration(parsed, 2, 7);};+/**+ * K2.x models that accept `thinking: {type: 'enabled' | 'disabled'}` with+ * fixed sampling params (temperature 1/0.6, top_p 0.95, penalties 0):+ * kimi-k2.5 and kimi-k2.6. Bare legacy kimi-k2-* ids (e.g.+ * kimi-k2-0711-preview) predate the toggle, and k3+ replaced the `thinking`+ * param with top-level `reasoning_effort`.+ */export const isKimiThinkingToggleModel = (model: string): boolean => {const parsed = parseKimiModelId(model);if (!parsed) return false;+ if (isKimiNativeThinkingModel(model)) return false;- return (- parsed.majorVersion === 2 &&- parsed.minorVersion !== undefined &&- !isKimiNativeThinkingModel(model)- );+ return parsed.majorVersion === 2 && parsed.minorVersion !== undefined;};+/**+ * Models that accept the optional `thinking.keep: 'all'` param β kimi-k2.6+ * only: kimi-k2.5 rejects it, kimi-k2.7-code always preserves (param+ * redundant), and k3+ has no `thinking` param at all.+ */export const isKimiPreserveThinkingModel = (model: string): boolean => {const parsed = parseKimiModelId(model);if (!parsed) return false;return parsed.majorVersion === 2 && parsed.minorVersion === 6;};++/**+ * Kimi models that expose `reasoning_content` on the OpenAI-compatible route:+ * dot-versioned k2 models (k2.5/k2.6/k2.7-code) and every generation after.+ */+export const isKimiReasoningModel = (model: string): boolean => {+ const parsed = parseKimiModelId(model);+ if (!parsed) return false;++ return (+ parsed.majorVersion > 2 || (parsed.majorVersion === 2 && parsed.minorVersion !== undefined)+ );+};diff --git a/packages/model-runtime/src/providers/opencodeCodingPlan/index.test.ts b/packages/model-runtime/src/providers/opencodeCodingPlan/index.test.tsindex 2eae4f4541d..d0054c29a05 100644--- a/packages/model-runtime/src/providers/opencodeCodingPlan/index.test.ts+++ b/packages/model-runtime/src/providers/opencodeCodingPlan/index.test.ts@@ -1,12 +1,29 @@// @vitest-environment nodeimport { ModelProvider } from 'model-bank';-import { describe, expect, it } from 'vitest';+import OpenAI from 'openai';+import type { Mock } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { LobeOpenCodeCodingPlanAI, sanitizeJsonSchema } from './index';+// The router pulls the cloud model-bank config for deepseek route resolution,+// which transitively imports server-only modules (e.g. redis-client). Stub it+// so the OpenAI-compatible chat route can be exercised in the node test env.+const { loadModelsMock } = vi.hoisted(() => ({ loadModelsMock: vi.fn() }));+vi.mock('@lobechat/business-model-bank/model-config', () => ({+ loadModels: loadModelsMock,+}));+const provider = ModelProvider.OpenCodeCodingPlan;const defaultBaseURL = 'https://opencode.ai/zen/go/v1';+// Avoid a real models.dev fetch during router resolution; the failure path falls+// back to the hardcoded interleaved snapshot, which is what these tests assert on.+global.fetch = vi.fn().mockRejectedValue(new Error('no network in test')) as any;++// Silence the router's console.error on the mocked (never-resolving) fetch path.+vi.spyOn(console, 'error').mockImplementation(() => {});+describe('LobeOpenCodeCodingPlanAI', () => {describe('init', () => {it('should correctly initialize with an API key', () => {@@ -77,10 +94,7 @@ describe('sanitizeJsonSchema', () => {{ type: 'object', properties: { x: { enum: ['a', null] } } },{ type: 'object', properties: { y: { enum: ['b', null] } } },],- anyOf: [- { enum: ['c', null] },- { type: ['string', 'null'] },- ],+ anyOf: [{ enum: ['c', null] }, { type: ['string', 'null'] }],};const result = sanitizeJsonSchema(schema);expect(result.allOf[0].properties.x.enum).toEqual(['a']);@@ -96,10 +110,7 @@ describe('sanitizeJsonSchema', () => {type: 'object',properties: { tag: { enum: ['alpha', 'beta', null] } },},- prefixItems: [- { enum: ['x', null] },- { enum: ['y', null] },- ],+ prefixItems: [{ enum: ['x', null] }, { enum: ['y', null] }],};const result = sanitizeJsonSchema(schema);expect(result.items.properties.tag.enum).toEqual(['alpha', 'beta']);@@ -116,6 +127,8 @@ describe('sanitizeJsonSchema', () => {},},if: { properties: { x: { enum: ['a', null] } } },+ // `then` here is the JSON Schema if/then/else keyword, not a thenable.+ // eslint-disable-next-line unicorn/no-thenablethen: { properties: { y: { type: ['string', 'null'] } } },else: { properties: { z: { enum: ['b', null] } } },};@@ -138,3 +151,107 @@ describe('sanitizeJsonSchema', () => {expect(sanitizeJsonSchema(schema)).toEqual(schema);});});++describe('buildOpenAIPayload Kimi thinking semantics', () => {+ let instance: InstanceType<typeof LobeOpenCodeCodingPlanAI>;+ let createSpy: Mock;++ const getLastRequestPayload = () => createSpy.mock.calls.at(-1)?.[0];++ const findAssistantMessage = (payload: any) =>+ payload.messages.find((message: any) => message.role === 'assistant');++ beforeEach(() => {+ loadModelsMock.mockResolvedValue([]);+ instance = new LobeOpenCodeCodingPlanAI({ apiKey: 'test' });+ // Kimi models route to the OpenAI-compatible fallback runtime, whose client+ // is built lazily per request; spy on the shared SDK prototype to capture+ // the outgoing chat.completions.create params.+ createSpy = vi+ .spyOn(OpenAI.Chat.Completions.prototype, 'create')+ .mockResolvedValue(new ReadableStream() as any) as unknown as Mock;+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ describe('native-thinking K3 models (kimi-k3)', () => {+ it('should drop a saved thinking:disabled and keep reasoning_effort + forced reasoning_content', async () => {+ await instance.chat({+ messages: [+ { content: 'Hello', role: 'user' },+ { content: 'Response', role: 'assistant' },+ { content: 'Follow-up', role: 'user' },+ ],+ model: 'kimi-k3',+ reasoning_effort: 'high',+ thinking: { type: 'disabled' },+ } as any);++ const payload = getLastRequestPayload();++ // K3 rejects the `thinking` param entirely: no key must be emitted.+ expect('thinking' in payload).toBe(false);+ // disabled is ignored for native-thinking models, so reasoning_effort passes through.+ expect(payload.reasoning_effort).toBe('high');+ // assistant messages still get reasoning_content forced (fallback ' ').+ expect(findAssistantMessage(payload)?.reasoning_content).toBe(' ');+ });++ it('should not emit thinking even when thinking:enabled is provided', async () => {+ await instance.chat({+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'kimi-k3',+ thinking: { type: 'enabled' },+ } as any);++ const payload = getLastRequestPayload();++ // K3 configures reasoning via top-level reasoning_effort only; the K2.x+ // `thinking` param is never emitted, enabled or disabled.+ expect('thinking' in payload).toBe(false);+ });+ });++ describe('native-thinking K2.7 code model (kimi-k2.7-code)', () => {+ it('should not re-emit thinking:disabled and still force reasoning_content', async () => {+ await instance.chat({+ messages: [+ { content: 'Hello', role: 'user' },+ { content: 'Response', role: 'assistant' },+ { content: 'Follow-up', role: 'user' },+ ],+ model: 'kimi-k2.7-code',+ thinking: { type: 'disabled' },+ } as any);++ const payload = getLastRequestPayload();++ // Native-thinking models cannot turn reasoning off; disabled must not be re-emitted.+ expect('thinking' in payload).toBe(false);+ expect(findAssistantMessage(payload)?.reasoning_content).toBe(' ');+ });+ });++ describe('toggleable K2.x model (kimi-k2.6)', () => {+ it('should re-emit thinking:disabled and not force reasoning_content', async () => {+ await instance.chat({+ messages: [+ { content: 'Hello', role: 'user' },+ { content: 'Response', role: 'assistant' },+ { content: 'Follow-up', role: 'user' },+ ],+ model: 'kimi-k2.6',+ thinking: { type: 'disabled' },+ } as any);++ const payload = getLastRequestPayload();++ // Toggleable K2.x models keep the old behavior: disabled is honored and re-emitted.+ expect(payload.thinking).toEqual({ type: 'disabled' });+ // With thinking explicitly disabled, assistant messages are not forced to carry reasoning_content.+ expect(findAssistantMessage(payload)?.reasoning_content).toBeUndefined();+ });+ });+});diff --git a/packages/model-runtime/src/providers/opencodeCodingPlan/index.ts b/packages/model-runtime/src/providers/opencodeCodingPlan/index.tsindex d43210b6def..2096827dd50 100644--- a/packages/model-runtime/src/providers/opencodeCodingPlan/index.ts+++ b/packages/model-runtime/src/providers/opencodeCodingPlan/index.ts@@ -6,6 +6,11 @@ import { createRouterRuntime } from '../../core/RouterRuntime';import type { CreateRouterRuntimeOptions } from '../../core/RouterRuntime/createRuntime';import type { ChatStreamPayload } from '../../types';import { processMultiProviderModelList } from '../../utils/modelParse';+import {+ isKimiNativeThinkingModel,+ isKimiReasoningEffortModel,+ isKimiReasoningModel,+} from '../moonshot/kimiModelId';import { resolveProviderRouteModels } from '../utils/resolveProviderRouteModels';// ============================================================================@@ -216,8 +221,9 @@ const enrichWithModelsDev = (// Reasoning Content Helpers// ============================================================================-// Kimi K2.x models expose reasoning on the OpenAI-compatible route-const isKimiThinkingToggleModel = (model: string) => model.startsWith('kimi-k2.');+// Kimi dot-versioned k2 models (k2.5+) and later generations (k3+) expose+// reasoning on the OpenAI-compatible route+const isKimiThinkingToggleModel = isKimiReasoningModel;// Models in `interleavedIds` need:// 1. reason β reasoning_content conversion@@ -313,7 +319,12 @@ const buildOpenAIPayload = (if (!isKimi && !interleaved) return payload as any;- const thinkingExplicitlyDisabled = (payload as any).thinking?.type === 'disabled';+ // Native-thinking Kimi models (k2.7-code, k3+) cannot turn reasoning off, so a+ // saved disabled-thinking setting must be ignored: they still require+ // reasoning_content round-trip and reject a `thinking: disabled` payload.+ const nativeThinking = isKimiNativeThinkingModel(model);+ const thinkingExplicitlyDisabled =+ !nativeThinking && (payload as any).thinking?.type === 'disabled';const shouldForceReasoning = (interleaved || isKimi) && !thinkingExplicitlyDisabled;const messages = payload.messages.map((message: any) => {@@ -375,7 +386,11 @@ const buildOpenAIPayload = (response_format,tools,...(!thinkingExplicitlyDisabled && reasoning_effort ? { reasoning_effort } : {}),- ...(thinking?.type === 'enabled' || thinking?.type === 'disabled'+ // K3+ models configure reasoning via top-level reasoning_effort only and+ // reject the K2.x-only `thinking` param; native-thinking models never get+ // `disabled` re-emitted (the toggle does not exist for them).+ ...(!isKimiReasoningEffortModel(model) &&+ (thinking?.type === 'enabled' || (thinking?.type === 'disabled' && !nativeThinking))? { thinking: { type: thinking.type } }: {}),stream: payload.stream ?? true,diff --git a/packages/model-runtime/src/utils/modelParse.ts b/packages/model-runtime/src/utils/modelParse.tsindex cf523afed10..1f452194dbb 100644--- a/packages/model-runtime/src/utils/modelParse.ts+++ b/packages/model-runtime/src/utils/modelParse.ts@@ -83,8 +83,16 @@ export const MODEL_LIST_CONFIGS = {},moonshot: {functionCallKeywords: ['moonshot', 'kimi'],- reasoningKeywords: ['thinking', 'k2.5'],- visionKeywords: ['vision', 'kimi-latest', 'kimi-thinking-preview', 'k2.5'],+ reasoningKeywords: ['thinking', 'k2.5', 'k2.6', 'k2.7', 'kimi-k3'],+ visionKeywords: [+ 'vision',+ 'kimi-latest',+ 'kimi-thinking-preview',+ 'k2.5',+ 'k2.6',+ 'k2.7',+ 'kimi-k3',+ ],},openai: {excludeKeywords: ['audio'],