Skip to content
Open
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
118 changes: 118 additions & 0 deletions packages/ai/clarifai/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,122 @@
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> = { CLARIFAI_PAT: 'test-pat' },
dryRun = false,
) => ({
secret: (key: string) => secrets[key],
log: () => {},
dryRun,
});

describe('Clarifai 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({ CLARIFAI_PAT: 'test-pat' }, true),
'hello',
{},
{},
);

expect(result).toEqual({
text: '[dry-run]',
model: 'https://clarifai.com/openai/chat-completion/models/gpt-oss-120b',
});
expect(fetchMock).not.toHaveBeenCalled();
});

it('posts OpenAI-compatible chat completions requests and maps usage tokens', async () => {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
model: 'openai/chat-completion/models/gpt-oss-120b',
choices: [{ message: { role: 'assistant', content: 'hi from clarifai' } }],
usage: { prompt_tokens: 9, completion_tokens: 5, total_tokens: 14 },
}),
});
vi.stubGlobal('fetch', fetchMock);

const result = await adapter.generate(
ctx(),
'hello',
{
model: 'openai/chat-completion/models/gpt-oss-120b',
system: 'be concise',
maxTokens: 64,
temperature: 0.2,
extra: { top_p: 0.9, seed: 7 },
},
{},
);

expect(fetchMock).toHaveBeenCalledOnce();
const call = fetchMock.mock.calls[0];
expect(call).toBeDefined();
const [url, request] = call!;
expect(url).toBe('https://api.clarifai.com/v2/ext/openai/v1/chat/completions');
expect(request.headers.authorization).toBe('Key test-pat');
expect(request.headers['content-type']).toBe('application/json');
expect(JSON.parse(request.body)).toEqual({
model: 'openai/chat-completion/models/gpt-oss-120b',
messages: [
{ role: 'system', content: 'be concise' },
{ role: 'user', content: 'hello' },
],
stream: false,
max_completion_tokens: 64,
temperature: 0.2,
top_p: 0.9,
seed: 7,
});
expect(result).toEqual({
text: 'hi from clarifai',
model: 'openai/chat-completion/models/gpt-oss-120b',
inputTokens: 9,
outputTokens: 5,
});
});

it('supports compatible text-style choices and custom base URLs', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
choices: [{ text: 'legacy text response' }],
}),
}));

const result = await adapter.generate(
ctx(),
'hello',
{ model: 'anthropic/completion/models/claude-sonnet-4' },
{ baseUrl: 'https://clarifai.test/v2/ext/openai/v1' },
);

expect(result).toEqual({
text: 'legacy text response',
model: 'anthropic/completion/models/claude-sonnet-4',
});
});

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

await expect(adapter.generate(ctx(), 'hello', {}, {})).rejects.toThrow(
/Clarifai 401: invalid pat/,
);
});
});
82 changes: 71 additions & 11 deletions packages/ai/clarifai/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.clarifai.com/v2/ext/openai/v1';
const DEFAULT_MODEL = 'https://clarifai.com/openai/chat-completion/models/gpt-oss-120b';

export default defineAi<Config>({
id: 'ai-clarifai',
label: 'Clarifai',
defaultModel: 'CLARIFAI_PAT',
models: ['CLARIFAI_PAT'],

async generate(ctx, prompt, _opts, _config) {
const apiKey = ctx.secret('https://clarifai.com');
if (!apiKey) throw new Error('https://clarifai.com not in vault — run `sh1pt promote ai setup`');
ctx.log(`[stub] ai-clarifai · ${prompt.length} chars in — integration pending`);
return { text: '[stub — ai-clarifai integration not yet implemented]', model: 'CLARIFAI_PAT' };
defaultModel: DEFAULT_MODEL,
models: [
DEFAULT_MODEL,
'openai/chat-completion/models/gpt-oss-120b',
'anthropic/completion/models/claude-sonnet-4',
'https://clarifai.com/openai/chat-completion/models/gpt-4o',
],

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

const messages: ClarifaiMessage[] = [];
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: `Key ${apiKey}`,
'content-type': 'application/json',
},
body: JSON.stringify({
model,
messages,
stream: false,
...(opts.maxTokens !== undefined ? { max_completion_tokens: opts.maxTokens } : {}),
...(opts.temperature !== undefined ? { temperature: opts.temperature } : {}),
...opts.extra,
}),
});
if (!res.ok) throw new Error(`Clarifai ${res.status}: ${(await res.text()).slice(0, 200)}`);

const data = await res.json() as ClarifaiChatResponse;
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<Config>({
secretKey: 'https://clarifai.com',
secretKey: 'CLARIFAI_PAT',
label: 'Clarifai',
vendorDocUrl: '',
vendorDocUrl: 'https://docs.clarifai.com/compute/inference/open-ai/',
steps: [
'Sign in at and create an API key',
'Sign in to Clarifai and create a Personal Access Token (PAT)',
'Copy the key — usually shown once',
'Paste below; sh1pt encrypts it in the vault',
],
}),
});

type ClarifaiRole = 'system' | 'user' | 'assistant' | 'developer' | 'tool';

interface ClarifaiMessage {
role: ClarifaiRole;
content: string;
}

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