7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
feat(providers): add APINex free chat and decision adapter (#1578)
Tashfeen9b3045673a59
diff --git a/client/src/components/keys/shared.tsx b/client/src/components/keys/shared.tsxindex 20730ee2..1ae09376 100644--- a/client/src/components/keys/shared.tsx+++ b/client/src/components/keys/shared.tsx@@ -34,6 +34,7 @@ export const PLATFORMS: { value: Platform; label: string; url: string; keyless?:{ value: 'speka', label: 'Speka ($1 shared monthly credits)', url: 'https://speka.me/dashboard/keys' },{ value: 'auray', label: 'Auray', url: 'https://app.auray.ai', hidden: true },{ value: 'beatapi', label: 'BeatAPI (JEV decisions; temporary free offer)', url: 'https://beatapi.io' },+ { value: 'apinex', label: 'APINex (shared daily free chat and decisions)', url: 'https://apinex.bond/keys' },{ value: 'typhoon', label: 'Typhoon (free research API)', url: 'https://playground.opentyphoon.ai' },{ value: 'plugsky', label: 'Plugsky (free chat aliases)', url: 'https://plugsky.com/dashboard' },{ value: 'inferbase', label: 'Inferbase (shared monthly and daily allowance)', url: 'https://inferbase.ai' },diff --git a/client/src/lib/routing.ts b/client/src/lib/routing.tsindex 36b85ae9..edd36fea 100644--- a/client/src/lib/routing.ts+++ b/client/src/lib/routing.ts@@ -467,6 +467,7 @@ export const platformColors: Record<string, string> = {parallel: '#0ea5e9',serpsearch: '#2563eb',beatapi: '#8b5cf6',+ apinex: '#06b6d4',}// ── Grouped (unified) rendering ──────────────────────────────────────────────diff --git a/docs/APINEX.md b/docs/APINEX.mdnew file mode 100644index 00000000..5e2fef60--- /dev/null+++ b/docs/APINEX.md@@ -0,0 +1,43 @@+# APINex++APINex uses `https://api.apinex.bond/v1`, with Bearer API-key authentication.+Add a key in the dashboard or import `APINEX_API_KEY` from an environment file.++- Chat and SSE: `POST /chat/completions`, preserving the exact `free/` model ID.+- Decisions: `POST /decisions`, with `{model, state, questions}` and typed+ `choice`, `noul`, or `score` answers. JEV belongs in `decisionModels`, not chat.+- Key validation: read-only `GET /balance`. A $0 wallet is valid on Free;+ validation does not spend generation quota. Authentication failures are+ invalid; throttles, outages, and malformed responses remain inconclusive.+- Responses must identify the requested model. A substituted paid alias or+ malformed response is an error, never a silent success or paid retry.++## Free eligibility, verified 2026-10-18++Authenticated `GET /subscription` returned `mode: "free"`, `plan: null`, a+10,000,000-unit daily token allowance and the next midnight-UTC reset.+The public rate-limit endpoint reported 5 requests/minute on Free. The+allowance is shared across chat and decisions: current model multipliers+charge 2–4 units per input/output token. It is **not** 10M raw tokens per model,+a monthly cash credit, or a one-time signup balance.++Ten chat routes and one JEV decision route returned valid responses with a+$0 wallet, no subscription, and $0 billed. These tests verify working routes,+not independent attestation of the upstream model weights. Ten other routes+had `free/` names but `allowFree: false`: those are subscription-only and were+excluded. Eligibility must be checked using the provider's current public+model metadata, not the ID prefix alone.++Model rows are published only through the signed Oracle catalog. No seeds,+model-discovery enrollment, or database migration bypasses the existing+Premium-now / Free-after-30-days release gate. Existing installations need+application code containing this adapter before they can use these rows.++Sources:++- <https://apinex.bond/developers/models/chat>+- <https://apinex.bond/developers/models/decisions>+- <https://apinex.bond/developers/balance>+- <https://apinex.bond/api/public/subscriptions>+- <https://apinex.bond/api/public/rate-limits>+- <https://apinex.bond/api/public/models>diff --git a/server/src/__tests__/providers/catalog-gateways.test.ts b/server/src/__tests__/providers/catalog-gateways.test.tsindex 55c6b17f..c6b0372f 100644--- a/server/src/__tests__/providers/catalog-gateways.test.ts+++ b/server/src/__tests__/providers/catalog-gateways.test.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { InferbaseProvider, INFERBASE_BASE_URL } from '../../providers/inferbase.js';+import { ApinexProvider, APINEX_BASE_URL } from '../../providers/apinex.js';import { SimpleLLMProvider, SIMPLELLM_BASE_URL } from '../../providers/simplellm.js';import { getProvider } from '../../providers/index.js';import { AUTH_JSON_PROVIDER_MAP, parseKeysFromFile } from '../../lib/key-parser.js';@@ -10,6 +11,7 @@ import { getDb, initDb } from '../../db/index.js';const json = (body: unknown, status = 200, headers = {}) => new Response(JSON.stringify(body), { status, headers });const configs = [+ { platform: 'apinex' as const, provider: ApinexProvider, base: APINEX_BASE_URL, validate: `${APINEX_BASE_URL}/balance`, account: { object: 'balance', balance_usd: 0 }, model: 'free/glm-5.3-flashx', returned: 'free/glm-5.3-flashx' },{ platform: 'inferbase' as const, provider: InferbaseProvider, base: INFERBASE_BASE_URL, validate: 'https://api.inferbase.ai/api/v1/inference/credits', account: { balance_micros: 0 }, model: 'deepseek-v4-flash', returned: 'deepseek-v4-flash' },{ platform: 'simplellm' as const, provider: SimpleLLMProvider, base: SIMPLELLM_BASE_URL, validate: `${SIMPLELLM_BASE_URL}/rate-limit`, account: { limit_rpm: 1000 }, model: 'free-gemma-4-E4B', returned: 'gemma-4-E4B' },];diff --git a/server/src/__tests__/services/apinex.test.ts b/server/src/__tests__/services/apinex.test.tsnew file mode 100644index 00000000..bda4d9ca--- /dev/null+++ b/server/src/__tests__/services/apinex.test.ts@@ -0,0 +1,91 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { initDb, getDb } from '../../db/index.js';+import { encrypt } from '../../lib/crypto.js';+import { runDecision, DECISION_PLATFORMS } from '../../services/decision.js';+import { clearAllCooldowns } from '../../services/ratelimit.js';+import { applyCatalog, catalogShapeProblems } from '../../services/catalog-sync.js';+import { ApinexProvider } from '../../providers/apinex.js';++const model = 'free/jev-1.13';+const json = (body: unknown, status = 200, headers = {}) => new Response(JSON.stringify(body), { status, headers });+const request = { state: 'Invoice charged twice', questions: {+ billing: { type: 'noul' as const, instructions: 'Billing issue?' },+ route: { type: 'choice' as const, instructions: 'Choose a queue', criteria: { billing: 'Invoice questions', technical: 'Software issues' } },+ urgency: { type: 'score' as const, instructions: 'Rate urgency', criteria: { low: 'Routine question', high: 'Urgent' } },+} };+const answers = { billing: { type: 'noul', noul: 0.99 }, route: { type: 'choice', choice: 'billing', confidence: 1 }, urgency: { type: 'score', score: 0.5 } };+beforeEach(() => { process.env.ENCRYPTION_KEY = '0'.repeat(64); initDb(':memory:'); clearAllCooldowns(Number.MAX_SAFE_INTEGER); });+afterEach(() => { vi.restoreAllMocks(); getDb().close(); });+function seed() {+ const key = encrypt('unit-test-key');+ getDb().prepare("INSERT INTO api_keys (platform,label,encrypted_key,iv,auth_tag,status,enabled) VALUES ('apinex','test',?,?,?,'healthy',1)").run(key.encrypted, key.iv, key.authTag);+ getDb().prepare("INSERT INTO media_models (platform,model_id,display_name,modality,priority,enabled,quota_label) VALUES ('apinex',?,?,'decision',0,1,'Shared daily quota')").run(model, model);+}++describe('APINex decisions', () => {+ it('dispatches typed questions to /decisions with the exact free route', async () => {+ seed();+ const fetch = vi.spyOn(global, 'fetch').mockResolvedValue(json({ model, answers, usage: { input_tokens: 335, output_tokens: 47 } }));+ expect(DECISION_PLATFORMS.has('apinex')).toBe(true);+ expect(await runDecision(request, { model })).toEqual({ provider: 'apinex', model, answers, usage: { input_tokens: 335, output_tokens: 47 } });+ expect(fetch.mock.calls[0][0]).toBe('https://api.apinex.bond/v1/decisions');+ expect(JSON.parse(String(fetch.mock.calls[0][1]?.body))).toEqual({ model, ...request });+ expect(new Headers(fetch.mock.calls[0][1]?.headers).get('authorization')).toBe('Bearer unit-test-key');+ expect(fetch.mock.calls[0][1]?.redirect).toBe('error');+ expect(fetch).toHaveBeenCalledTimes(1);+ });++ it.each([+ null, { model: 'jev-1.13', answers }, { answers }, { model, answers: {} },+ { model, answers: { ...answers, billing: { type: 'noul', noul: 'yes' } } },+ { model, answers: { ...answers, route: { type: 'choice', choice: 1 } } },+ { model, answers: { ...answers, urgency: { type: 'score', score: null } } },+ { model, answers, error: { message: 'Upstream failed' } },+ ])('fails closed on malformed, missing, or substituted answers', async body => {+ seed(); vi.spyOn(global, 'fetch').mockResolvedValue(json(body));+ await expect(runDecision(request, { model })).rejects.toMatchObject({ status: 502 });+ });++ it.each([401, 402, 429, 503])('uses existing failure policy for HTTP %s, with no paid-alias retry', async status => {+ seed();+ const fetch = vi.spyOn(global, 'fetch').mockResolvedValue(json({ error: { retry_after_seconds: 45 } }, status));+ const error = await runDecision(request, { model }).catch(error => error);+ expect(error).toMatchObject({ status: status === 429 ? 429 : 502, retryAfterMs: status === 429 ? 45_000 : undefined });+ expect(error.message).toContain(`apinex ${status}`);+ expect(fetch).toHaveBeenCalledTimes(1);+ });++ it('keeps chat and decision rows distinct, catalog-only, and idempotent', () => {+ const db = getDb(), premiumSince = '2026-10-18T12:00:00.000Z';+ expect(db.prepare("SELECT COUNT(*) n FROM models WHERE platform='apinex'").get()).toEqual({ n: 0 });+ expect(db.prepare("SELECT COUNT(*) n FROM media_models WHERE platform='apinex'").get()).toEqual({ n: 0 });+ const catalog = { version: '2099.01.01', generatedAt: premiumSince, tier: 'live' as const, quirks: [],+ models: [{ platform: 'apinex', modelId: 'free/glm-5.3', displayName: 'GLM 5.3', intelligenceRank: 50, speedRank: 50, sizeLabel: '', limits: { rpm: 5, rpd: null, tpm: null, tpd: null }, monthlyTokenBudget: 'Shared daily weighted allowance', contextWindow: 1000000, enabled: true, supportsTools: true, supportsVision: false, premiumSince }],+ decisionModels: [{ platform: 'apinex', modelId: model, displayName: 'JEV 1.13', priority: 10, enabled: true, quotaLabel: 'Shared daily weighted allowance', contextWindow: 65536, premiumSince }],+ };+ expect(catalogShapeProblems(catalog)).toEqual([]);+ expect(applyCatalog(db, catalog).skippedUnknownPlatform).toBe(0);+ expect(applyCatalog(db, catalog).inserted).toBe(0);+ expect(db.prepare("SELECT model_id FROM models WHERE platform='apinex'").all()).toEqual([{ model_id: 'free/glm-5.3' }]);+ const row = db.prepare("SELECT model_id,modality,meta_json FROM media_models WHERE platform='apinex'").get() as { model_id: string; modality: string; meta_json: string };+ expect(row.model_id).toBe(model); expect(row.modality).toBe('decision');+ expect(JSON.parse(row.meta_json).premiumSince).toBe(premiumSince);+ });+});++describe('APINex response guards', () => {+ it.each([{ balance_usd: 0 }, { object: 'balance', balance_usd: '0' }, { object: 'balance', balance_usd: 0, error: 'failed' }])('rejects malformed account metadata', async body => {+ vi.spyOn(global, 'fetch').mockResolvedValue(json(body));+ await expect(new ApinexProvider().validateKey('test')).rejects.toMatchObject({ status: 502 });+ });+ it.each([{ error: { message: 'Upstream failed' } }, { model: 'free/glm-5.3' }])('rejects malformed SSE after a valid first event', async event => {+ const first = { id: 's', object: 'chat.completion.chunk', model: 'free/glm-5.3', choices: [{ index: 0, delta: { role: 'assistant' }, finish_reason: null }] };+ vi.spyOn(global, 'fetch').mockResolvedValue(new Response([first, event].map(c => `data: ${JSON.stringify(c)}\n\n`).join('') + 'data: [DONE]\n\n'));+ const collect = async () => { for await (const _ of new ApinexProvider().streamChatCompletion('test', [], 'free/glm-5.3')) { /* drain */ } };+ await expect(collect()).rejects.toMatchObject({ status: 502 });+ });+ it('rejects a stream with no identified completion', async () => {+ vi.spyOn(global, 'fetch').mockResolvedValue(new Response('data: [DONE]\n\n'));+ await expect(new ApinexProvider().streamChatCompletion('test', [], 'free/glm-5.3').next()).rejects.toMatchObject({ status: 502 });+ });+});diff --git a/server/src/__tests__/services/decision.test.ts b/server/src/__tests__/services/decision.test.tsindex bed9f871..a60ed4b4 100644--- a/server/src/__tests__/services/decision.test.ts+++ b/server/src/__tests__/services/decision.test.ts@@ -64,7 +64,7 @@ describe('decision service', () => {});it('has adapters for the supported decision platforms', () => {- expect([...DECISION_PLATFORMS].sort()).toEqual(['beatapi', 'cloudflare', 'openrouter']);+ expect([...DECISION_PLATFORMS].sort()).toEqual(['apinex', 'beatapi', 'cloudflare', 'openrouter']);});it('calls Cloudflare ai/run with the account from the key and the short model selector', async () => {diff --git a/server/src/lib/key-parser.ts b/server/src/lib/key-parser.tsindex b514a2ee..642a51e9 100644--- a/server/src/lib/key-parser.ts+++ b/server/src/lib/key-parser.ts@@ -48,6 +48,7 @@ export const PREFIX_MAP: Record<string, string> = {SPEKA_: 'speka',AURAY_: 'auray',BEATAPI_: 'beatapi',+ APINEX_: 'apinex',BEAT_API_: 'beatapi',SERPSEARCH_: 'serpsearch',SERP_SEARCH_: 'serpsearch',@@ -163,6 +164,7 @@ export const AUTH_JSON_PROVIDER_MAP: Record<string, string> = {speka: 'speka',auray: 'auray',beatapi: 'beatapi',+ apinex: 'apinex',serpsearch: 'serpsearch',typhoon: 'typhoon',plugsky: 'plugsky',diff --git a/server/src/providers/apinex.ts b/server/src/providers/apinex.tsnew file mode 100644index 00000000..c22e309c--- /dev/null+++ b/server/src/providers/apinex.ts@@ -0,0 +1,58 @@+import type { ChatCompletionChunk, ChatCompletionResponse, ChatMessage } from '@freellmapi/shared/types.js';+import { providerHttpError, type CompletionOptions, type KeyValidationResult } from './base.js';+import { OpenAICompatProvider } from './openai-compat.js';+import type { QuotaObservationContext } from '../services/provider-quota.js';++export const APINEX_BASE_URL = 'https://api.apinex.bond/v1';++function checkModel(requested: string, returned: string): void {+ if (requested !== returned) {+ throw Object.assign(new Error('APINex returned a different or missing model identity'), { status: 502 });+ }+}++/** Free-category chat shares a weighted daily allowance with decisions.+ * Preserve free/ exactly; never retry a paid alias. Eligibility and model+ * rows belong exclusively in the signed, tier-selected catalog. */+export class ApinexProvider extends OpenAICompatProvider {+ constructor() {+ super({ platform: 'apinex', name: 'APINex', baseUrl: APINEX_BASE_URL, validateUrl: `${APINEX_BASE_URL}/balance` });+ }++ protected override async validationResult(response: Response): Promise<KeyValidationResult> {+ if ([401, 403].includes(response.status)) return super.validationResult(response);+ if (!response.ok) throw providerHttpError(response, 'APINex key validation is temporarily inconclusive');+ const body = await response.json().catch(() => null) as { object?: unknown; balance_usd?: unknown; error?: unknown } | null;+ if (body?.object !== 'balance' || body.error || typeof body.balance_usd !== 'number' || !Number.isFinite(body.balance_usd)) {+ throw Object.assign(new Error('APINex returned an invalid balance response'), { status: 502 });+ }+ // A zero-dollar wallet is valid: free-category calls use the daily pool.+ return true;+ }++ override async chatCompletion(apiKey: string, messages: ChatMessage[], modelId: string,+ options?: CompletionOptions, quotaContext?: QuotaObservationContext): Promise<ChatCompletionResponse> {+ const response = await super.chatCompletion(apiKey, messages, modelId, options, quotaContext);+ checkModel(modelId, response.model);+ return response;+ }++ override async *streamChatCompletion(apiKey: string, messages: ChatMessage[], modelId: string,+ options?: CompletionOptions, quotaContext?: QuotaObservationContext): AsyncGenerator<ChatCompletionChunk> {+ let identified = false;+ for await (const chunk of super.streamChatCompletion(apiKey, messages, modelId, options, quotaContext)) {+ if ('error' in chunk || !Array.isArray(chunk.choices)) {+ throw Object.assign(new Error('APINex returned an upstream stream error or malformed event'), { status: 502 });+ }+ // Usage-only terminal frames may omit model, but every content-bearing+ // frame must carry the exact route. Do not accept an empty stream.+ if (chunk.model || chunk.choices.length) {+ checkModel(modelId, chunk.model);+ identified = true;+ }+ if (!identified) checkModel(modelId, chunk.model);+ yield chunk;+ }+ if (!identified) checkModel(modelId, '');+ }+}diff --git a/server/src/providers/index.ts b/server/src/providers/index.tsindex 5a74884b..8bf9356d 100644--- a/server/src/providers/index.ts+++ b/server/src/providers/index.ts@@ -39,6 +39,7 @@ import { WaterfallProvider } from './waterfall.js';import { LogfareProvider } from './logfare.js';import { AurayProvider } from './auray.js';import { BeatApiProvider } from './beatapi.js';+import { ApinexProvider } from './apinex.js';import { SerpSearchProvider } from './serpsearch.js';const providers = new Map<Platform, BaseProvider>();@@ -85,6 +86,7 @@ register(new BlockRunProvider());register(new MoondreamProvider());register(new AurayProvider());register(new BeatApiProvider());+register(new ApinexProvider());register(new SerpSearchProvider());// Free-plan grants are shared wallets, not free credits per model. Eligibilitydiff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex 64c6772c..7f921593 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -63,6 +63,7 @@ const PLATFORMS = ['blockrun','moondream','beatapi',+ 'apinex','serpsearch','freeai','google', 'groq', 'cerebras', 'sail', 'electronhub', 'experiential', 'router9', 'septor', 'clod', 'speechify', 'blaze', 'lucidity', 'airforce', 'dreamprompting', 'waterfall', 'logfare', 'bai', 'radeon', 'nvidia', 'mistral',diff --git a/server/src/services/decision.ts b/server/src/services/decision.tsindex 58fc4ac4..52792dd2 100644--- a/server/src/services/decision.ts+++ b/server/src/services/decision.ts@@ -1,5 +1,6 @@import { getDb } from '../db/index.js';import { BEATAPI_BASE_URL } from '../providers/beatapi.js';+import { APINEX_BASE_URL } from '../providers/apinex.js';import { parseRetryAfterMs, parseStatedRetryMs } from '../providers/base.js';import { RetryHintTracker } from '../lib/retry-hint.js';import { getClientContext } from '../lib/client-context.js';@@ -178,6 +179,27 @@ function cloudflareKey(key: string): { accountId: string; token: string } {}const ADAPTERS: Record<string, Adapter> = {+ apinex: async (cred, modelId, body, signal) => {+ const json = await upstream(`${APINEX_BASE_URL}/decisions`, 'apinex', {+ method: 'POST', redirect: 'error',+ headers: { Authorization: `Bearer ${cred.key}`, 'Content-Type': 'application/json' },+ body: JSON.stringify({ model: modelId, state: body.state, questions: body.questions }),+ }, signal) as { model?: string; answers?: unknown; usage?: unknown; error?: unknown } | null;+ if (!json || json.error || json.model !== modelId) {+ throw new DecisionError('apinex returned an error or a different decision model', 502);+ }+ const answers = answersOf(json.answers, 'apinex');+ for (const [id, question] of Object.entries(body.questions)) {+ const answer = answers[id] as { type?: unknown; choice?: unknown; noul?: unknown; score?: unknown } | null;+ const value = answer?.[question.type];+ if (!answer || answer.type !== question.type || (question.type === 'choice'+ ? typeof value !== 'string'+ : typeof value !== 'number' || !Number.isFinite(value))) {+ throw new DecisionError('apinex returned a missing or invalid typed answer', 502);+ }+ }+ return { answers, usage: usageOf(json.usage) };+ },beatapi: async (cred, modelId, body, signal) => {const json = await upstream(`${BEATAPI_BASE_URL}/systemone`, 'beatapi', {method: 'POST', redirect: 'error',diff --git a/server/src/services/provider-quota.ts b/server/src/services/provider-quota.tsindex b94a8b60..20f2eeb0 100644--- a/server/src/services/provider-quota.ts+++ b/server/src/services/provider-quota.ts@@ -121,6 +121,7 @@ export function inferPoolForPlatform(platform: Platform, modelId?: string | null// Auray: free credits renew monthly and are one wallet shared across chat// and embeddings (see providers/auray.ts), so one pool for the account.if (platform === 'auray') return 'auray::monthly-credit';+ if (platform === 'apinex') return 'apinex::daily-free';if (platform === 'plugsky') return 'plugsky::fair-use';if (platform === 'inferbase') return 'inferbase::managed-free';if (platform === 'simplellm') return 'simplellm::free';@@ -183,6 +184,7 @@ export function inferPoolForPlatform(platform: Platform, modelId?: string | null}function isSharedPool(platform: Platform): boolean {+ if (platform === 'apinex') return true;if (platform === 'aclide') return true;if (platform === 'speka') return true;if (platform === 'auray') return true;diff --git a/shared/types.ts b/shared/types.tsindex 02e04df9..8955655c 100644--- a/shared/types.ts+++ b/shared/types.ts@@ -76,6 +76,8 @@ export type Platform =| 'auray'// Decision-only JEV adapter; promotional availability is catalog-managed.| 'beatapi'+ // Free-category chat and decisions share one weighted daily allowance.+ | 'apinex'// Ongoing free research API for chat and speech recognition; catalog only.| 'typhoon'// Permanent free chat aliases, shared fair-use quota; signed catalog only.