kimi-vercel-ai-sdk-provider 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/LICENSE +198 -0
  2. package/README.md +871 -0
  3. package/dist/index.d.mts +1317 -0
  4. package/dist/index.d.ts +1317 -0
  5. package/dist/index.js +2764 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/index.mjs +2734 -0
  8. package/dist/index.mjs.map +1 -0
  9. package/package.json +70 -0
  10. package/src/__tests__/caching.test.ts +97 -0
  11. package/src/__tests__/chat.test.ts +386 -0
  12. package/src/__tests__/code-integration.test.ts +562 -0
  13. package/src/__tests__/code-provider.test.ts +289 -0
  14. package/src/__tests__/code.test.ts +427 -0
  15. package/src/__tests__/core.test.ts +172 -0
  16. package/src/__tests__/files.test.ts +185 -0
  17. package/src/__tests__/integration.test.ts +457 -0
  18. package/src/__tests__/provider.test.ts +188 -0
  19. package/src/__tests__/tools.test.ts +519 -0
  20. package/src/chat/index.ts +42 -0
  21. package/src/chat/kimi-chat-language-model.ts +829 -0
  22. package/src/chat/kimi-chat-messages.ts +297 -0
  23. package/src/chat/kimi-chat-response.ts +84 -0
  24. package/src/chat/kimi-chat-settings.ts +216 -0
  25. package/src/code/index.ts +66 -0
  26. package/src/code/kimi-code-language-model.ts +669 -0
  27. package/src/code/kimi-code-messages.ts +303 -0
  28. package/src/code/kimi-code-provider.ts +239 -0
  29. package/src/code/kimi-code-settings.ts +193 -0
  30. package/src/code/kimi-code-types.ts +354 -0
  31. package/src/core/errors.ts +140 -0
  32. package/src/core/index.ts +36 -0
  33. package/src/core/types.ts +148 -0
  34. package/src/core/utils.ts +210 -0
  35. package/src/files/attachment-processor.ts +276 -0
  36. package/src/files/file-utils.ts +257 -0
  37. package/src/files/index.ts +24 -0
  38. package/src/files/kimi-file-client.ts +292 -0
  39. package/src/index.ts +122 -0
  40. package/src/kimi-provider.ts +263 -0
  41. package/src/tools/builtin-tools.ts +273 -0
  42. package/src/tools/index.ts +33 -0
  43. package/src/tools/prepare-tools.ts +306 -0
  44. package/src/version.ts +4 -0
@@ -0,0 +1,263 @@
1
+ /**
2
+ * Kimi provider factory.
3
+ * @module
4
+ */
5
+
6
+ import { type LanguageModelV3, NoSuchModelError, type ProviderV3 } from '@ai-sdk/provider';
7
+ import {
8
+ type FetchFunction,
9
+ loadApiKey,
10
+ loadOptionalSetting,
11
+ withUserAgentSuffix,
12
+ withoutTrailingSlash
13
+ } from '@ai-sdk/provider-utils';
14
+ import { KimiChatLanguageModel, type KimiChatModelId, type KimiChatSettings } from './chat';
15
+ import { KimiFileClient } from './files';
16
+ import { kimiTools } from './tools';
17
+ import { VERSION } from './version';
18
+
19
+ // ============================================================================
20
+ // Constants
21
+ // ============================================================================
22
+
23
+ const GLOBAL_BASE_URL = 'https://api.moonshot.ai/v1';
24
+ const CN_BASE_URL = 'https://api.moonshot.cn/v1';
25
+
26
+ // ============================================================================
27
+ // Provider Settings
28
+ // ============================================================================
29
+
30
+ /**
31
+ * Settings for creating a Kimi provider instance.
32
+ */
33
+ export interface KimiProviderSettings {
34
+ /**
35
+ * Moonshot AI API key. Defaults to the MOONSHOT_API_KEY environment variable.
36
+ */
37
+ apiKey?: string;
38
+
39
+ /**
40
+ * Base URL override. Defaults to the global or China endpoint.
41
+ */
42
+ baseURL?: string;
43
+
44
+ /**
45
+ * Select the regional endpoint when baseURL is not provided.
46
+ * - `global`: Use the global API endpoint (api.moonshot.ai)
47
+ * - `cn`: Use the China API endpoint (api.moonshot.cn)
48
+ *
49
+ * @default 'global'
50
+ */
51
+ endpoint?: 'global' | 'cn';
52
+
53
+ /**
54
+ * Default headers for all requests.
55
+ */
56
+ headers?: Record<string, string | undefined>;
57
+
58
+ /**
59
+ * Custom fetch implementation.
60
+ */
61
+ fetch?: FetchFunction;
62
+
63
+ /**
64
+ * ID generator for tool call fallback IDs.
65
+ */
66
+ generateId?: () => string;
67
+
68
+ /**
69
+ * Enable JSON schema structured outputs by default.
70
+ */
71
+ supportsStructuredOutputs?: boolean;
72
+
73
+ /**
74
+ * Include usage details in streaming responses if supported.
75
+ */
76
+ includeUsageInStream?: boolean;
77
+
78
+ /**
79
+ * Override supported URL patterns for file parts.
80
+ */
81
+ supportedUrls?: LanguageModelV3['supportedUrls'];
82
+ }
83
+
84
+ // ============================================================================
85
+ // Provider Interface
86
+ // ============================================================================
87
+
88
+ /**
89
+ * The Kimi provider interface.
90
+ */
91
+ export interface KimiProvider extends Omit<ProviderV3, 'specificationVersion'> {
92
+ specificationVersion: 'v3';
93
+
94
+ /**
95
+ * Creates a chat language model.
96
+ * @param modelId - The model identifier
97
+ * @param settings - Optional model settings
98
+ */
99
+ (modelId: KimiChatModelId, settings?: KimiChatSettings): LanguageModelV3;
100
+
101
+ /**
102
+ * Creates a chat language model.
103
+ * @param modelId - The model identifier
104
+ * @param settings - Optional model settings
105
+ */
106
+ languageModel(modelId: KimiChatModelId, settings?: KimiChatSettings): LanguageModelV3;
107
+
108
+ /**
109
+ * Creates a chat language model (alias for languageModel).
110
+ * @param modelId - The model identifier
111
+ * @param settings - Optional model settings
112
+ */
113
+ chat(modelId: KimiChatModelId, settings?: KimiChatSettings): LanguageModelV3;
114
+
115
+ /**
116
+ * Built-in tools that can be used with Kimi models.
117
+ */
118
+ tools: typeof kimiTools;
119
+
120
+ /**
121
+ * File client for uploading and extracting content from files.
122
+ * Pre-configured with the provider's API key and base URL.
123
+ *
124
+ * @example
125
+ * ```ts
126
+ * const kimi = createKimi();
127
+ * const result = await kimi.files.uploadAndExtract({
128
+ * data: pdfBuffer,
129
+ * filename: 'document.pdf',
130
+ * });
131
+ * console.log(result.content);
132
+ * ```
133
+ */
134
+ files: KimiFileClient;
135
+ }
136
+
137
+ // ============================================================================
138
+ // Provider Factory
139
+ // ============================================================================
140
+
141
+ /**
142
+ * Create a Kimi provider instance.
143
+ *
144
+ * @param options - Provider settings
145
+ * @returns A configured Kimi provider
146
+ *
147
+ * @example
148
+ * ```ts
149
+ * import { createKimi } from 'kimi-vercel-ai-sdk-provider
150
+ ';
151
+ *
152
+ * const kimi = createKimi({
153
+ * apiKey: process.env.MOONSHOT_API_KEY,
154
+ * });
155
+ *
156
+ * const result = await generateText({
157
+ * model: kimi('kimi-k2.5'),
158
+ * prompt: 'Hello!',
159
+ * });
160
+ * ```
161
+ *
162
+ * @example
163
+ * ```ts
164
+ * // With web search enabled
165
+ * const result = await generateText({
166
+ * model: kimi('kimi-k2.5', { webSearch: true }),
167
+ * prompt: 'What are the latest AI news?',
168
+ * });
169
+ * ```
170
+ *
171
+ * @example
172
+ * ```ts
173
+ * // With code interpreter
174
+ * const result = await generateText({
175
+ * model: kimi('kimi-k2.5', { codeInterpreter: true }),
176
+ * prompt: 'Calculate the factorial of 20',
177
+ * });
178
+ * ```
179
+ */
180
+ export function createKimi(options: KimiProviderSettings = {}): KimiProvider {
181
+ const resolvedBaseURL =
182
+ loadOptionalSetting({
183
+ settingValue: options.baseURL,
184
+ environmentVariableName: 'MOONSHOT_BASE_URL'
185
+ }) ?? (options.endpoint === 'cn' ? CN_BASE_URL : GLOBAL_BASE_URL);
186
+
187
+ const baseURL = withoutTrailingSlash(resolvedBaseURL) ?? GLOBAL_BASE_URL;
188
+
189
+ const getHeaders = () =>
190
+ withUserAgentSuffix(
191
+ {
192
+ Authorization: `Bearer ${loadApiKey({
193
+ apiKey: options.apiKey,
194
+ environmentVariableName: 'MOONSHOT_API_KEY',
195
+ description: 'Moonshot'
196
+ })}`,
197
+ ...options.headers
198
+ },
199
+ `ai-sdk/kimi/${VERSION}`
200
+ );
201
+
202
+ const createChatModel = (modelId: KimiChatModelId, settings: KimiChatSettings = {}) =>
203
+ new KimiChatLanguageModel(modelId, settings, {
204
+ provider: 'kimi.chat',
205
+ baseURL,
206
+ headers: getHeaders,
207
+ fetch: options.fetch,
208
+ generateId: options.generateId,
209
+ supportsStructuredOutputs: settings.supportsStructuredOutputs ?? options.supportsStructuredOutputs,
210
+ includeUsageInStream: settings.includeUsageInStream ?? options.includeUsageInStream,
211
+ supportedUrls: settings.supportedUrls ?? options.supportedUrls
212
+ });
213
+
214
+ const provider: KimiProvider = (modelId: KimiChatModelId, settings?: KimiChatSettings): KimiChatLanguageModel => {
215
+ if (new.target) {
216
+ throw new Error('The Kimi provider function cannot be called with new.');
217
+ }
218
+
219
+ return createChatModel(modelId, settings);
220
+ };
221
+
222
+ provider.specificationVersion = 'v3';
223
+ provider.languageModel = createChatModel;
224
+ provider.chat = createChatModel;
225
+ provider.tools = kimiTools;
226
+ provider.files = new KimiFileClient({
227
+ baseURL,
228
+ headers: getHeaders,
229
+ fetch: options.fetch
230
+ });
231
+
232
+ provider.embeddingModel = (modelId: string) => {
233
+ throw new NoSuchModelError({ modelId, modelType: 'embeddingModel' });
234
+ };
235
+
236
+ provider.imageModel = (modelId: string) => {
237
+ throw new NoSuchModelError({ modelId, modelType: 'imageModel' });
238
+ };
239
+
240
+ provider.rerankingModel = (modelId: string) => {
241
+ throw new NoSuchModelError({ modelId, modelType: 'rerankingModel' });
242
+ };
243
+
244
+ return provider;
245
+ }
246
+
247
+ /**
248
+ * Default Kimi provider instance.
249
+ *
250
+ * Uses the MOONSHOT_API_KEY environment variable for authentication.
251
+ *
252
+ * @example
253
+ * ```ts
254
+ * import { kimi } from 'kimi-vercel-ai-sdk-provider
255
+ ';
256
+ *
257
+ * const result = await generateText({
258
+ * model: kimi('kimi-k2.5'),
259
+ * prompt: 'Hello!',
260
+ * });
261
+ * ```
262
+ */
263
+ export const kimi = createKimi();
@@ -0,0 +1,273 @@
1
+ /**
2
+ * Built-in tools for Kimi API.
3
+ *
4
+ * Kimi provides server-side tools that can be invoked during chat completions:
5
+ * - `$web_search`: Search the web for information
6
+ * - `$code`: Execute code using Kimi's code interpreter
7
+ *
8
+ * @module
9
+ */
10
+
11
+ // ============================================================================
12
+ // Constants
13
+ // ============================================================================
14
+
15
+ /**
16
+ * Kimi's built-in web search tool identifier.
17
+ * This tool allows Kimi to search the web for up-to-date information.
18
+ */
19
+ export const KIMI_WEB_SEARCH_TOOL_NAME = '$web_search';
20
+
21
+ /**
22
+ * Kimi's built-in code interpreter tool identifier.
23
+ * This tool allows Kimi to execute code and return results.
24
+ */
25
+ export const KIMI_CODE_INTERPRETER_TOOL_NAME = '$code';
26
+
27
+ // ============================================================================
28
+ // Types
29
+ // ============================================================================
30
+
31
+ /**
32
+ * Configuration for Kimi's built-in web search tool.
33
+ */
34
+ export interface KimiWebSearchConfig {
35
+ /**
36
+ * Whether to include search results in the response.
37
+ * When true, the search results will be included in the tool output.
38
+ */
39
+ search_result?: boolean;
40
+ /**
41
+ * Allow additional configuration options.
42
+ */
43
+ [key: string]: unknown;
44
+ }
45
+
46
+ /**
47
+ * Configuration for Kimi's built-in code interpreter tool.
48
+ */
49
+ export interface KimiCodeInterpreterConfig {
50
+ /**
51
+ * Maximum execution time in seconds.
52
+ * Default varies by model and API tier.
53
+ */
54
+ timeout?: number;
55
+
56
+ /**
57
+ * Whether to return execution output.
58
+ * When true, stdout/stderr will be included in results.
59
+ */
60
+ include_output?: boolean;
61
+
62
+ /**
63
+ * Allow additional configuration options.
64
+ */
65
+ [key: string]: unknown;
66
+ }
67
+
68
+ /**
69
+ * A Kimi built-in tool definition.
70
+ * These are handled server-side by Kimi's API.
71
+ */
72
+ export interface KimiBuiltinTool {
73
+ type: 'builtin_function';
74
+ function: {
75
+ name: string;
76
+ config?: Record<string, unknown>;
77
+ };
78
+ }
79
+
80
+ // ============================================================================
81
+ // Web Search Tool
82
+ // ============================================================================
83
+
84
+ /**
85
+ * Configuration options for the web search tool.
86
+ */
87
+ export interface KimiWebSearchToolOptions {
88
+ /**
89
+ * Whether the web search tool is enabled.
90
+ */
91
+ enabled: boolean;
92
+
93
+ /**
94
+ * Optional configuration for the web search tool.
95
+ */
96
+ config?: KimiWebSearchConfig;
97
+ }
98
+
99
+ export type KimiWebSearchToolConfig = KimiWebSearchToolOptions;
100
+
101
+ /**
102
+ * Create a Kimi built-in web search tool definition.
103
+ *
104
+ * @param config - Optional configuration for the web search tool
105
+ * @returns A built-in tool definition for $web_search
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * // Basic usage
110
+ * const tool = createWebSearchTool();
111
+ *
112
+ * // With configuration
113
+ * const tool = createWebSearchTool({ search_result: true });
114
+ * ```
115
+ */
116
+ export function createWebSearchTool(config?: KimiWebSearchConfig): KimiBuiltinTool {
117
+ return {
118
+ type: 'builtin_function',
119
+ function: {
120
+ name: KIMI_WEB_SEARCH_TOOL_NAME,
121
+ ...(config ? { config } : {})
122
+ }
123
+ };
124
+ }
125
+
126
+ export function createKimiWebSearchTool(config?: KimiWebSearchConfig): KimiBuiltinTool {
127
+ return createWebSearchTool(config);
128
+ }
129
+
130
+ // ============================================================================
131
+ // Code Interpreter Tool
132
+ // ============================================================================
133
+
134
+ /**
135
+ * Configuration options for the code interpreter tool.
136
+ */
137
+ export interface KimiCodeInterpreterToolOptions {
138
+ /**
139
+ * Whether the code interpreter tool is enabled.
140
+ */
141
+ enabled: boolean;
142
+
143
+ /**
144
+ * Optional configuration for the code interpreter tool.
145
+ */
146
+ config?: KimiCodeInterpreterConfig;
147
+ }
148
+
149
+ /**
150
+ * Create a Kimi built-in code interpreter tool definition.
151
+ *
152
+ * @param config - Optional configuration for the code interpreter tool
153
+ * @returns A built-in tool definition for $code
154
+ *
155
+ * @example
156
+ * ```ts
157
+ * // Basic usage
158
+ * const tool = createCodeInterpreterTool();
159
+ *
160
+ * // With configuration
161
+ * const tool = createCodeInterpreterTool({ timeout: 30, include_output: true });
162
+ * ```
163
+ */
164
+ export function createCodeInterpreterTool(config?: KimiCodeInterpreterConfig): KimiBuiltinTool {
165
+ return {
166
+ type: 'builtin_function',
167
+ function: {
168
+ name: KIMI_CODE_INTERPRETER_TOOL_NAME,
169
+ ...(config ? { config } : {})
170
+ }
171
+ };
172
+ }
173
+
174
+ // ============================================================================
175
+ // Utilities
176
+ // ============================================================================
177
+
178
+ /**
179
+ * Check if a tool name is a Kimi built-in tool.
180
+ * Built-in tools are prefixed with '$'.
181
+ *
182
+ * @param toolName - The tool name to check
183
+ * @returns True if the tool is a built-in tool
184
+ */
185
+ export function isBuiltinToolName(toolName: string): boolean {
186
+ return toolName.startsWith('$');
187
+ }
188
+
189
+ /**
190
+ * Check if a tool name is the web search tool.
191
+ *
192
+ * @param toolName - The tool name to check
193
+ * @returns True if the tool is the web search tool
194
+ */
195
+ export function isWebSearchTool(toolName: string): boolean {
196
+ return toolName === KIMI_WEB_SEARCH_TOOL_NAME;
197
+ }
198
+
199
+ /**
200
+ * Check if a tool name is the code interpreter tool.
201
+ *
202
+ * @param toolName - The tool name to check
203
+ * @returns True if the tool is the code interpreter tool
204
+ */
205
+ export function isCodeInterpreterTool(toolName: string): boolean {
206
+ return toolName === KIMI_CODE_INTERPRETER_TOOL_NAME;
207
+ }
208
+
209
+ // ============================================================================
210
+ // Provider Tool Definitions
211
+ // ============================================================================
212
+
213
+ /**
214
+ * Create provider-level tool definitions for use with the AI SDK.
215
+ * These can be passed directly to the tools option.
216
+ */
217
+ export const kimiTools = {
218
+ /**
219
+ * Create a web search tool for use with Kimi models.
220
+ *
221
+ * @param config - Optional configuration
222
+ * @returns A provider tool definition
223
+ *
224
+ * @example
225
+ * ```ts
226
+ * import { kimi, kimiTools } from 'kimi-vercel-ai-sdk-provider
227
+ ';
228
+ *
229
+ * const result = await generateText({
230
+ * model: kimi('kimi-k2.5'),
231
+ * tools: {
232
+ * webSearch: kimiTools.webSearch(),
233
+ * },
234
+ * prompt: 'What are the latest AI news?',
235
+ * });
236
+ * ```
237
+ */
238
+ webSearch: (config?: KimiWebSearchConfig) => {
239
+ return {
240
+ type: 'provider' as const,
241
+ id: 'kimi.webSearch',
242
+ args: createWebSearchTool(config)
243
+ };
244
+ },
245
+
246
+ /**
247
+ * Create a code interpreter tool for use with Kimi models.
248
+ *
249
+ * @param config - Optional configuration
250
+ * @returns A provider tool definition
251
+ *
252
+ * @example
253
+ * ```ts
254
+ * import { kimi, kimiTools } from 'kimi-vercel-ai-sdk-provider
255
+ ';
256
+ *
257
+ * const result = await generateText({
258
+ * model: kimi('kimi-k2.5'),
259
+ * tools: {
260
+ * codeInterpreter: kimiTools.codeInterpreter(),
261
+ * },
262
+ * prompt: 'Calculate the factorial of 10',
263
+ * });
264
+ * ```
265
+ */
266
+ codeInterpreter: (config?: KimiCodeInterpreterConfig) => {
267
+ return {
268
+ type: 'provider' as const,
269
+ id: 'kimi.codeInterpreter',
270
+ args: createCodeInterpreterTool(config)
271
+ };
272
+ }
273
+ };
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Tools module exports.
3
+ * @module
4
+ */
5
+
6
+ export type {
7
+ KimiBuiltinTool,
8
+ KimiCodeInterpreterConfig,
9
+ KimiCodeInterpreterToolOptions,
10
+ KimiWebSearchConfig,
11
+ KimiWebSearchToolConfig,
12
+ KimiWebSearchToolOptions
13
+ } from './builtin-tools';
14
+ export type {
15
+ KimiFunctionTool,
16
+ KimiTool,
17
+ PrepareToolsOptions,
18
+ PrepareToolsResult
19
+ } from './prepare-tools';
20
+ // Built-in tools
21
+ export {
22
+ KIMI_CODE_INTERPRETER_TOOL_NAME,
23
+ KIMI_WEB_SEARCH_TOOL_NAME,
24
+ createCodeInterpreterTool,
25
+ createKimiWebSearchTool,
26
+ createWebSearchTool,
27
+ isBuiltinToolName,
28
+ isCodeInterpreterTool,
29
+ isWebSearchTool,
30
+ kimiTools
31
+ } from './builtin-tools';
32
+ // Tool preparation
33
+ export { prepareKimiTools } from './prepare-tools';