Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions packages/ai/kimi/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,110 @@
import { smokeTest } from '@profullstack/sh1pt-core/testing';
import { afterEach, describe, expect, it, vi } from 'vitest';
import adapter from './index.js';

smokeTest(adapter, { idPrefix: 'ai' });

const ctx = (
secrets: Record<string, string> = { MOONSHOT_API_KEY: 'test-key' },
dryRun = false,
) => ({
secret: (key: string) => secrets[key],
log: () => {},
dryRun,
});

describe('Kimi generation', () => {
afterEach(() => {
vi.unstubAllGlobals();
});

it('short-circuits dry-run before network calls', async () => {
const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);

const result = await adapter.generate(
ctx({ MOONSHOT_API_KEY: 'test-key' }, true),
'hello',
{},
{},
);

expect(result).toEqual({ text: '[dry-run]', model: 'kimi-k2-0905-preview' });
expect(fetchMock).not.toHaveBeenCalled();
});

it('posts chat completions requests and maps usage tokens', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
model: 'moonshot-v1-8k',
choices: [{ message: { content: 'hi from kimi' } }],
usage: { prompt_tokens: 8, completion_tokens: 3 },
}),
});
vi.stubGlobal('fetch', fetchMock);

const result = await adapter.generate(
ctx(),
'hello',
{
model: 'moonshot-v1-8k',
system: 'be direct',
maxTokens: 64,
temperature: 0.3,
extra: { top_p: 0.8 },
},
{ baseUrl: 'https://kimi.test/v1/' },
);

expect(fetchMock).toHaveBeenCalledOnce();
const [url, request] = fetchMock.mock.calls[0]!;
expect(url).toBe('https://kimi.test/v1/chat/completions');
expect(request.headers.authorization).toBe('Bearer test-key');
expect(request.headers['content-type']).toBe('application/json');
expect(JSON.parse(request.body)).toEqual({
model: 'moonshot-v1-8k',
messages: [
{ role: 'system', content: 'be direct' },
{ role: 'user', content: 'hello' },
],
max_tokens: 64,
temperature: 0.3,
top_p: 0.8,
});
expect(result).toEqual({
text: 'hi from kimi',
model: 'moonshot-v1-8k',
inputTokens: 8,
outputTokens: 3,
});
});

it.each([
['missing scheme', 'kimi.test/v1'],
['ftp scheme', 'ftp://kimi.test/v1'],
['credentials', 'https://user:pass@kimi.test/v1'],
['query string', 'https://kimi.test/v1?token=secret'],
['fragment', 'https://kimi.test/v1#chat'],
])('rejects unclean custom baseUrl values: %s', async (_label, baseUrl) => {
const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);

await expect(adapter.generate(ctx(), 'hello', {}, { baseUrl })).rejects.toThrow(
/Kimi baseUrl/,
);
expect(fetchMock).not.toHaveBeenCalled();
});

it('includes status and response body excerpt on errors', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: false,
status: 401,
text: async () => 'invalid api key'.repeat(30),
}));

await expect(adapter.generate(ctx(), 'hello', {}, {})).rejects.toThrow(
/kimi 401: invalid api key/,
);
});
});
22 changes: 21 additions & 1 deletion packages/ai/kimi/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ export default defineAi<Config>({
if (opts.system) messages.push({ role: 'system', content: opts.system });
messages.push({ role: 'user', content: prompt });

const res = await fetch(`${config.baseUrl ?? DEFAULT_BASE}/chat/completions`, {
const baseUrl = cleanBaseUrl(config.baseUrl ?? DEFAULT_BASE);
const res = await fetch(`${baseUrl}/chat/completions`, {
method: 'POST',
headers: {
authorization: `Bearer ${apiKey}`,
Expand Down Expand Up @@ -69,3 +70,22 @@ export default defineAi<Config>({
],
}),
});

function cleanBaseUrl(value: string): string {
let url: URL;
try {
url = new URL(value);
} catch {
throw new Error('Kimi baseUrl must be a valid URL');
}

if (url.protocol !== 'https:' && url.protocol !== 'http:') {
throw new Error('Kimi baseUrl must use http or https');
}

if (url.username || url.password || url.search || url.hash) {
throw new Error('Kimi baseUrl must be a clean API base without credentials, query, or hash');
}

return url.toString().replace(/\/+$/, '');
}
Loading