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
110 changes: 110 additions & 0 deletions packages/ai/ionet/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,114 @@
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> = { IOINTELLIGENCE_API_KEY: 'test-key' },
dryRun = false,
) => ({
secret: (key: string) => secrets[key],
log: () => {},
dryRun,
});

describe('io.net IO Intelligence 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({ IOINTELLIGENCE_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: 'meta-llama/Llama-3.3-70B-Instruct',
choices: [{ message: { role: 'assistant', content: 'hi from io intelligence' } }],
usage: { prompt_tokens: 10, completion_tokens: 4, total_tokens: 14 },
}),
});
vi.stubGlobal('fetch', fetchMock);

const result = await adapter.generate(
ctx(),
'hello',
{
system: 'be direct',
maxTokens: 50,
temperature: 0.7,
extra: { top_p: 0.9, request_id: 'req-test' },
},
{},
);

expect(fetchMock).toHaveBeenCalledOnce();
const call = fetchMock.mock.calls[0];
expect(call).toBeDefined();
const [url, request] = call!;
expect(url).toBe('https://api.intelligence.io.solutions/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: 'meta-llama/Llama-3.3-70B-Instruct',
messages: [
{ role: 'system', content: 'be direct' },
{ role: 'user', content: 'hello' },
],
stream: false,
max_tokens: 50,
temperature: 0.7,
top_p: 0.9,
request_id: 'req-test',
});
expect(result).toEqual({
text: 'hi from io intelligence',
model: 'meta-llama/Llama-3.3-70B-Instruct',
inputTokens: 10,
outputTokens: 4,
});
});

it('supports text-style choices from compatible responses', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
model: 'Qwen/Qwen2-VL-7B-Instruct',
choices: [{ text: 'legacy text response' }],
}),
}));

const result = await adapter.generate(ctx(), 'hello', {}, { baseUrl: 'https://ionet.test/api/v1' });

expect(result).toEqual({
text: 'legacy text response',
model: 'Qwen/Qwen2-VL-7B-Instruct',
});
});

it('includes status and response body excerpt on errors', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: false,
status: 429,
text: async () => 'rate limit exceeded'.repeat(30),
}));

await expect(adapter.generate(ctx(), 'hello', {}, {})).rejects.toThrow(
/io.net 429: rate limit exceeded/,
);
});
});
86 changes: 73 additions & 13 deletions packages/ai/ionet/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,87 @@ interface Config {
baseUrl?: string;
}

const DEFAULT_BASE = 'https://api.intelligence.io.solutions/api/v1';
const DEFAULT_MODEL = 'meta-llama/Llama-3.3-70B-Instruct';

export default defineAi<Config>({
id: 'ai-ionet',
label: 'io.net',
defaultModel: 'IONET_API_KEY',
models: ['IONET_API_KEY'],

async generate(ctx, prompt, _opts, _config) {
const apiKey = ctx.secret('https://io.net');
if (!apiKey) throw new Error('https://io.net not in vault — run `sh1pt promote ai setup`');
ctx.log(`[stub] ai-ionet · ${prompt.length} chars in — integration pending`);
return { text: '[stub — ai-ionet integration not yet implemented]', model: 'IONET_API_KEY' };
defaultModel: DEFAULT_MODEL,
models: [
DEFAULT_MODEL,
'meta-llama/Llama-3.2-90B-Vision-Instruct',
'Qwen/Qwen2-VL-7B-Instruct',
],

async generate(ctx, prompt, opts, config) {
const apiKey = ctx.secret('IOINTELLIGENCE_API_KEY');
if (!apiKey) throw new Error('IOINTELLIGENCE_API_KEY not in vault');
const model = opts.model ?? DEFAULT_MODEL;
ctx.log(`ionet · model=${model} · ${prompt.length} chars in`);
if (ctx.dryRun) return { text: '[dry-run]', model };

const messages: IoNetMessage[] = [];
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(`io.net ${res.status}: ${(await res.text()).slice(0, 200)}`);

const data = await res.json() as IoNetChatResponse;
const choice = data.choices[0];
return {
text: choice?.message?.content ?? choice?.text ?? '',
model: data.model,
inputTokens: data.usage?.prompt_tokens,
outputTokens: data.usage?.completion_tokens,
};
},

setup: tokenSetup<Config>({
secretKey: 'https://io.net',
label: 'io.net',
vendorDocUrl: '',
secretKey: 'IOINTELLIGENCE_API_KEY',
label: 'io.net IO Intelligence',
vendorDocUrl: 'https://io.net/docs/reference/ai-models/get-started-with-io-intelligence-api',
steps: [
'Sign in at and create an API key',
'Copy the key — usually shown once',
'Sign in at https://io.net and open IO Intelligence API keys',
'Create a secret key for the IO Intelligence project',
'Copy the key; it is usually shown once',
'Paste below; sh1pt encrypts it in the vault',
],
}),
});

type IoNetRole = 'system' | 'user' | 'assistant' | 'tool';

interface IoNetMessage {
role: IoNetRole;
content: string;
}

interface IoNetChatResponse {
model: string;
choices: Array<{
message?: {
content?: string;
};
text?: string;
}>;
usage?: {
prompt_tokens?: number;
completion_tokens?: number;
};
}
Loading