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: use Anthropic SDK for Kimi Coding Plan provider (#13345)

Hardy59d8d878a2ca
diff --git a/packages/model-bank/src/aiModels/kimiCodingPlan.ts b/packages/model-bank/src/aiModels/kimiCodingPlan.ts
index 9c062aba8f9..1888b04aa3e 100644
--- a/packages/model-bank/src/aiModels/kimiCodingPlan.ts
+++ b/packages/model-bank/src/aiModels/kimiCodingPlan.ts
@@ -15,7 +15,7 @@ const kimiCodingPlanChatModels: AIChatModelCard[] = [
"Kimi K2.5 is Kimi's most versatile model to date, featuring a native multimodal architecture that supports both vision and text inputs, 'thinking' and 'non-thinking' modes, and both conversational and agent tasks.",
displayName: 'Kimi K2.5',
enabled: true,
- id: 'kimi-k2.5',
+ id: 'k2p5',
maxOutput: 32_768,
organization: 'Moonshot',
releasedAt: '2026-01-27',
@@ -24,20 +24,6 @@ const kimiCodingPlanChatModels: AIChatModelCard[] = [
},
type: 'chat',
},
- {
- abilities: {
- functionCall: true,
- },
- contextWindowTokens: 131_072,
- description:
- 'Kimi K2: MoE architecture base model with exceptional code and Agent capabilities.',
- displayName: 'Kimi K2',
- id: 'kimi-k2',
- maxOutput: 65_536,
- organization: 'Moonshot',
- releasedAt: '2025-07-01',
- type: 'chat',
- },
{
abilities: {
functionCall: true,
diff --git a/packages/model-bank/src/modelProviders/kimiCodingPlan.ts b/packages/model-bank/src/modelProviders/kimiCodingPlan.ts
index ab0f3c23c9a..9c939644ac1 100644
--- a/packages/model-bank/src/modelProviders/kimiCodingPlan.ts
+++ b/packages/model-bank/src/modelProviders/kimiCodingPlan.ts
@@ -3,7 +3,7 @@ import type { ModelProviderCard } from '@/types/llm';
// ref: https://platform.moonshot.ai/docs
const KimiCodingPlan: ModelProviderCard = {
chatModels: [],
- checkModel: 'kimi-k2.5',
+ checkModel: 'k2p5',
description:
'Kimi Code from Moonshot AI provides access to Kimi models including K2.5 for coding tasks.',
disableBrowserRequest: true,
@@ -14,13 +14,13 @@ const KimiCodingPlan: ModelProviderCard = {
settings: {
disableBrowserRequest: true,
proxyUrl: {
- placeholder: 'https://api.kimi.com/coding/v1',
+ placeholder: 'https://api.kimi.com/coding',
},
responseAnimation: {
speed: 2,
text: 'smooth',
},
- sdkType: 'openai',
+ sdkType: 'anthropic',
showDeployName: true,
showModelFetcher: false,
},
diff --git a/packages/model-runtime/src/providers/kimiCodingPlan/index.test.ts b/packages/model-runtime/src/providers/kimiCodingPlan/index.test.ts
index 27d80c86494..3a440421d3e 100644
--- a/packages/model-runtime/src/providers/kimiCodingPlan/index.test.ts
+++ b/packages/model-runtime/src/providers/kimiCodingPlan/index.test.ts
@@ -1,19 +1,354 @@
// @vitest-environment node
import { ModelProvider } from 'model-bank';
+import type { Mock } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { testProvider } from '../../providerTestUtils';
-import { LobeKimiCodingPlanAI } from './index';
+import * as debugStreamModule from '../../utils/debugStream';
+import { LobeKimiCodingPlanAI, params } from './index';
const provider = ModelProvider.KimiCodingPlan;
-const defaultBaseURL = 'https://api.kimi.com/coding/v1';
-
-testProvider({
- Runtime: LobeKimiCodingPlanAI,
- provider,
- defaultBaseURL,
- chatDebugEnv: 'DEBUG_KIMI_CODING_PLAN_CHAT_COMPLETION',
- chatModel: 'kimi-k2.5',
- test: {
- skipAPICall: true,
- },
+const defaultBaseURL = 'https://api.kimi.com/coding';
+
+const bizErrorType = 'ProviderBizError';
+const invalidErrorType = 'InvalidProviderAPIKey';
+
+// Mock the console.error to avoid polluting test output
+vi.spyOn(console, 'error').mockImplementation(() => {});
+
+let instance: InstanceType<typeof LobeKimiCodingPlanAI>;
+
+beforeEach(() => {
+ instance = new LobeKimiCodingPlanAI({ apiKey: 'test' });
+
+ // Use vi.spyOn to mock the Anthropic messages.create call.
+ vi.spyOn(instance['client'].messages, 'create').mockResolvedValue(new ReadableStream() as any);
+});
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('LobeKimiCodingPlanAI', () => {
+ describe('init', () => {
+ it('should correctly initialize with an API key', async () => {
+ const instance = new LobeKimiCodingPlanAI({ apiKey: 'test_api_key' });
+ expect(instance).toBeInstanceOf(LobeKimiCodingPlanAI);
+ expect(instance.baseURL).toBe(defaultBaseURL);
+ });
+
+ it('should correctly initialize with a baseURL', async () => {
+ const instance = new LobeKimiCodingPlanAI({
+ apiKey: 'test_api_key',
+ baseURL: 'https://api.custom.com/coding',
+ });
+ expect(instance).toBeInstanceOf(LobeKimiCodingPlanAI);
+ expect(instance.baseURL).toBe('https://api.custom.com/coding');
+ });
+
+ it('should correctly initialize with different id', async () => {
+ const instance = new LobeKimiCodingPlanAI({
+ apiKey: 'test_api_key',
+ id: 'abc',
+ });
+ expect(instance).toBeInstanceOf(LobeKimiCodingPlanAI);
+ expect(instance['id']).toBe('abc');
+ });
+ });
+
+ describe('params', () => {
+ it('should have correct baseURL', () => {
+ expect(params.baseURL).toBe(defaultBaseURL);
+ });
+
+ it('should have correct provider', () => {
+ expect(params.provider).toBe(provider);
+ });
+ });
+
+ describe('chat', () => {
+ it('should return a StreamingTextResponse on successful API call', async () => {
+ const result = await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'k2p5',
+ temperature: 0,
+ });
+
+ // Assert
+ expect(result).toBeInstanceOf(Response);
+ });
+
+ it('should handle text messages correctly', async () => {
+ // Arrange
+ const mockStream = new ReadableStream({
+ start(controller) {
+ controller.enqueue('Hello, world!');
+ controller.close();
+ },
+ });
+ const mockResponse = Promise.resolve(mockStream);
+ (instance['client'].messages.create as Mock).mockResolvedValue(mockResponse);
+
+ // Act
+ const result = await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'k2p5',
+ temperature: 0,
+ top_p: 1,
+ });
+
+ // Assert
+ expect(instance['client'].messages.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ model: 'k2p5',
+ stream: true,
+ }),
+ expect.objectContaining({}),
+ );
+ expect(result).toBeInstanceOf(Response);
+ });
+
+ it('should call debugStream in DEBUG mode', async () => {
+ // Arrange
+ const mockProdStream = new ReadableStream({
+ start(controller) {
+ controller.enqueue('Hello, world!');
+ controller.close();
+ },
+ }) as any;
+ const mockDebugStream = new ReadableStream({
+ start(controller) {
+ controller.enqueue('Debug stream content');
+ controller.close();
+ },
+ }) as any;
+ mockDebugStream.toReadableStream = () => mockDebugStream;
+
+ (instance['client'].messages.create as Mock).mockResolvedValue({
+ tee: () => [mockProdStream, { toReadableStream: () => mockDebugStream }],
+ });
+
+ const originalDebugValue = process.env.DEBUG_KIMI_CODING_PLAN_CHAT_COMPLETION;
+
+ process.env.DEBUG_KIMI_CODING_PLAN_CHAT_COMPLETION = '1';
+ vi.spyOn(debugStreamModule, 'debugStream').mockImplementation(() => Promise.resolve());
+
+ // Act
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'k2p5',
+ temperature: 0,
+ });
+
+ // Assert
+ expect(debugStreamModule.debugStream).toHaveBeenCalled();
+
+ // Cleanup
+ process.env.DEBUG_KIMI_CODING_PLAN_CHAT_COMPLETION = originalDebugValue;
+ });
+
+ describe('Error', () => {
+ it('should throw InvalidProviderAPIKey error on 401 error', async () => {
+ // Arrange
+ const apiError = {
+ status: 401,
+ error: {
+ type: 'error',
+ error: {
+ type: 'authentication_error',
+ message: 'invalid x-api-key',
+ },
+ },
+ };
+ (instance['client'].messages.create as Mock).mockRejectedValue(apiError);
+
+ try {
+ // Act
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'k2p5',
+ temperature: 0,
+ });
+ } catch (e) {
+ // Assert - endpoint is desensitized for non-default URLs
+ expect(e).toEqual({
+ endpoint: 'https://api.***.com/coding',
+ error: apiError,
+ errorType: invalidErrorType,
+ provider,
+ });
+ }
+ });
+
+ it('should throw BizError error', async () => {
+ // Arrange
+ const apiError = {
+ status: 529,
+ error: {
+ type: 'error',
+ error: {
+ type: 'overloaded_error',
+ message: 'API is temporarily overloaded',
+ },
+ },
+ };
+ (instance['client'].messages.create as Mock).mockRejectedValue(apiError);
+
+ try {
+ // Act
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'k2p5',
+ temperature: 0,
+ });
+ } catch (e) {
+ // Assert - endpoint is desensitized for non-default URLs
+ expect(e).toEqual({
+ endpoint: 'https://api.***.com/coding',
+ error: apiError.error.error,
+ errorType: bizErrorType,
+ provider,
+ });
+ }
+ });
+
+ it('should throw InvalidProviderAPIKey if no apiKey is provided', async () => {
+ try {
+ new LobeKimiCodingPlanAI({});
+ } catch (e) {
+ expect(e).toEqual({ errorType: invalidErrorType });
+ }
+ });
+ });
+
+ describe('Error handling', () => {
+ it('should throw LocationNotSupportError on 403 error', async () => {
+ // Arrange
+ const apiError = { status: 403 };
+ (instance['client'].messages.create as Mock).mockRejectedValue(apiError);
+
+ // Act & Assert - endpoint is desensitized for non-default URLs
+ await expect(
+ instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'k2p5',
+ temperature: 1,
+ }),
+ ).rejects.toEqual({
+ endpoint: 'https://api.***.com/coding',
+ error: apiError,
+ errorType: 'LocationNotSupportError',
+ provider,
+ });
+ });
+
+ it('should throw ProviderBizError on other error status codes', async () => {
+ // Arrange
+ const apiError = { status: 500 };
+ (instance['client'].messages.create as Mock).mockRejectedValue(apiError);
+
+ // Act & Assert - endpoint is desensitized for non-default URLs
+ await expect(
+ instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'k2p5',
+ temperature: 1,
+ }),
+ ).rejects.toEqual({
+ endpoint: 'https://api.***.com/coding',
+ error: {
+ headers: undefined,
+ stack: undefined,
+ status: 500,
+ },
+ errorType: bizErrorType,
+ provider,
+ });
+ });
+
+ it('should desensitize custom baseURL in error message', async () => {
+ // Arrange
+ const apiError = { status: 401 };
+ const customInstance = new LobeKimiCodingPlanAI({
+ apiKey: 'test',
+ baseURL: 'https://api.custom.com/coding',
+ });
+ vi.spyOn(customInstance['client'].messages, 'create').mockRejectedValue(apiError);
+
+ // Act & Assert
+ await expect(
+ customInstance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'k2p5',
+ temperature: 0,
+ }),
+ ).rejects.toEqual({
+ endpoint: 'https://api.cu****om.com/coding',
+ error: apiError,
+ errorType: invalidErrorType,
+ provider,
+ });
+ });
+ });
+
+ describe('Options', () => {
+ it('should pass signal to API call', async () => {
+ // Arrange
+ const controller = new AbortController();
+
+ // Act
+ await instance.chat(
+ {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'k2p5',
+ temperature: 1,
+ },
+ { signal: controller.signal },
+ );
+
+ // Assert
+ expect(instance['client'].messages.create).toHaveBeenCalledWith(
+ expect.objectContaining({}),
+ expect.objectContaining({ signal: controller.signal }),
+ );
+ });
+
+ it('should apply callback to the returned stream', async () => {
+ // Arrange
+ const callback = vi.fn();
+
+ // Act
+ await instance.chat(
+ {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'k2p5',
+ temperature: 0,
+ },
+ {
+ callback: { onStart: callback },
+ },
+ );
+
+ // Assert
+ expect(callback).toHaveBeenCalled();
+ });
+
+ it('should set headers on the response', async () => {
+ // Arrange
+ const headers = { 'X-Test-Header': 'test' };
+
+ // Act
+ const result = await instance.chat(
+ {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'k2p5',
+ temperature: 1,
+ },
+ { headers },
+ );
+
+ // Assert
+ expect(result.headers.get('X-Test-Header')).toBe('test');
+ });
+ });
+ });
});
diff --git a/packages/model-runtime/src/providers/kimiCodingPlan/index.ts b/packages/model-runtime/src/providers/kimiCodingPlan/index.ts
index 3e80fb8b6f6..515c56ebb31 100644
--- a/packages/model-runtime/src/providers/kimiCodingPlan/index.ts
+++ b/packages/model-runtime/src/providers/kimiCodingPlan/index.ts
@@ -1,33 +1,44 @@
+import type Anthropic from '@anthropic-ai/sdk';
import { ModelProvider } from 'model-bank';
-import { createOpenAICompatibleRuntime } from '../../core/openaiCompatibleFactory';
+import {
+ buildDefaultAnthropicPayload,
+ createAnthropicCompatibleParams,
+ createAnthropicCompatibleRuntime,
+} from '../../core/anthropicCompatibleFactory';
+import type { ChatStreamPayload } from '../../types';
+import { getModelPropertyWithFallback } from '../../utils/getFallbackModelProperty';
import { processMultiProviderModelList } from '../../utils/modelParse';
-export const LobeKimiCodingPlanAI = createOpenAICompatibleRuntime({
- baseURL: 'https://api.kimi.com/coding/v1',
- chatCompletion: {
- handlePayload: (payload) => {
- const { model, thinking, ...rest } = payload;
+const DEFAULT_KIMI_CODING_BASE_URL = 'https://api.kimi.com/coding';
+
+const buildKimiCodingPlanAnthropicPayload = async (
+ payload: ChatStreamPayload,
+): Promise<Anthropic.MessageCreateParams> => {
+ const resolvedMaxTokens =
+ payload.max_tokens ??
+ (await getModelPropertyWithFallback<number | undefined>(
+ payload.model,
+ 'maxOutput',
+ ModelProvider.KimiCodingPlan,
+ )) ??
+ 8192;
+
+ return buildDefaultAnthropicPayload({
+ ...payload,
+ max_tokens: resolvedMaxTokens,
+ });
+};
- return {
- ...rest,
- ...(thinking?.type === 'enabled' &&
- thinking?.budget_tokens !== 0 && {
- enable_thinking: true,
- thinking_budget: thinking?.budget_tokens || undefined,
- }),
- model,
- stream: true,
- ...(payload.tools && {
- parallel_tool_calls: true,
- }),
- } as any;
- },
+export const params = createAnthropicCompatibleParams({
+ baseURL: DEFAULT_KIMI_CODING_BASE_URL,
+ chatCompletion: {
+ handlePayload: buildKimiCodingPlanAnthropicPayload,
},
debug: {
chatCompletion: () => process.env.DEBUG_KIMI_CODING_PLAN_CHAT_COMPLETION === '1',
},
- models: async () => {
+ models: async ({ client }) => {
const { kimicodingplan } = await import('model-bank');
return processMultiProviderModelList(
kimicodingplan.map((m: { id: string }) => ({ id: m.id })),
@@ -36,3 +47,7 @@ export const LobeKimiCodingPlanAI = createOpenAICompatibleRuntime({
},
provider: ModelProvider.KimiCodingPlan,
});
+
+export const LobeKimiCodingPlanAI = createAnthropicCompatibleRuntime(params);
+
+export default LobeKimiCodingPlanAI;