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
Add ModelScope provider (#581)
Tashfeenb05b2f8ae2a3
diff --git a/README.md b/README.mdindex 5e758d0a..c4f9208f 100644--- a/README.md+++ b/README.md@@ -2,7 +2,7 @@# FreeLLMAPI-**One OpenAI-compatible endpoint. 28 free LLM providers. 339 free model endpoints. ~4 billion tokens per month.**+**One OpenAI-compatible endpoint. 29 free LLM providers. 339 free model endpoints. ~4 billion tokens per month.**Aggregate free tiers from dozens of providers, plus custom OpenAI-compatible chat, embedding, image, and audio endpoints, behind a single `/v1` API. Keys are stored encrypted. A router picks the best available model for each request, falls over to the next provider when one is rate-limited, and tracks per-key usage so you stay under every free-tier cap.@@ -51,7 +51,7 @@ Your router updates its own model catalog from a signed feed: new free models, qEvery serious AI lab now offers a free tier — a few million tokens a month, a few thousand requests a day. On its own each tier is a toy. Stacked together, they add up to roughly **4 billion tokens per month** of working inference capacity, across **235 model families / 339 provider endpoints** from small-and-fast to reasonably capable.-The problem is that stacking them by hand is painful: twenty-eight different SDKs, twenty-eight different rate limits, twenty-eight places a request can fail. FreeLLMAPI collapses that into one OpenAI-compatible endpoint. Point any OpenAI client library at your local server, and it routes transparently across whichever providers you've added keys for.+The problem is that stacking them by hand is painful: twenty-nine different SDKs, twenty-nine different rate limits, twenty-nine places a request can fail. FreeLLMAPI collapses that into one OpenAI-compatible endpoint. Point any OpenAI client library at your local server, and it routes transparently across whichever providers you've added keys for.And the free-tier landscape shifts weekly: providers launch models, retire them, and change quotas without notice. FreeLLMAPI tracks all of that for you. The router pulls a signed model catalog from [freellmapi.co](https://freellmapi.co) on its own, so your install keeps up without a `git pull`. See [Premium (live catalog)](#premium-live-catalog) for how fast it keeps up.@@ -76,6 +76,9 @@ And the free-tier landscape shifts weekly: providers launch models, retire them,<td align="center"><a href="https://build.nvidia.com"><b>NVIDIA</b><br/>NIM · 40 RPM free (eval-only ToS)</a></td><td align="center"><a href="https://huggingface.co/docs/inference-providers"><b>HuggingFace</b><br/>Router → DeepSeek V4 · Kimi K2.6 · Qwen3</a></td></tr>+<tr>+<td align="center"><a href="https://modelscope.cn"><b>ModelScope</b><br/>Qwen3 · DeepSeek V4 · GLM-5 (needs Aliyun cn binding)</a></td>+</tr></table><p align="center"><strong>…and many more.</strong></p>diff --git a/client/src/components/keys/shared.tsx b/client/src/components/keys/shared.tsxindex ff80afdc..c7d3349c 100644--- a/client/src/components/keys/shared.tsx+++ b/client/src/components/keys/shared.tsx@@ -54,6 +54,7 @@ export const PLATFORMS: { value: Platform; label: string; url: string; keyless?:{ value: 'navy', label: 'NavyAI (free key)', url: 'https://api.navy' },{ value: 'nara', label: 'NaraRouter (free key)', url: 'https://router.bynara.id' },{ value: 'sealion', label: 'SEA-LION (free key)', url: 'https://sea-lion.ai' },+ { value: 'modelscope', label: 'ModelScope (free key, needs Aliyun cn binding)', url: 'https://modelscope.cn/my/myaccesstoken' },{ value: 'aihorde', label: 'AI Horde (no key needed, slow)', url: 'https://aihorde.net/register', keyless: true },]diff --git a/client/src/lib/routing.ts b/client/src/lib/routing.tsindex e8fffb22..8c634c7a 100644--- a/client/src/lib/routing.ts+++ b/client/src/lib/routing.ts@@ -168,6 +168,7 @@ export const platformColors: Record<string, string> = {navy: '#1d4ed8',nara: '#2563eb',sealion: '#0ea5e9',+ modelscope: '#624aff',aihorde: '#dc2626',}diff --git a/server/src/__tests__/lib/key-parser.test.ts b/server/src/__tests__/lib/key-parser.test.tsindex 43fa6825..e9f70ef3 100644--- a/server/src/__tests__/lib/key-parser.test.ts+++ b/server/src/__tests__/lib/key-parser.test.ts@@ -42,6 +42,7 @@ describe('key parser', () => {expect(detectPlatform('REQUESTY_')).toBe('requesty');expect(detectPlatform('NAVYAI_')).toBe('navy');expect(detectPlatform('SEALION_')).toBe('sealion');+ expect(detectPlatform('MODELSCOPE_')).toBe('modelscope');expect(detectPlatform('SAMBANOVA_')).toBeNull();});@@ -52,6 +53,7 @@ describe('key parser', () => {expect(AUTH_JSON_PROVIDER_MAP['requesty']).toBe('requesty');expect(AUTH_JSON_PROVIDER_MAP['api-navy']).toBe('navy');expect(AUTH_JSON_PROVIDER_MAP['sea-lion']).toBe('sealion');+ expect(AUTH_JSON_PROVIDER_MAP['model-scope']).toBe('modelscope');const result = parseAuthJson(JSON.stringify({credential_pool: {gemini: [{ id: '1', label: 'Gemini', auth_type: 'api_key', access_token: 'AIza-test' }],diff --git a/server/src/__tests__/providers/modelscope.test.ts b/server/src/__tests__/providers/modelscope.test.tsnew file mode 100644index 00000000..721e5cec--- /dev/null+++ b/server/src/__tests__/providers/modelscope.test.ts@@ -0,0 +1,141 @@+import { describe, it, expect, vi, afterEach } from 'vitest';+import { ModelScopeProvider } from '../../providers/modelscope.js';+import { getProvider, hasProvider, resolveProvider } from '../../providers/index.js';+import type { KeyValidationFailure } from '../../providers/base.js';++// All fixtures are deliberately fake — no real ModelScope tokens exist for+// this project yet (auth requires an Alibaba Cloud cn-site account binding).+const GARBAGE_KEY = 'ms-test-invalid';++const ROSTER = {+ ok: true,+ status: 200,+ json: () => Promise.resolve({+ object: 'list',+ data: [+ { id: 'Qwen/Qwen3-235B-A22B-Instruct-2507', object: 'model' },+ { id: 'deepseek-ai/DeepSeek-V4-Flash', object: 'model' },+ ],+ }),+};++// The verified keyless probe (2026-07-26): a 401 from chat/completions with a+// garbage Bearer token. The alibaba-binding variant below is the+// maintainer-documented shape for unbound accounts — unconfirmed until a+// community tester runs a real token (#581).+const AUTH_FAILED_401 = {+ ok: false,+ status: 401,+ json: () => Promise.resolve({+ error: { message: 'please bind your alibaba cloud account before use' },+ }),+};++afterEach(() => {+ vi.restoreAllMocks();+});++describe('ModelScope registration (#581)', () => {+ it('is registered and routable in the provider registry', () => {+ expect(hasProvider('modelscope')).toBe(true);+ const provider = getProvider('modelscope');+ expect(provider).toBeInstanceOf(ModelScopeProvider);+ expect(provider?.platform).toBe('modelscope');+ expect(provider?.name).toBe('ModelScope');+ expect(provider?.keyless).toBe(false);+ // resolveProvider (the routing entry point) returns the same singleton.+ expect(resolveProvider('modelscope')).toBe(provider);+ });+});++describe('ModelScope validateKey (#581)', () => {+ it('does NOT trust GET /v1/models — a garbage key that 200s there is still invalid', async () => {+ // The trap: ModelScope's /v1/models answers 200 with or without auth+ // (verified keyless 2026-07-26), so the default openai-compat validateKey+ // would mark garbage keys healthy forever.+ const calls: Array<{ url: string; init: RequestInit }> = [];+ vi.spyOn(global, 'fetch').mockImplementation(async (url, init) => {+ calls.push({ url: String(url), init: init as RequestInit });+ if (String(url).endsWith('/models')) return ROSTER as unknown as Response;+ return AUTH_FAILED_401 as unknown as Response;+ });++ const provider = new ModelScopeProvider();+ const result = await provider.validateKey(GARBAGE_KEY);++ expect(result).not.toBe(true);+ const failure = result as KeyValidationFailure;+ expect(failure.valid).toBe(false);+ // The alibaba-binding reason must surface verbatim in the health error.+ expect(failure.error).toContain('please bind your alibaba cloud account before use');+ expect(failure.error).toContain('401');++ // Probe shape: models list first (to pick a live model id), then a+ // 1-token chat completion that actually enforces auth.+ expect(calls).toHaveLength(2);+ expect(calls[0].url).toBe('https://api-inference.modelscope.cn/v1/models');+ expect(calls[1].url).toBe('https://api-inference.modelscope.cn/v1/chat/completions');+ expect(calls[1].init.method).toBe('POST');+ const body = JSON.parse(String(calls[1].init.body));+ expect(body.model).toBe('Qwen/Qwen3-235B-A22B-Instruct-2507'); // first roster entry+ expect(body.max_tokens).toBe(1);+ expect((calls[1].init.headers as Record<string, string>)['Authorization']).toBe(`Bearer ${GARBAGE_KEY}`);+ });++ it('returns true when the 1-token chat probe authenticates (200)', async () => {+ vi.spyOn(global, 'fetch').mockImplementation(async (url) => {+ if (String(url).endsWith('/models')) return ROSTER as unknown as Response;+ return {+ ok: true,+ status: 200,+ json: () => Promise.resolve({+ id: 'chatcmpl-1', object: 'chat.completion', created: 1,+ model: 'Qwen/Qwen3-235B-A22B-Instruct-2507',+ choices: [{ index: 0, message: { role: 'assistant', content: 'p' }, finish_reason: 'length' }],+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },+ }),+ } as unknown as Response;+ });++ const provider = new ModelScopeProvider();+ await expect(provider.validateKey('ms-test-valid-shaped')).resolves.toBe(true);+ });++ it('treats a 429 probe answer as a VALID key (quota, not auth)', async () => {+ // ModelScope also 429s for retired models ("insufficient balance (1008)").+ // Neither case is an auth failure, so the key must not be disabled.+ vi.spyOn(global, 'fetch').mockImplementation(async (url) => {+ if (String(url).endsWith('/models')) return ROSTER as unknown as Response;+ return {+ ok: false,+ status: 429,+ json: () => Promise.resolve({ error: { message: 'Request limit exceeded' } }),+ } as unknown as Response;+ });++ const provider = new ModelScopeProvider();+ await expect(provider.validateKey('ms-test-valid-shaped')).resolves.toBe(true);+ });++ it('throws (health status=error, never invalid) when the roster fetch fails', async () => {+ vi.spyOn(global, 'fetch').mockResolvedValue({+ ok: false,+ status: 503,+ json: () => Promise.resolve({}),+ } as unknown as Response);++ const provider = new ModelScopeProvider();+ await expect(provider.validateKey(GARBAGE_KEY)).rejects.toThrow(/HTTP 503/);+ });++ it('throws when the roster is empty (no probe model available)', async () => {+ vi.spyOn(global, 'fetch').mockResolvedValue({+ ok: true,+ status: 200,+ json: () => Promise.resolve({ object: 'list', data: [] }),+ } as unknown as Response);++ const provider = new ModelScopeProvider();+ await expect(provider.validateKey(GARBAGE_KEY)).rejects.toThrow(/no models/);+ });+});diff --git a/server/src/__tests__/providers/openai-compat.test.ts b/server/src/__tests__/providers/openai-compat.test.tsindex 686c805a..fed7e574 100644--- a/server/src/__tests__/providers/openai-compat.test.ts+++ b/server/src/__tests__/providers/openai-compat.test.ts@@ -510,6 +510,9 @@ describe('OpenAICompatProvider - platform instances', () => {{ platform: 'navy', name: 'NavyAI', baseUrl: 'https://api.navy/v1' },{ platform: 'nara', name: 'NaraRouter', baseUrl: 'https://router.bynara.id/v1' },{ platform: 'sealion', name: 'SEA-LION', baseUrl: 'https://api.sea-lion.ai/v1' },+ // modelscope registers a ModelScopeProvider subclass (custom validateKey,+ // see providers/modelscope.test.ts) but chat routing is stock openai-compat.+ { platform: 'modelscope', name: 'ModelScope', baseUrl: 'https://api-inference.modelscope.cn/v1' },] as const;for (const p of platforms) {diff --git a/server/src/__tests__/routes/keys.test.ts b/server/src/__tests__/routes/keys.test.tsindex 18203226..c7490a53 100644--- a/server/src/__tests__/routes/keys.test.ts+++ b/server/src/__tests__/routes/keys.test.ts@@ -130,6 +130,19 @@ describe('Keys API', () => {expect(body.notice ?? null).toBeNull();});+ it('POST /api/keys accepts the modelscope platform (#581)', async () => {+ const { status, body } = await request(app, 'POST', '/api/keys', {+ platform: 'modelscope',+ key: 'ms-test-invalid-not-a-real-token',+ label: 'ModelScope test',+ });+ expect(status).toBe(201);+ expect(body.platform).toBe('modelscope');+ // Catalog rows land only after community testing (#581), so a fresh DB+ // has no modelscope models and the no-catalog-models notice is expected.+ expect(body.modelsAvailable).toBe(0);+ });+it('POST /api/keys rejects invalid platform', async () => {const { status } = await request(app, 'POST', '/api/keys', {platform: 'invalid_platform',diff --git a/server/src/__tests__/services/ratelimit.test.ts b/server/src/__tests__/services/ratelimit.test.tsindex a6d1d868..aea3d40c 100644--- a/server/src/__tests__/services/ratelimit.test.ts+++ b/server/src/__tests__/services/ratelimit.test.ts@@ -264,6 +264,8 @@ describe('Rate Limiter', () => {it('defaults to OpenRouter ~1000/day and allows env override / disable', () => {delete process.env[ENV];expect(getProviderDailyRequestCap('openrouter')).toBe(1000);+ // ModelScope: 2000/day account-wide upstream, shipped as 1800 for margin (#581).+ expect(getProviderDailyRequestCap('modelscope')).toBe(1800);expect(getProviderDailyRequestCap('groq')).toBeNull(); // no shared capprocess.env[ENV] = '50';expect(getProviderDailyRequestCap('openrouter')).toBe(50);diff --git a/server/src/lib/key-parser.ts b/server/src/lib/key-parser.tsindex d8258954..634ba65e 100644--- a/server/src/lib/key-parser.ts+++ b/server/src/lib/key-parser.ts@@ -44,6 +44,8 @@ export const PREFIX_MAP: Record<string, string> = {BYNARA_: 'nara',SEALION_: 'sealion',SEA_LION_: 'sealion',+ MODELSCOPE_: 'modelscope',+ MODEL_SCOPE_: 'modelscope',AIHORDE_: 'aihorde',};@@ -69,6 +71,8 @@ export const AUTH_JSON_PROVIDER_MAP: Record<string, string> = {'nara-router': 'nara',sealion: 'sealion','sea-lion': 'sealion',+ modelscope: 'modelscope',+ 'model-scope': 'modelscope',};export function detectPlatform(prefix: string): string | null {diff --git a/server/src/providers/index.ts b/server/src/providers/index.tsindex d73d7039..8c1b6bc5 100644--- a/server/src/providers/index.ts+++ b/server/src/providers/index.ts@@ -5,6 +5,7 @@ import { OpenAICompatProvider } from './openai-compat.js';import { CohereProvider } from './cohere.js';import { CloudflareProvider } from './cloudflare.js';import { AIHordeProvider } from './aihorde.js';+import { ModelScopeProvider } from './modelscope.js';const providers = new Map<Platform, BaseProvider>();@@ -329,6 +330,25 @@ register(new OpenAICompatProvider({baseUrl: 'https://api.sea-lion.ai/v1',}));+// ModelScope (魔搭社区, Alibaba) — OpenAI-compatible inference API+// (api-inference.modelscope.cn/v1, Bearer auth). Free tier: 2000 requests/day+// account-wide. Token from modelscope.cn/my/myaccesstoken, BUT calls only work+// after binding the ModelScope account to an Alibaba Cloud CHINA-site (cn)+// account with Chinese real-name verification — unbound tokens 401 on every+// call ("please bind your alibaba cloud account before use"). Dedicated+// ModelScopeProvider (not plain OpenAICompatProvider) because GET /v1/models+// answers 200 even for garbage tokens, so key validation needs a 1-token chat+// probe instead — see providers/modelscope.ts.+//+// RETIRED-model gotcha (#581): ModelScope answers requests for retired models+// with `429 insufficient balance (1008)`. isPaymentRequiredError+// (lib/error-classify.ts) reads "insufficient balance" as out-of-credits and+// benches the key ~24h — intentionally NOT special-cased in the shared+// classifier (the string is a genuine payment marker everywhere else). Keep+// retired ids out of the catalog instead; the quota-header path in+// provider-quota.ts keys on response headers, never on that message text.+register(new ModelScopeProvider());+// AI Horde — free, community-powered inference (volunteer workers) via an// OpenAI-compatible proxy. Dedicated AIHordeProvider (not OpenAICompatProvider)// because the proxy is queue-based and diverges from the OpenAI contract:diff --git a/server/src/providers/modelscope.ts b/server/src/providers/modelscope.tsnew file mode 100644index 00000000..e8393be5--- /dev/null+++ b/server/src/providers/modelscope.ts@@ -0,0 +1,106 @@+import { OpenAICompatProvider } from './openai-compat.js';+import type { KeyValidationResult } from './base.js';+import { recordQuotaObservationsFromResponse, type QuotaObservationContext } from '../services/provider-quota.js';++const MODELSCOPE_BASE_URL = 'https://api-inference.modelscope.cn/v1';++/**+ * ModelScope (魔搭社区, Alibaba) — OpenAI-compatible inference API.+ *+ * Everything except key validation is stock OpenAI-compat. validateKey is+ * overridden because of a trap in ModelScope's API surface:+ *+ * GET /v1/models returns 200 WITHOUT auth — and, verified keyless on+ * 2026-07-26, it also returns 200 with a GARBAGE Bearer token. The default+ * openai-compat validateKey (GET /v1/models with the key) would therefore+ * mark any invalid key healthy forever. /v1/models is useless for+ * validation on this platform.+ *+ * The only endpoint verified to enforce auth is POST /v1/chat/completions:+ * a garbage token gets a clean+ * 401 {"error":{"message":"Authentication failed, please make sure that a+ * valid ModelScope token is supplied."}}+ * before any generation happens. So validation makes a 1-token chat+ * completion. The model id is picked dynamically from GET /v1/models (first+ * entry) because the roster churns — a hardcoded id would rot.+ *+ * COST: a successful validation burns 1 request (and ~1 output token) of the+ * 2000-requests/day account-wide free quota per health check. A failed-auth+ * validation is rejected before generation and, per maintainer reports, does+ * not count against quota.+ *+ * Community testers must confirm (we have NO real token for this platform):+ * the maintainer-documented bad-binding failure is+ * `401 please bind your alibaba cloud account before use`+ * — a token minted without binding the ModelScope account to an Alibaba+ * Cloud CHINA-site account fails every call with that message. It flows+ * through validationResult() into the health error verbatim so users see the+ * actionable reason instead of a generic "invalid key". See issue #581.+ */+export class ModelScopeProvider extends OpenAICompatProvider {+ constructor() {+ super({+ platform: 'modelscope',+ name: 'ModelScope',+ // Serves large reasoning models (DeepSeek-V4, Qwen3 Thinking variants)+ // from cn-region infrastructure; cross-region TTFB plus buffered+ // reasoning phases blow the 60s default. 90s matches NVIDIA NIM's+ // allowance for the same model class.+ baseUrl: MODELSCOPE_BASE_URL,+ timeoutMs: 90_000,+ });+ }++ override async validateKey(apiKey: string, quotaContext?: QuotaObservationContext): Promise<KeyValidationResult> {+ // Transport errors (DNS / timeout / TLS) propagate — health.ts marks+ // status='error' without counting toward auto-disable; only a confirmed+ // 401/403 disables a key.++ // Step 1: pick a live model id for the auth probe. This call is NOT the+ // validation (it answers 200 for any token, see class comment) — it only+ // keeps the probe's model id in sync with the churning roster.+ const modelsRes = await this.fetchWithTimeout(`${MODELSCOPE_BASE_URL}/models`, {+ method: 'GET',+ headers: { 'Authorization': `Bearer ${apiKey}` },+ }, 30000, { timeoutBounds: 'request' });+ if (!modelsRes.ok) {+ // Auth failures cannot happen here (endpoint is unauthenticated); treat+ // any non-200 as an upstream outage → status='error', never 'invalid'.+ throw new Error(`ModelScope /models returned HTTP ${modelsRes.status} while picking a validation probe model`);+ }+ const roster = await modelsRes.json().catch(() => null) as { data?: Array<{ id?: string }> } | null;+ const probeModel = roster?.data?.[0]?.id;+ if (!probeModel) {+ throw new Error('ModelScope /models returned no models to probe key validity against');+ }++ // Step 2: the actual auth check — a minimal 1-token completion.+ const res = await this.fetchWithTimeout(`${MODELSCOPE_BASE_URL}/chat/completions`, {+ method: 'POST',+ headers: {+ 'Authorization': `Bearer ${apiKey}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({+ model: probeModel,+ messages: [{ role: 'user', content: 'ping' }],+ max_tokens: 1,+ }),+ }, 30000, { timeoutBounds: 'request' });++ recordQuotaObservationsFromResponse(res, {+ platform: this.platform,+ keyId: quotaContext?.keyId,+ providerAccountId: quotaContext?.providerAccountId,+ modelId: probeModel,+ quotaPoolKey: quotaContext?.quotaPoolKey,+ endpoint: 'chat/completions',+ });++ // validationResult: 401/403 → {valid:false, error:<upstream message>}+ // (surfaces the alibaba-binding reason); everything else — 200, but also+ // 400/404 (probe model quirk), 429 (quota) — proves the token+ // authenticated and returns true.+ return this.validationResult(res);+ }+}diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex a956efc0..afe32a65 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -21,7 +21,7 @@ const PLATFORMS = ['google', 'groq', 'cerebras', 'nvidia', 'mistral','openrouter', 'github', 'cohere', 'cloudflare', 'zhipu', 'ollama','kilo', 'pollinations', 'llm7', 'huggingface', 'opencode', 'ovh', 'agnes', 'reka', 'siliconflow',- 'routeway', 'bazaarlink', 'ainative', 'aion', 'requesty', 'navy', 'nara', 'sealion', 'aihorde', 'custom',+ 'routeway', 'bazaarlink', 'ainative', 'aion', 'requesty', 'navy', 'nara', 'sealion', 'modelscope', 'aihorde', 'custom',] as const;const ALLOWED_IMPORT_EXTENSIONS = new Set(['.env', '.json', '.jsonc', '.md', '.txt', '.csv']);diff --git a/server/src/services/provider-quota.ts b/server/src/services/provider-quota.tsindex cbb2bbd4..1cb15d44 100644--- a/server/src/services/provider-quota.ts+++ b/server/src/services/provider-quota.ts@@ -141,11 +141,13 @@ function inferPoolForPlatform(platform: Platform, modelId?: string | null): striif (platform === 'navy') return 'navy::free';if (platform === 'nara') return 'nara::free';if (platform === 'sealion') return 'sealion::free';+ // ModelScope: one 2000-requests/day quota across the whole account.+ if (platform === 'modelscope') return 'modelscope::account';return normalizedModelId ? `${platform}::${normalizedModelId}` : `${platform}::account`;}function isSharedPool(platform: Platform): boolean {- return ['openrouter', 'google', 'groq', 'cerebras', 'sambanova', 'nvidia', 'mistral', 'github', 'cohere', 'cloudflare', 'zhipu', 'ollama', 'kilo', 'pollinations', 'llm7', 'huggingface', 'opencode', 'routeway', 'bazaarlink', 'ainative', 'aion', 'requesty', 'navy', 'nara', 'sealion', 'aihorde'].includes(platform);+ return ['openrouter', 'google', 'groq', 'cerebras', 'sambanova', 'nvidia', 'mistral', 'github', 'cohere', 'cloudflare', 'zhipu', 'ollama', 'kilo', 'pollinations', 'llm7', 'huggingface', 'opencode', 'routeway', 'bazaarlink', 'ainative', 'aion', 'requesty', 'navy', 'nara', 'sealion', 'modelscope', 'aihorde'].includes(platform);}type HeaderSpec = { metric: QuotaMetric; limit: string; remaining?: string; reset?: string; strategy?: QuotaResetStrategy };@@ -163,6 +165,17 @@ const HEADER_SPECS: Partial<Record<Platform, HeaderSpec[]>> = {{ metric: 'requests', limit: 'x-ratelimit-limit-requests', remaining: 'x-ratelimit-remaining-requests', reset: 'x-ratelimit-reset-requests', strategy: 'provider_reported' },{ metric: 'tokens', limit: 'x-ratelimit-limit-tokens', remaining: 'x-ratelimit-remaining-tokens', reset: 'x-ratelimit-reset-tokens', strategy: 'provider_reported' },],+ // ModelScope reportedly returns `modelscope-ratelimit-*`-style headers on+ // authenticated responses. UNCONFIRMED: no real token exists for this+ // platform yet (auth needs an Alibaba Cloud cn-site binding, #581), and the+ // keyless probes we could run (401s, unauthenticated /v1/models) carry no+ // ratelimit headers at all. Absent headers are a no-op in+ // maybeAddObservation, so a wrong guess here costs nothing; community+ // testers should dump response headers (see the #581 tester guide) and+ // correct these names.+ modelscope: [+ { metric: 'requests', limit: 'modelscope-ratelimit-requests-limit', remaining: 'modelscope-ratelimit-requests-remaining', reset: 'modelscope-ratelimit-requests-reset', strategy: 'provider_reported' },+ ],};function extractContext(opts: Pick<QuotaObservationInput, 'platform' | 'modelId' | 'quotaPoolKey' | 'keyId' | 'providerAccountId' | 'endpoint'> = {}) {diff --git a/server/src/services/ratelimit.ts b/server/src/services/ratelimit.tsindex aead6fd7..90369d84 100644--- a/server/src/services/ratelimit.ts+++ b/server/src/services/ratelimit.ts@@ -347,6 +347,10 @@ export function canUseTokens(// PROVIDER_DAILY_REQUEST_CAP_OPENROUTER=50 (set 0 to disable the cap)const DEFAULT_PROVIDER_DAILY_REQUEST_CAPS: Record<string, number> = {openrouter: 1000,+ // ModelScope's free tier is 2000 requests/day across the whole account (all+ // models share it). 1800 leaves margin for validation probes and for drift+ // between our ledger and the provider's own daily boundary (#581).+ modelscope: 1800,};const DEFAULT_PROVIDER_DAILY_TOKEN_CAPS: Record<string, number> = {diff --git a/shared/types.ts b/shared/types.tsindex 3cae3d5f..0822e5a7 100644--- a/shared/types.ts+++ b/shared/types.ts@@ -102,6 +102,13 @@ export type Platform =// (Google sign-in, no card, no region wall) at 10 RPM; catalog rows live in// the Oracle catalog (premium now, free after 30 days).| 'sealion'+ // ModelScope (魔搭社区, Alibaba) — OpenAI-compatible inference API+ // (api-inference.modelscope.cn/v1). Free tier is 2000 requests/day+ // account-wide, but calls only work after the ModelScope account is bound to+ // an Alibaba Cloud CHINA-site (cn) account with Chinese real-name+ // verification — tokens mint without binding, then every call 401s. Catalog+ // rows land after community testing confirms per-model behavior (#581).+ | 'modelscope'// AI Horde — free, community-powered inference (volunteer workers) via an// OpenAI-compatible proxy (https://oai.aihorde.net/v1). Queue-based, so calls// can take tens of seconds; no tool support; usage is reported as kudos, not