diff --git a/packages/ai/baseten/src/index.test.ts b/packages/ai/baseten/src/index.test.ts index f43ad207..74a16e93 100644 --- a/packages/ai/baseten/src/index.test.ts +++ b/packages/ai/baseten/src/index.test.ts @@ -1,4 +1,121 @@ 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 = { BASETEN_API_KEY: 'test-key' }, dryRun = false) => ({ + secret: (key: string) => secrets[key], + log: () => {}, + dryRun, +}); + +describe('Baseten OpenAI-compatible 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({ BASETEN_API_KEY: 'test-key' }, true), 'hello', {}, {}); + + expect(result).toEqual({ text: '[dry-run]', model: 'deepseek-ai/DeepSeek-V4-Pro' }); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('posts chat completions requests and maps usage tokens', async () => { + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + choices: [{ message: { content: 'hi from baseten' } }], + model: 'openai/gpt-oss-120b', + usage: { prompt_tokens: 7, completion_tokens: 3 }, + }), + }); + vi.stubGlobal('fetch', fetchMock); + + const result = await adapter.generate(ctx(), 'hello', { + model: 'openai/gpt-oss-120b', + system: 'be brief', + maxTokens: 20, + temperature: 0.2, + extra: { top_p: 0.9 }, + }, {}); + + expect(fetchMock).toHaveBeenCalledOnce(); + const call = fetchMock.mock.calls[0]; + expect(call).toBeDefined(); + const [url, request] = call!; + expect(url).toBe('https://inference.baseten.co/v1/chat/completions'); + expect(request.headers.authorization).toBe('Bearer test-key'); + expect(JSON.parse(request.body)).toEqual({ + model: 'openai/gpt-oss-120b', + messages: [ + { role: 'system', content: 'be brief' }, + { role: 'user', content: 'hello' }, + ], + max_tokens: 20, + temperature: 0.2, + top_p: 0.9, + }); + expect(result).toEqual({ + text: 'hi from baseten', + model: 'openai/gpt-oss-120b', + inputTokens: 7, + outputTokens: 3, + }); + }); + + it('normalizes configured base URLs with trailing slashes', async () => { + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ choices: [{ message: { content: 'ok' } }], model: 'deepseek-ai/DeepSeek-V4-Pro' }), + }); + vi.stubGlobal('fetch', fetchMock); + + await adapter.generate(ctx(), 'hello', {}, { baseUrl: 'https://proxy.example.com/' }); + + const [url] = fetchMock.mock.calls[0]!; + expect(url).toBe('https://proxy.example.com/v1/chat/completions'); + }); + + it.each([ + ['missing scheme', 'proxy.example.com'], + ['unsupported scheme', 'ftp://proxy.example.com'], + ['credentials', 'https://user:pass@proxy.example.com'], + ['query string', 'https://proxy.example.com?debug=true'], + ['fragment', 'https://proxy.example.com#v1'], + ])('rejects unclean configured base URLs: %s', async (_case, baseUrl) => { + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + + await expect(adapter.generate(ctx(), 'hello', {}, { baseUrl })).rejects.toThrow( + /Baseten baseUrl/, + ); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('includes status and redacted response body excerpt on errors', async () => { + const apiKey = 'test-key-crossing-truncation-boundary'; + const prefix = 'x'.repeat(190); + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ + ok: false, + status: 429, + text: async () => `${prefix}${apiKey} rate limited`, + })); + + let error: unknown; + try { + await adapter.generate(ctx({ BASETEN_API_KEY: apiKey }), 'hello', {}, {}); + } catch (exc) { + error = exc; + } + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toContain('Baseten 429:'); + expect((error as Error).message).toContain('[redacted]'); + expect((error as Error).message).not.toContain(apiKey); + expect((error as Error).message).not.toContain(apiKey.slice(0, 10)); + }); +}); diff --git a/packages/ai/baseten/src/index.ts b/packages/ai/baseten/src/index.ts index 5803d1ae..e0f2bd1f 100644 --- a/packages/ai/baseten/src/index.ts +++ b/packages/ai/baseten/src/index.ts @@ -4,25 +4,88 @@ interface Config { baseUrl?: string; } +const DEFAULT_BASE = 'https://inference.baseten.co'; + +function chatCompletionsUrl(baseUrl?: string): string { + return `${cleanBaseUrl(baseUrl ?? DEFAULT_BASE)}/v1/chat/completions`; +} + +function cleanBaseUrl(value: string): string { + let url: URL; + try { + url = new URL(value); + } catch { + throw new Error('Baseten baseUrl must be a valid URL'); + } + if (url.protocol !== 'https:' && url.protocol !== 'http:') { + throw new Error('Baseten baseUrl must use http or https'); + } + if (url.username || url.password || url.search || url.hash) { + throw new Error('Baseten baseUrl must be a clean API base without credentials, query, or hash'); + } + return url.toString().replace(/\/+$/, ''); +} + +function redact(value: string, apiKey: string): string { + return apiKey ? value.split(apiKey).join('[redacted]') : value; +} + export default defineAi({ id: 'ai-baseten', label: 'Baseten', - defaultModel: 'BASETEN_API_KEY', - models: ['BASETEN_API_KEY'], - - async generate(ctx, prompt, _opts, _config) { - const apiKey = ctx.secret('https://www.baseten.co'); - if (!apiKey) throw new Error('https://www.baseten.co not in vault — run `sh1pt promote ai setup`'); - ctx.log(`[stub] ai-baseten · ${prompt.length} chars in — integration pending`); - return { text: '[stub — ai-baseten integration not yet implemented]', model: 'BASETEN_API_KEY' }; + defaultModel: 'deepseek-ai/DeepSeek-V4-Pro', + models: [ + 'deepseek-ai/DeepSeek-V4-Pro', + 'openai/gpt-oss-120b', + 'zai-org/GLM-5.2', + 'zai-org/GLM-5', + ], + + async generate(ctx, prompt, opts, config) { + const apiKey = ctx.secret('BASETEN_API_KEY'); + if (!apiKey) throw new Error('BASETEN_API_KEY not in vault'); + const model = opts.model ?? 'deepseek-ai/DeepSeek-V4-Pro'; + ctx.log(`baseten · model=${model} · ${prompt.length} chars in`); + if (ctx.dryRun) return { text: '[dry-run]', model }; + + const messages: Array<{ role: string; content: string }> = []; + if (opts.system) messages.push({ role: 'system', content: opts.system }); + messages.push({ role: 'user', content: prompt }); + + const res = await fetch(chatCompletionsUrl(config.baseUrl), { + method: 'POST', + headers: { + authorization: `Bearer ${apiKey}`, + 'content-type': 'application/json', + }, + body: JSON.stringify({ + model, + messages, + ...(opts.maxTokens !== undefined ? { max_tokens: opts.maxTokens } : {}), + ...(opts.temperature !== undefined ? { temperature: opts.temperature } : {}), + ...opts.extra, + }), + }); + if (!res.ok) throw new Error(`Baseten ${res.status}: ${redact(await res.text(), apiKey).slice(0, 200)}`); + const data = (await res.json()) as { + choices: Array<{ message?: { content?: string } }>; + model: string; + usage?: { prompt_tokens?: number; completion_tokens?: number }; + }; + return { + text: data.choices[0]?.message?.content ?? '', + model: data.model, + inputTokens: data.usage?.prompt_tokens, + outputTokens: data.usage?.completion_tokens, + }; }, setup: tokenSetup({ - secretKey: 'https://www.baseten.co', + secretKey: 'BASETEN_API_KEY', label: 'Baseten', - vendorDocUrl: '', + vendorDocUrl: 'https://app.baseten.co', steps: [ - 'Sign in at and create an API key', + 'Sign in at https://app.baseten.co and create an API key', 'Copy the key — usually shown once', 'Paste below; sh1pt encrypts it in the vault', ],