diff --git a/packages/ai/akashml/src/index.test.ts b/packages/ai/akashml/src/index.test.ts index f43ad207..7627bb89 100644 --- a/packages/ai/akashml/src/index.test.ts +++ b/packages/ai/akashml/src/index.test.ts @@ -1,4 +1,119 @@ 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 = { AKASH_API_KEY: 'test-key' }, + dryRun = false, +) => ({ + secret: (key: string) => secrets[key], + log: () => {}, + dryRun, +}); + +describe('Akash ML 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({ AKASH_API_KEY: 'test-key' }, true), + 'hello', + {}, + {}, + ); + + expect(result).toEqual({ text: '[dry-run]', model: 'meta-llama/Llama-3.3-70B-Instruct' }); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('posts chat completions requests and maps usage tokens', async () => { + const fetchMock = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + model: 'deepseek-ai/DeepSeek-V4-Flash', + choices: [{ message: { role: 'assistant', content: 'hi from akash' } }], + usage: { prompt_tokens: 12, completion_tokens: 4, total_tokens: 16 }, + }), + }); + vi.stubGlobal('fetch', fetchMock); + + const result = await adapter.generate( + ctx(), + 'hello', + { + model: 'deepseek-ai/DeepSeek-V4-Flash', + system: 'be concise', + maxTokens: 48, + temperature: 0.3, + extra: { top_p: 0.8, seed: 42 }, + }, + {}, + ); + + expect(fetchMock).toHaveBeenCalledOnce(); + const call = fetchMock.mock.calls[0]; + expect(call).toBeDefined(); + const [url, request] = call!; + expect(url).toBe('https://chatapi.akash.network/api/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: 'deepseek-ai/DeepSeek-V4-Flash', + messages: [ + { role: 'system', content: 'be concise' }, + { role: 'user', content: 'hello' }, + ], + stream: false, + max_tokens: 48, + temperature: 0.3, + top_p: 0.8, + seed: 42, + }); + expect(result).toEqual({ + text: 'hi from akash', + model: 'deepseek-ai/DeepSeek-V4-Flash', + inputTokens: 12, + outputTokens: 4, + }); + }); + + it('supports text-style choices from compatible responses', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + choices: [{ text: 'legacy text response' }], + }), + })); + + const result = await adapter.generate( + ctx(), + 'hello', + { model: 'Qwen/Qwen3.6-35B-A3B' }, + { baseUrl: 'https://akash.test/api/v1' }, + ); + + expect(result).toEqual({ + text: 'legacy text response', + model: 'Qwen/Qwen3.6-35B-A3B', + }); + }); + + it('includes status and response body excerpt on errors', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ + ok: false, + status: 429, + text: async () => 'rate limited'.repeat(30), + })); + + await expect(adapter.generate(ctx(), 'hello', {}, {})).rejects.toThrow( + /Akash ML 429: rate limited/, + ); + }); +}); diff --git a/packages/ai/akashml/src/index.ts b/packages/ai/akashml/src/index.ts index 50567e2b..eada32ff 100644 --- a/packages/ai/akashml/src/index.ts +++ b/packages/ai/akashml/src/index.ts @@ -4,27 +4,88 @@ interface Config { baseUrl?: string; } +const DEFAULT_BASE = 'https://chatapi.akash.network/api/v1'; +const DEFAULT_MODEL = 'meta-llama/Llama-3.3-70B-Instruct'; + export default defineAi({ id: 'ai-akashml', label: 'Akash ML', - defaultModel: 'AKASH_API_KEY', - models: ['AKASH_API_KEY'], - - async generate(ctx, prompt, _opts, _config) { - const apiKey = ctx.secret('https://chatapi.akash.network'); - if (!apiKey) throw new Error('https://chatapi.akash.network not in vault — run `sh1pt promote ai setup`'); - ctx.log(`[stub] ai-akashml · ${prompt.length} chars in — integration pending`); - return { text: '[stub — ai-akashml integration not yet implemented]', model: 'AKASH_API_KEY' }; + defaultModel: DEFAULT_MODEL, + models: [ + DEFAULT_MODEL, + 'deepseek-ai/DeepSeek-V4-Flash', + 'Qwen/Qwen3.6-35B-A3B', + 'moonshotai/Kimi-K2.6', + 'MiniMaxAI/MiniMax-M2.5', + ], + + async generate(ctx, prompt, opts, config) { + const apiKey = ctx.secret('AKASH_API_KEY'); + if (!apiKey) throw new Error('AKASH_API_KEY not in vault'); + const model = opts.model ?? DEFAULT_MODEL; + ctx.log(`akashml - model=${model} - ${prompt.length} chars in`); + if (ctx.dryRun) return { text: '[dry-run]', model }; + + const messages: AkashMessage[] = []; + 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`, { + method: 'POST', + headers: { + authorization: `Bearer ${apiKey}`, + 'content-type': 'application/json', + }, + body: JSON.stringify({ + model, + messages, + stream: false, + ...(opts.maxTokens !== undefined ? { max_tokens: opts.maxTokens } : {}), + ...(opts.temperature !== undefined ? { temperature: opts.temperature } : {}), + ...opts.extra, + }), + }); + if (!res.ok) throw new Error(`Akash ML ${res.status}: ${(await res.text()).slice(0, 200)}`); + + const data = await res.json() as AkashChatResponse; + const choice = data.choices[0]; + return { + text: choice?.message?.content ?? choice?.text ?? '', + model: data.model ?? model, + inputTokens: data.usage?.prompt_tokens, + outputTokens: data.usage?.completion_tokens, + }; }, setup: tokenSetup({ - secretKey: 'https://chatapi.akash.network', + secretKey: 'AKASH_API_KEY', label: 'Akash ML', - vendorDocUrl: '', + vendorDocUrl: 'https://chatapi.akash.network/documentation', steps: [ - 'Sign in at and create an API key', + 'Sign in at https://chatapi.akash.network or https://akashml.com and create an API key', 'Copy the key — usually shown once', 'Paste below; sh1pt encrypts it in the vault', ], }), }); + +type AkashRole = 'system' | 'user' | 'assistant' | 'tool'; + +interface AkashMessage { + role: AkashRole; + content: string; +} + +interface AkashChatResponse { + model?: string; + choices: Array<{ + message?: { + content?: string; + }; + text?: string; + }>; + usage?: { + prompt_tokens?: number; + completion_tokens?: number; + }; +}