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): forward Kimi reasoning effort and inline videos (#21554)

YuTengjing547622d485e4
diff --git a/packages/model-runtime/src/providers/moonshot/index.reasoningEffort.test.ts b/packages/model-runtime/src/providers/moonshot/index.reasoningEffort.test.ts
new file mode 100644
index 00000000000..e409da99461
--- /dev/null
+++ b/packages/model-runtime/src/providers/moonshot/index.reasoningEffort.test.ts
@@ -0,0 +1,95 @@
+// @vitest-environment node
+import type { Mock } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { LobeMoonshotAnthropicAI } from './index';
+
+const { loadModelsMock } = vi.hoisted(() => ({
+ loadModelsMock: vi.fn(),
+}));
+
+vi.mock('@lobechat/business-model-bank/model-config', () => ({
+ loadModels: loadModelsMock,
+}));
+
+describe('LobeMoonshotAnthropicAI reasoning effort', () => {
+ let instance: InstanceType<typeof LobeMoonshotAnthropicAI>;
+
+ const getLastRequestPayload = () => {
+ const calls = ((instance as any).client.messages.create as Mock).mock.calls;
+ return calls.at(-1)?.[0];
+ };
+
+ beforeEach(() => {
+ loadModelsMock.mockResolvedValue([]);
+ instance = new LobeMoonshotAnthropicAI({ apiKey: 'test' });
+
+ vi.spyOn((instance as any).client.messages, 'create').mockResolvedValue(
+ new ReadableStream() as any,
+ );
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it.each(['kimi-k3', 'kimi-k3.1-pro', 'kimi-k3.1-pro-highspeed'])(
+ 'should send reasoning_effort as output_config.effort for %s',
+ async (model) => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model,
+ reasoning_effort: 'low',
+ temperature: 1,
+ });
+
+ const payload = getLastRequestPayload();
+ expect(payload.output_config).toEqual({ effort: 'low' });
+ expect(payload.reasoning_effort).toBeUndefined();
+ },
+ );
+
+ it.each(['low', 'high', 'max'])('should forward %s reasoning effort', async (effort) => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'kimi-k3.1-pro',
+ reasoning_effort: effort as 'low' | 'high' | 'max',
+ temperature: 1,
+ });
+
+ expect(getLastRequestPayload().output_config).toEqual({ effort });
+ });
+
+ it('should drop reasoning effort values that Kimi does not accept', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'kimi-k3.1-pro',
+ reasoning_effort: 'medium',
+ temperature: 1,
+ });
+
+ const payload = getLastRequestPayload();
+ expect(payload.output_config).toBeUndefined();
+ });
+
+ it('should not send output_config when no reasoning effort is set', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'kimi-k3.1-pro',
+ temperature: 1,
+ });
+
+ expect(getLastRequestPayload().output_config).toBeUndefined();
+ });
+
+ it('should not send output_config for K2.x models', async () => {
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'kimi-k2.7-code',
+ reasoning_effort: 'high',
+ temperature: 1,
+ });
+
+ expect(getLastRequestPayload().output_config).toBeUndefined();
+ });
+});
diff --git a/packages/model-runtime/src/providers/moonshot/index.ts b/packages/model-runtime/src/providers/moonshot/index.ts
index c8492988df9..0155af01d54 100644
--- a/packages/model-runtime/src/providers/moonshot/index.ts
+++ b/packages/model-runtime/src/providers/moonshot/index.ts
@@ -16,13 +16,16 @@ import type { CreateRouterRuntimeOptions } from '../../core/RouterRuntime';
import { createRouterRuntime } from '../../core/RouterRuntime';
import type { ChatStreamPayload, GenerateObjectOptions, GenerateObjectPayload } from '../../types';
import { getModelPropertyWithFallback } from '../../utils/getFallbackModelProperty';
+import { imageUrlToBase64 } from '../../utils/imageToBase64';
import { MODEL_LIST_CONFIGS, processModelList } from '../../utils/modelParse';
import { sanitizeAnthropicThinkingParts } from '../../utils/sanitizeAnthropicThinkingParts';
+import { parseDataUri } from '../../utils/uriParser';
import {
isKimiNativeThinkingModel,
isKimiPreserveThinkingModel,
isKimiReasoningEffortModel,
isKimiThinkingToggleModel,
+ resolveKimiReasoningEffort,
} from './modelId';
export interface MoonshotModelCard {
@@ -155,6 +158,56 @@ const normalizeMessagesForOpenAI = (
return normalized;
});
+/** Raw video bytes one request may inline, so long video threads cannot exhaust memory. */
+const KIMI_VIDEO_INPUT_MAX_BYTES = 100 * 1024 * 1024;
+const KIMI_VIDEO_DOWNLOAD_TIMEOUT_MS = 30_000;
+
+/**
+ * Kimi rejects remote video URLs with "unsupported video url" but accepts base64 video
+ * blocks, so fetch remote videos and inline them before building the payload. Videos are
+ * downloaded one at a time against a shared byte budget; exceeding it fails the request
+ * instead of sending a truncated video.
+ */
+const inlineRemoteVideos = async (messages: ChatStreamPayload['messages']) => {
+ let remainingBytes = KIMI_VIDEO_INPUT_MAX_BYTES;
+ const result: ChatStreamPayload['messages'] = [];
+
+ for (const message of messages) {
+ if (!Array.isArray(message.content) || !message.content.some((p) => p.type === 'video_url')) {
+ result.push(message);
+ continue;
+ }
+
+ const content: typeof message.content = [];
+
+ for (const part of message.content) {
+ if (part.type !== 'video_url' || parseDataUri(part.video_url.url).type !== 'url') {
+ content.push(part);
+ continue;
+ }
+
+ if (remainingBytes <= 0) {
+ throw new RangeError(
+ `Videos in this conversation exceed the ${KIMI_VIDEO_INPUT_MAX_BYTES}-byte limit`,
+ );
+ }
+
+ // imageUrlToBase64 is the generic SSRF-safe binary downloader with a byte cap.
+ const { base64, mimeType } = await imageUrlToBase64(part.video_url.url, {
+ maxBytes: remainingBytes,
+ signal: AbortSignal.timeout(KIMI_VIDEO_DOWNLOAD_TIMEOUT_MS),
+ });
+ remainingBytes -= Math.floor((base64.length * 3) / 4);
+
+ content.push({ ...part, video_url: { url: `data:${mimeType};base64,${base64}` } });
+ }
+
+ result.push({ ...message, content });
+ }
+
+ return result;
+};
+
/**
* Build Moonshot Anthropic format payload with special handling for the kimi thinking toggle
*/
@@ -179,7 +232,10 @@ const buildMoonshotAnthropicPayload = async (
...payload,
enabledSearch: false,
max_tokens: resolvedMaxTokens,
- messages: normalizeMessagesForAnthropic(payload.messages, isThinkingEnabled),
+ messages: normalizeMessagesForAnthropic(
+ await inlineRemoteVideos(payload.messages),
+ isThinkingEnabled,
+ ),
});
const tools = appendSearchTool(basePayload.tools, payload.enabledSearch);
@@ -192,7 +248,13 @@ const buildMoonshotAnthropicPayload = async (
// https://platform.kimi.ai/docs/guide/kimi-k3-quickstart
if (isKimiReasoningEffortModel(payload.model)) {
const { temperature: _temperature, top_p: _topP, ...effortBase } = basePayloadWithSearch;
- return effortBase;
+ // The Messages API ignores top-level `reasoning_effort`; it reads the strength from
+ // `output_config.effort` instead. https://platform.kimi.ai/docs/api/messages
+ const effort = resolveKimiReasoningEffort(payload.reasoning_effort);
+
+ return effort
+ ? ({ ...effortBase, output_config: { effort } } as Anthropic.MessageCreateParams)
+ : effortBase;
}
if (!isThinkingToggle && !isNativeThinking) return basePayloadWithSearch;
@@ -248,13 +310,11 @@ const buildMoonshotOpenAIPayload = (
...effortRest
} = rest;
+ const effort = resolveKimiReasoningEffort(reasoning_effort);
+
return {
...effortRest,
- // K3 supports low/high/max. Filter generic values such as medium so stale
- // cross-model settings cannot make the provider reject the whole request.
- ...(reasoning_effort === 'low' || reasoning_effort === 'high' || reasoning_effort === 'max'
- ? { reasoning_effort }
- : {}),
+ ...(effort ? { reasoning_effort: effort } : {}),
...(max_tokens === undefined ? {} : { max_completion_tokens: max_tokens }),
messages: normalizedMessages,
model,
diff --git a/packages/model-runtime/src/providers/moonshot/index.video.test.ts b/packages/model-runtime/src/providers/moonshot/index.video.test.ts
new file mode 100644
index 00000000000..6e140b84c68
--- /dev/null
+++ b/packages/model-runtime/src/providers/moonshot/index.video.test.ts
@@ -0,0 +1,135 @@
+// @vitest-environment node
+import type { Mock } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { imageUrlToBase64 } from '../../utils/imageToBase64';
+import { LobeMoonshotAnthropicAI } from './index';
+
+const { loadModelsMock } = vi.hoisted(() => ({
+ loadModelsMock: vi.fn(),
+}));
+
+vi.mock('@lobechat/business-model-bank/model-config', () => ({
+ loadModels: loadModelsMock,
+}));
+
+vi.mock('../../utils/imageToBase64', () => ({
+ imageUrlToBase64: vi.fn(),
+}));
+
+const MAX_BYTES = 100 * 1024 * 1024;
+
+const videoMessage = (...urls: string[]) => ({
+ content: urls.map((url) => ({ type: 'video_url' as const, video_url: { url } })),
+ role: 'user' as const,
+});
+
+describe('LobeMoonshotAnthropicAI video input', () => {
+ let instance: InstanceType<typeof LobeMoonshotAnthropicAI>;
+
+ const getLastRequestPayload = () => {
+ const calls = ((instance as any).client.messages.create as Mock).mock.calls;
+ return calls.at(-1)?.[0];
+ };
+
+ beforeEach(() => {
+ loadModelsMock.mockResolvedValue([]);
+ instance = new LobeMoonshotAnthropicAI({ apiKey: 'test' });
+
+ vi.spyOn((instance as any).client.messages, 'create').mockResolvedValue(
+ new ReadableStream() as any,
+ );
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should inline http video urls as base64 because Kimi rejects remote video urls', async () => {
+ vi.mocked(imageUrlToBase64).mockResolvedValue({ base64: 'AAAA', mimeType: 'video/mp4' });
+
+ await instance.chat({
+ messages: [
+ {
+ content: [
+ { text: 'What color is the video?', type: 'text' },
+ { type: 'video_url', video_url: { url: 'https://example.com/clip.mp4' } },
+ ],
+ role: 'user',
+ },
+ ],
+ model: 'kimi-k3.1-pro',
+ temperature: 1,
+ });
+
+ expect(imageUrlToBase64).toHaveBeenCalledWith('https://example.com/clip.mp4', {
+ maxBytes: MAX_BYTES,
+ signal: expect.any(AbortSignal),
+ });
+ expect(getLastRequestPayload().messages[0].content).toContainEqual(
+ expect.objectContaining({
+ source: { data: 'AAAA', media_type: 'video/mp4', type: 'base64' },
+ type: 'video',
+ }),
+ );
+ });
+
+ it('should keep data uri videos without fetching', async () => {
+ await instance.chat({
+ messages: [
+ {
+ content: [{ type: 'video_url', video_url: { url: 'data:video/mp4;base64,BBBB' } }],
+ role: 'user',
+ },
+ ],
+ model: 'kimi-k3.1-pro',
+ temperature: 1,
+ });
+
+ expect(imageUrlToBase64).not.toHaveBeenCalled();
+ expect(getLastRequestPayload().messages[0].content).toContainEqual(
+ expect.objectContaining({
+ source: { data: 'BBBB', media_type: 'video/mp4', type: 'base64' },
+ type: 'video',
+ }),
+ );
+ });
+
+ it('should share one byte budget across all videos in the request', async () => {
+ // 'AAAA' decodes to 3 bytes
+ vi.mocked(imageUrlToBase64).mockResolvedValue({ base64: 'AAAA', mimeType: 'video/mp4' });
+
+ await instance.chat({
+ messages: [videoMessage('https://example.com/a.mp4', 'https://example.com/b.mp4')],
+ model: 'kimi-k3.1-pro',
+ temperature: 1,
+ });
+
+ expect(imageUrlToBase64).toHaveBeenNthCalledWith(1, 'https://example.com/a.mp4', {
+ maxBytes: MAX_BYTES,
+ signal: expect.any(AbortSignal),
+ });
+ expect(imageUrlToBase64).toHaveBeenNthCalledWith(2, 'https://example.com/b.mp4', {
+ maxBytes: MAX_BYTES - 3,
+ signal: expect.any(AbortSignal),
+ });
+ });
+
+ it('should fail instead of sending more videos once the budget is used up', async () => {
+ vi.mocked(imageUrlToBase64).mockResolvedValue({
+ base64: 'A'.repeat(Math.ceil(MAX_BYTES / 3) * 4),
+ mimeType: 'video/mp4',
+ });
+
+ await expect(
+ instance.chat({
+ messages: [videoMessage('https://example.com/a.mp4', 'https://example.com/b.mp4')],
+ model: 'kimi-k3.1-pro',
+ temperature: 1,
+ }),
+ ).rejects.toBeDefined();
+
+ expect(imageUrlToBase64).toHaveBeenCalledTimes(1);
+ expect((instance as any).client.messages.create).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/model-runtime/src/providers/moonshot/modelId.ts b/packages/model-runtime/src/providers/moonshot/modelId.ts
index 778f6c76be4..799f21d09ef 100644
--- a/packages/model-runtime/src/providers/moonshot/modelId.ts
+++ b/packages/model-runtime/src/providers/moonshot/modelId.ts
@@ -100,6 +100,15 @@ export const isKimiReasoningEffortModel = (model: string): boolean => {
return parsed.majorVersion >= 3;
};
+export type KimiReasoningEffort = 'low' | 'high' | 'max';
+
+/**
+ * K3+ accepts only low/high/max. Generic values such as `medium` are dropped so
+ * stale cross-model settings cannot make the provider reject the whole request.
+ */
+export const resolveKimiReasoningEffort = (value: unknown): KimiReasoningEffort | undefined =>
+ value === 'low' || value === 'high' || value === 'max' ? value : undefined;
+
/**
* Models that must round-trip the complete assistant message (including
* `reasoning_content`) across turns with no opt-out: `-code` variants since
diff --git a/packages/model-runtime/src/utils/imageToBase64.test.ts b/packages/model-runtime/src/utils/imageToBase64.test.ts
new file mode 100644
index 00000000000..96887947264
--- /dev/null
+++ b/packages/model-runtime/src/utils/imageToBase64.test.ts
@@ -0,0 +1,43 @@
+// @vitest-environment node
+import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { imageUrlToBase64 } from './imageToBase64';
+
+vi.mock('@lobechat/ssrf-safe-fetch', () => ({
+ ssrfSafeFetch: vi.fn(),
+}));
+
+describe('imageUrlToBase64', () => {
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('should cap the server-side download itself, not only the buffered result', async () => {
+ vi.mocked(ssrfSafeFetch).mockResolvedValue(new Response(new Uint8Array([1, 2, 3])));
+
+ await imageUrlToBase64('https://example.com/a.bin', { maxBytes: 3 });
+
+ // One byte over the limit is read so an oversized body is detected instead of truncated.
+ expect(ssrfSafeFetch).toHaveBeenCalledWith('https://example.com/a.bin', undefined, {
+ maxContentLength: 4,
+ });
+ });
+
+ it('should reject a body longer than maxBytes without content-length', async () => {
+ vi.mocked(ssrfSafeFetch).mockResolvedValue(new Response(new Uint8Array([1, 2, 3, 4])));
+
+ await expect(imageUrlToBase64('https://example.com/a.bin', { maxBytes: 3 })).rejects.toThrow(
+ RangeError,
+ );
+ });
+
+ it('should pass the abort signal to the download', async () => {
+ vi.mocked(ssrfSafeFetch).mockResolvedValue(new Response(new Uint8Array([1])));
+ const signal = AbortSignal.timeout(1000);
+
+ await imageUrlToBase64('https://example.com/a.bin', { signal });
+
+ expect(ssrfSafeFetch).toHaveBeenCalledWith('https://example.com/a.bin', { signal }, undefined);
+ });
+});
diff --git a/packages/model-runtime/src/utils/imageToBase64.ts b/packages/model-runtime/src/utils/imageToBase64.ts
index bd2868c0765..87a0654348e 100644
--- a/packages/model-runtime/src/utils/imageToBase64.ts
+++ b/packages/model-runtime/src/utils/imageToBase64.ts
@@ -46,6 +46,8 @@ export const imageToBase64 = ({
export interface ImageUrlToBase64Options {
/** Abort the download once the response exceeds this many bytes. */
maxBytes?: number;
+ /** Cancels the download, e.g. `AbortSignal.timeout(...)`. */
+ signal?: AbortSignal;
}
/**
@@ -60,9 +62,18 @@ export const imageUrlToBase64 = async (
const isServer = typeof window === 'undefined';
// Use SSRF-safe fetch on server-side to prevent SSRF attacks
+ const init = options.signal ? { signal: options.signal } : undefined;
+ // ssrfSafeFetch buffers the whole body before returning, so the cap must be applied
+ // there. It truncates silently, so read one extra byte for readBlobWithLimit to reject.
const res = isServer
- ? await import('@lobechat/ssrf-safe-fetch').then((m) => m.ssrfSafeFetch(imageUrl))
- : await fetch(imageUrl);
+ ? await import('@lobechat/ssrf-safe-fetch').then((m) =>
+ m.ssrfSafeFetch(
+ imageUrl,
+ init,
+ options.maxBytes ? { maxContentLength: options.maxBytes + 1 } : undefined,
+ ),
+ )
+ : await fetch(imageUrl, init);
const blob = options.maxBytes
? await readBlobWithLimit(res, options.maxBytes)