mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-25 07:09:11 +00:00
feat(ai): monitor upstream model catalog changes (#4690)
* feat(ai): monitor upstream model catalog changes * fix(ai): persist catalog snapshots before change alerts * Remove the clause
This commit is contained in:
1 parent
0a5328bb24
commit
b3dad7a996
3 files changed
+823
No files matched your search
@@ -211,3 +211,36 @@ Below that, the chat transport won't repost the same alarm id within
|
||||
`repeatThrottleMs` (default 15 minutes). The first occurrence always posts,
|
||||
and the next one that gets through reports how many piled up in between —
|
||||
so a hot loop reads as one message with a count, not a wall of them.
|
||||
|
||||
## AI model catalog monitoring
|
||||
|
||||
The `aiModelMonitor` extension registers a fleet job automatically at boot.
|
||||
The scheduler checks for due work at startup and runs scans every 30 minutes
|
||||
until shutdown. It uses the configured provider keys,
|
||||
fetches complete upstream model lists, and records snapshots in the system KV
|
||||
store. The first successful scan establishes a baseline. A different endpoint
|
||||
or API key establishes a fresh baseline because account visibility can differ.
|
||||
|
||||
Each added or removed model raises an `info` alarm on `ai_providers`, which can
|
||||
map to `#alerts-ai` through `pager.slack.channels`. Unchanged catalogs are quiet.
|
||||
A failed, invalid, oversized, or incomplete listing raises a fetch-failure alarm
|
||||
and retains the last successful snapshot. Snapshot read or write failures raise
|
||||
a separate snapshot-failure alarm without emitting model changes. The monitor
|
||||
saves the new snapshot before emitting change alerts, so a failed save can be
|
||||
retried without replaying alerts. This isn't a durable alert queue. A process
|
||||
that stops after saving and before emitting can miss those alerts.
|
||||
Removing a provider's configuration
|
||||
doesn't report all of its models as removed.
|
||||
|
||||
| Providers | Monitoring |
|
||||
| --- | --- |
|
||||
| OpenAI, Azure, Claude, Gemini, Groq, DeepSeek, Mistral, Moonshot, MiniMax, Z.ai, BytePlus, Hoonify, Meta, ElevenLabs, Replicate | Model-listing API, including configured OpenAI and Gemini media keys |
|
||||
| Alibaba, Infron, Neuralwatt, Ollama, OpenRouter, Together, xAI, Cloudflare | Excluded because their upstream catalogs already refresh automatically |
|
||||
| AWS Polly and Textract, Kling, Speechify | No supported model-listing endpoint in this monitor |
|
||||
| Fake | Test provider with no upstream endpoint |
|
||||
|
||||
The monitor compares identifiers returned by each provider, across all model
|
||||
modalities that endpoint exposes. It doesn't modify Puter's model catalogs.
|
||||
The scheduler runs once across the fleet when a fleet scheduler is installed,
|
||||
and once per region with the built-in scheduler. See the scheduler's deployment
|
||||
configuration when running the monitor across regions.
|
||||
@@ -0,0 +1,473 @@
|
||||
import axios from 'axios';
|
||||
import { AlarmClient } from '../src/backend/clients/alarm/AlarmClient';
|
||||
import { JobScheduler } from '../src/backend/services/jobs/JobScheduler';
|
||||
import { createServer, type Server } from 'node:http';
|
||||
import { afterAll, beforeAll, beforeEach, expect, it, vi } from 'vitest';
|
||||
import { AIModelMonitorService } from './aiModelMonitor';
|
||||
import { setupTestServer } from '../src/backend/testUtil';
|
||||
import type { PuterServer } from '../src/backend/server';
|
||||
import type { IConfig } from '../src/backend/types';
|
||||
import type { AlertPayload } from '../src/backend/clients/alarm/types';
|
||||
import type { JobRunContext } from '../src/backend/services/jobs/JobScheduler';
|
||||
|
||||
let backend: PuterServer;
|
||||
let upstream: Server;
|
||||
let origin: string;
|
||||
let body: unknown;
|
||||
let status = 200;
|
||||
let requests: Array<{
|
||||
url: string;
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
}>;
|
||||
let responder: ((url: string) => unknown) | undefined;
|
||||
const alerts: AlertPayload[] = [];
|
||||
let seq = 0;
|
||||
const ctx = (): JobRunContext => ({
|
||||
signal: new AbortController().signal,
|
||||
state: null,
|
||||
saveState: async () => {},
|
||||
});
|
||||
const service = (key = 'openai', extra: Record<string, unknown> = {}) =>
|
||||
new AIModelMonitorService(
|
||||
{
|
||||
providers: {
|
||||
[key]: {
|
||||
apiKey: `fixture-${++seq}`,
|
||||
apiBaseUrl: origin,
|
||||
...extra,
|
||||
},
|
||||
},
|
||||
} as IConfig,
|
||||
backend.clients,
|
||||
backend.stores,
|
||||
backend.services,
|
||||
);
|
||||
|
||||
beforeAll(async () => {
|
||||
backend = await setupTestServer();
|
||||
backend.clients.alarm.addAlertHandler(
|
||||
async (alert) => {
|
||||
alerts.push(alert);
|
||||
},
|
||||
{ minSeverity: 'info' },
|
||||
);
|
||||
upstream = createServer((req, res) => {
|
||||
requests.push({ url: req.url!, headers: req.headers });
|
||||
res.writeHead(status, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify(responder ? responder(req.url!) : body));
|
||||
});
|
||||
await new Promise<void>((resolve) =>
|
||||
upstream.listen(0, '127.0.0.1', resolve),
|
||||
);
|
||||
origin = `http://127.0.0.1:${(upstream.address() as { port: number }).port}`;
|
||||
});
|
||||
afterAll(async () => {
|
||||
await new Promise<void>((resolve) => upstream.close(() => resolve()));
|
||||
await backend.shutdown();
|
||||
});
|
||||
beforeEach(() => {
|
||||
alerts.length = 0;
|
||||
requests = [];
|
||||
status = 200;
|
||||
body = { data: [{ id: 'old' }, { id: 'kept' }] };
|
||||
responder = undefined;
|
||||
});
|
||||
|
||||
it('baselines quietly, persists across instances, and reports additions and removals once', async () => {
|
||||
const monitor = service();
|
||||
await monitor.scan(ctx());
|
||||
expect(alerts).toHaveLength(0);
|
||||
body = { data: [{ id: 'new' }, { id: 'kept' }, { id: 'new' }] };
|
||||
await monitor.scan(ctx());
|
||||
expect(
|
||||
alerts.map((alert) => [
|
||||
alert.fields.change.replaceAll("'", ''),
|
||||
alert.fields.model.replaceAll("'", ''),
|
||||
]),
|
||||
).toEqual([
|
||||
['added', 'new'],
|
||||
['removed', 'old'],
|
||||
]);
|
||||
expect(
|
||||
alerts.every(
|
||||
(alert) =>
|
||||
alert.channel === 'ai_providers' && alert.severity === 'info',
|
||||
),
|
||||
).toBe(true);
|
||||
const restarted = new AIModelMonitorService(
|
||||
{
|
||||
providers: {
|
||||
openai: { apiKey: `fixture-${seq}`, apiBaseUrl: origin },
|
||||
},
|
||||
} as IConfig,
|
||||
backend.clients,
|
||||
backend.stores,
|
||||
backend.services,
|
||||
);
|
||||
await restarted.scan(ctx());
|
||||
expect(alerts).toHaveLength(2);
|
||||
});
|
||||
|
||||
it.each([
|
||||
null,
|
||||
{ data: [{}] },
|
||||
{ data: [{ id: 'x' }], has_more: true },
|
||||
{ error: 'denied' },
|
||||
])(
|
||||
'retains the baseline for an invalid or incomplete response %j',
|
||||
async (invalid) => {
|
||||
const monitor = service();
|
||||
await monitor.scan(ctx());
|
||||
body = invalid;
|
||||
await monitor.scan(ctx());
|
||||
expect(alerts.at(-1)?.message).toBe(
|
||||
'AI provider model catalog fetch failed',
|
||||
);
|
||||
alerts.length = 0;
|
||||
body = { data: [{ id: 'kept' }] };
|
||||
await monitor.scan(ctx());
|
||||
expect(
|
||||
alerts.map((alert) => alert.fields.model?.replaceAll("'", '')),
|
||||
).toEqual(['old']);
|
||||
},
|
||||
);
|
||||
|
||||
it('keeps failures isolated and never includes upstream error text or credentials', async () => {
|
||||
const monitor = service();
|
||||
status = 401;
|
||||
body = { error: 'secret-response' };
|
||||
await monitor.scan(ctx());
|
||||
expect(alerts).toHaveLength(1);
|
||||
expect(JSON.stringify(alerts)).not.toContain('secret-response');
|
||||
expect(JSON.stringify(alerts)).not.toContain(`fixture-${seq}`);
|
||||
});
|
||||
|
||||
it('follows Claude pagination with the correct authentication', async () => {
|
||||
responder = (url) =>
|
||||
url.includes('after_id=first')
|
||||
? { data: [{ id: 'last' }], has_more: false }
|
||||
: { data: [{ id: 'first' }], has_more: true, last_id: 'first' };
|
||||
await service('claude').scan(ctx());
|
||||
expect(requests.map((req) => req.url)).toEqual([
|
||||
'/models',
|
||||
'/models?after_id=first',
|
||||
]);
|
||||
expect(requests[0].headers['x-api-key']).toBe(`fixture-${seq}`);
|
||||
expect(requests[0].headers['anthropic-version']).toBe('2023-06-01');
|
||||
expect(alerts).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('reads ElevenLabs model_id and reports an empty successful catalog as removals', async () => {
|
||||
const monitor = service('elevenlabs');
|
||||
body = [{ model_id: 'voice-model' }];
|
||||
await monitor.scan(ctx());
|
||||
body = [];
|
||||
await monitor.scan(ctx());
|
||||
expect(
|
||||
alerts.map((alert) => alert.fields.model?.replaceAll("'", '')),
|
||||
).toEqual(['voice-model']);
|
||||
expect(requests[0].headers['xi-api-key']).toBe(`fixture-${seq}`);
|
||||
});
|
||||
|
||||
it('rejects Replicate pagination that would forward credentials to another host', async () => {
|
||||
body = {
|
||||
results: [{ owner: 'vendor', name: 'model' }],
|
||||
next: 'https://other.example/models',
|
||||
};
|
||||
await service('replicate-image-generation').scan(ctx());
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(alerts.at(-1)?.message).toBe(
|
||||
'AI provider model catalog fetch failed',
|
||||
);
|
||||
});
|
||||
|
||||
it('does not query dynamically refreshed providers or disabled credentials', async () => {
|
||||
await service('openrouter').scan(ctx());
|
||||
await service('openai', { enabled: false }).scan(ctx());
|
||||
expect(requests).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('stops before I/O after lease loss', async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await expect(
|
||||
service().scan({ ...ctx(), signal: controller.signal }),
|
||||
).rejects.toThrow();
|
||||
expect(requests).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('treats credential rotation as a new baseline', async () => {
|
||||
await service().scan(ctx());
|
||||
body = { data: [{ id: 'different-account' }] };
|
||||
await service().scan(ctx());
|
||||
expect(alerts).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('rejects a looping page cursor without replacing the baseline', async () => {
|
||||
body = { data: [{ id: 'one' }], has_more: true, last_id: 'one' };
|
||||
await service('claude').scan(ctx());
|
||||
expect(requests).toHaveLength(2);
|
||||
expect(alerts.at(-1)?.message).toBe(
|
||||
'AI provider model catalog fetch failed',
|
||||
);
|
||||
});
|
||||
|
||||
it('caps pagination rather than treating a truncated listing as complete', async () => {
|
||||
let page = 0;
|
||||
responder = () => ({
|
||||
data: [{ id: `m-${++page}` }],
|
||||
has_more: true,
|
||||
last_id: `m-${page}`,
|
||||
});
|
||||
await service('claude').scan(ctx());
|
||||
expect(requests).toHaveLength(100);
|
||||
expect(alerts.at(-1)?.message).toBe(
|
||||
'AI provider model catalog fetch failed',
|
||||
);
|
||||
});
|
||||
|
||||
it('isolates a failing provider from a successful provider', async () => {
|
||||
const monitor = new AIModelMonitorService(
|
||||
{
|
||||
providers: {
|
||||
openai: {
|
||||
apiKey: `failure-${++seq}`,
|
||||
apiBaseUrl: `${origin}/broken`,
|
||||
},
|
||||
groq: { apiKey: `success-${seq}`, apiBaseUrl: origin },
|
||||
},
|
||||
} as IConfig,
|
||||
backend.clients,
|
||||
backend.stores,
|
||||
backend.services,
|
||||
);
|
||||
responder = (url) =>
|
||||
url.startsWith('/broken') ? { error: 'upstream' } : body;
|
||||
await monitor.scan(ctx());
|
||||
body = { data: [{ id: 'kept' }, { id: 'new' }] };
|
||||
await monitor.scan(ctx());
|
||||
expect(
|
||||
alerts.filter((alert) => alert.message === 'AI provider model added'),
|
||||
).toHaveLength(1);
|
||||
expect(
|
||||
alerts.filter((alert) => alert.message === 'AI provider model removed'),
|
||||
).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('paginates the native Gemini catalog using API key headers', async () => {
|
||||
const get = vi
|
||||
.spyOn(axios, 'get')
|
||||
.mockResolvedValueOnce({
|
||||
data: {
|
||||
models: [{ name: 'models/first' }],
|
||||
nextPageToken: 'second',
|
||||
},
|
||||
})
|
||||
.mockResolvedValueOnce({ data: { models: [{ name: 'models/last' }] } });
|
||||
try {
|
||||
const monitor = new AIModelMonitorService(
|
||||
{ providers: { gemini: { apiKey: `google-${++seq}` } } } as IConfig,
|
||||
backend.clients,
|
||||
backend.stores,
|
||||
backend.services,
|
||||
);
|
||||
await monitor.scan(ctx());
|
||||
expect(get).toHaveBeenCalledTimes(2);
|
||||
expect(get.mock.calls[1][0]).toBe(
|
||||
'https://generativelanguage.googleapis.com/v1beta/models?pageToken=second',
|
||||
);
|
||||
expect(get.mock.calls[0][1]?.headers).toEqual({
|
||||
'x-goog-api-key': `google-${seq}`,
|
||||
});
|
||||
expect(alerts).toHaveLength(0);
|
||||
} finally {
|
||||
get.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('registers a fleet job at boot without monitor configuration', async () => {
|
||||
class InspectJobs extends JobScheduler {
|
||||
definition(name: string) {
|
||||
return this.definitionOf(name);
|
||||
}
|
||||
}
|
||||
const config = {
|
||||
providers: {},
|
||||
} as IConfig;
|
||||
const jobs = new InspectJobs(
|
||||
config,
|
||||
backend.clients,
|
||||
backend.stores,
|
||||
backend.services,
|
||||
);
|
||||
const monitor = new AIModelMonitorService(
|
||||
config,
|
||||
backend.clients,
|
||||
backend.stores,
|
||||
{ ...backend.services, jobs },
|
||||
);
|
||||
monitor.onServerStart();
|
||||
const job = jobs.definition('ai-model-monitor');
|
||||
expect(job.every).toBe(30 * 60_000);
|
||||
expect(job.scope).toBe('fleet');
|
||||
await job.run(ctx());
|
||||
expect(requests).toHaveLength(0);
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await expect(
|
||||
job.run({ ...ctx(), signal: controller.signal }),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ data: [{ id: 'm'.repeat(257) }] },
|
||||
{ data: Array.from({ length: 20_001 }, (_, i) => ({ id: `m-${i}` })) },
|
||||
{
|
||||
data: Array.from({ length: 2_000 }, (_, i) => ({
|
||||
id: `${'m'.repeat(200)}-${i}`,
|
||||
})),
|
||||
},
|
||||
])(
|
||||
'rejects catalog bounds without emitting model changes',
|
||||
async (oversized) => {
|
||||
body = oversized;
|
||||
await service().scan(ctx());
|
||||
expect(alerts).toHaveLength(1);
|
||||
expect(alerts[0].message).toBe(
|
||||
'AI provider model catalog fetch failed',
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it('follows same-origin Replicate pages and reads owner/name identifiers', async () => {
|
||||
responder = (url) =>
|
||||
url.includes('cursor=two')
|
||||
? { results: [{ owner: 'vendor', name: 'two' }], next: null }
|
||||
: {
|
||||
results: [{ owner: 'vendor', name: 'one' }],
|
||||
next: `${origin}/models?cursor=two`,
|
||||
};
|
||||
await service('replicate-image-generation').scan(ctx());
|
||||
expect(requests).toHaveLength(2);
|
||||
expect(alerts).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('diffs bogus models across reordered, changed, failed, and recovered catalogs', async () => {
|
||||
const alarm = new AlarmClient({} as IConfig);
|
||||
alarm.addAlertHandler(async (alert) => {
|
||||
alerts.push(alert);
|
||||
});
|
||||
const monitor = new AIModelMonitorService(
|
||||
{
|
||||
providers: {
|
||||
openai: { apiKey: `bogus-${++seq}`, apiBaseUrl: origin },
|
||||
},
|
||||
} as IConfig,
|
||||
{ ...backend.clients, alarm },
|
||||
backend.stores,
|
||||
backend.services,
|
||||
);
|
||||
body = { data: [{ id: 'bogus-stays' }, { id: 'bogus-retired' }] };
|
||||
await monitor.scan(ctx());
|
||||
expect(alerts).toHaveLength(0);
|
||||
|
||||
body = {
|
||||
data: [
|
||||
{ id: 'bogus-retired' },
|
||||
{ id: 'bogus-stays' },
|
||||
{ id: 'bogus-stays' },
|
||||
],
|
||||
};
|
||||
await monitor.scan(ctx());
|
||||
expect(alerts).toHaveLength(0);
|
||||
|
||||
body = { data: [{ id: 'bogus-new' }, { id: 'bogus-stays' }] };
|
||||
await monitor.scan(ctx());
|
||||
expect(
|
||||
alerts.map((alert) => ({
|
||||
change: alert.fields.change,
|
||||
model: alert.fields.model,
|
||||
channel: alert.channel,
|
||||
})),
|
||||
).toEqual([
|
||||
{ change: "'added'", model: "'bogus-new'", channel: 'ai_providers' },
|
||||
{
|
||||
change: "'removed'",
|
||||
model: "'bogus-retired'",
|
||||
channel: 'ai_providers',
|
||||
},
|
||||
]);
|
||||
|
||||
await monitor.scan(ctx());
|
||||
expect(alerts).toHaveLength(2);
|
||||
|
||||
status = 503;
|
||||
body = { error: 'bogus provider is offline' };
|
||||
await monitor.scan(ctx());
|
||||
expect(alerts).toHaveLength(3);
|
||||
expect(alerts[2].message).toBe('AI provider model catalog fetch failed');
|
||||
|
||||
status = 200;
|
||||
body = { data: [{ id: 'bogus-stays' }] };
|
||||
await monitor.scan(ctx());
|
||||
expect(alerts).toHaveLength(4);
|
||||
expect(alerts[3].fields.change).toBe("'removed'");
|
||||
expect(alerts[3].fields.model).toBe("'bogus-new'");
|
||||
expect(requests).toHaveLength(6);
|
||||
});
|
||||
|
||||
it.each(['read', 'write'] as const)(
|
||||
'does not emit model changes when a snapshot %s fails and recovers without replaying alerts',
|
||||
async (operation) => {
|
||||
const alarm = new AlarmClient({} as IConfig);
|
||||
alarm.addAlertHandler(async (alert) => {
|
||||
alerts.push(alert);
|
||||
});
|
||||
const monitor = new AIModelMonitorService(
|
||||
{
|
||||
providers: {
|
||||
openai: {
|
||||
apiKey: `kv-failure-${++seq}`,
|
||||
apiBaseUrl: origin,
|
||||
},
|
||||
},
|
||||
} as IConfig,
|
||||
{ ...backend.clients, alarm },
|
||||
backend.stores,
|
||||
backend.services,
|
||||
);
|
||||
await monitor.scan(ctx());
|
||||
expect(alerts).toHaveLength(0);
|
||||
body = { data: [{ id: 'kept' }, { id: 'new' }] };
|
||||
const failure = vi
|
||||
.spyOn(backend.clients.dynamo, operation === 'read' ? 'get' : 'put')
|
||||
.mockRejectedValueOnce(
|
||||
new Error('Injected storage failure with internal details'),
|
||||
);
|
||||
try {
|
||||
await monitor.scan(ctx());
|
||||
} finally {
|
||||
failure.mockRestore();
|
||||
}
|
||||
expect(alerts).toHaveLength(1);
|
||||
expect(alerts[0].message).toBe(
|
||||
'AI provider model catalog snapshot failed',
|
||||
);
|
||||
expect(alerts[0].fields.operation).toBe(`'${operation}'`);
|
||||
expect(alerts[0].channel).toBe('ai_providers');
|
||||
expect(JSON.stringify(alerts)).not.toContain('internal details');
|
||||
const { res } = await backend.stores.kv.get(
|
||||
{ key: 'openai', consistentRead: true },
|
||||
{ systemPartition: 'aiModelMonitor' },
|
||||
);
|
||||
expect((res as { models: string[] }).models).toEqual(['kept', 'old']);
|
||||
await monitor.scan(ctx());
|
||||
expect(alerts.map((alert) => alert.message)).toEqual([
|
||||
'AI provider model catalog snapshot failed',
|
||||
'AI provider model added',
|
||||
'AI provider model removed',
|
||||
]);
|
||||
await monitor.scan(ctx());
|
||||
expect(alerts).toHaveLength(3);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,317 @@
|
||||
import axios from 'axios';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { extension } from '@heyputer/backend/src/extensions';
|
||||
import { PuterService } from '@heyputer/backend/src/services/types.js';
|
||||
import type { JobRunContext } from '@heyputer/backend/src/services/jobs/JobScheduler.js';
|
||||
import { readProviderKey } from '@heyputer/backend/src/util/aiProviderKey.js';
|
||||
import { runWithConcurrencyLimit } from '@heyputer/backend/src/util/concurrency.js';
|
||||
|
||||
const EVERY_MS = 30 * 60_000;
|
||||
const MAX_PAGES = 100;
|
||||
const MAX_MODELS = 20_000;
|
||||
|
||||
type Format = 'openai' | 'claude' | 'gemini' | 'elevenlabs' | 'replicate';
|
||||
interface ModelEndpoint {
|
||||
provider: string;
|
||||
configKeys: string[];
|
||||
baseUrl: string;
|
||||
format?: Format;
|
||||
}
|
||||
|
||||
const ENDPOINTS: ModelEndpoint[] = [
|
||||
{
|
||||
provider: 'openai',
|
||||
configKeys: [
|
||||
'openai-completion',
|
||||
'openai',
|
||||
'openai-tts',
|
||||
'openai-image-generation',
|
||||
'openai-speech-to-text',
|
||||
],
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
},
|
||||
{ provider: 'azure', configKeys: ['azure-openai'], baseUrl: '' },
|
||||
{
|
||||
provider: 'claude',
|
||||
configKeys: ['claude'],
|
||||
baseUrl: 'https://api.anthropic.com/v1',
|
||||
format: 'claude',
|
||||
},
|
||||
{
|
||||
provider: 'gemini',
|
||||
configKeys: [
|
||||
'gemini',
|
||||
'gemini-image-generation',
|
||||
'gemini-video-generation',
|
||||
'gemini-tts',
|
||||
],
|
||||
baseUrl: 'https://generativelanguage.googleapis.com/v1beta',
|
||||
format: 'gemini',
|
||||
},
|
||||
{
|
||||
provider: 'groq',
|
||||
configKeys: ['groq'],
|
||||
baseUrl: 'https://api.groq.com/openai/v1',
|
||||
},
|
||||
{
|
||||
provider: 'deepseek',
|
||||
configKeys: ['deepseek'],
|
||||
baseUrl: 'https://api.deepseek.com',
|
||||
},
|
||||
{
|
||||
provider: 'mistral',
|
||||
configKeys: ['mistral'],
|
||||
baseUrl: 'https://api.mistral.ai/v1',
|
||||
},
|
||||
{
|
||||
provider: 'moonshot',
|
||||
configKeys: ['moonshot'],
|
||||
baseUrl: 'https://api.moonshot.ai/v1',
|
||||
},
|
||||
{
|
||||
provider: 'minimax',
|
||||
configKeys: ['minimax', 'minimax-video-generation'],
|
||||
baseUrl: 'https://api.minimax.io/v1',
|
||||
},
|
||||
{
|
||||
provider: 'zai',
|
||||
configKeys: ['zai'],
|
||||
baseUrl: 'https://api.z.ai/api/paas/v4',
|
||||
},
|
||||
{
|
||||
provider: 'byteplus',
|
||||
configKeys: ['byteplus'],
|
||||
baseUrl: 'https://ark.ap-southeast.bytepluses.com/api/v3',
|
||||
},
|
||||
{
|
||||
provider: 'hoonify',
|
||||
configKeys: ['hoonify'],
|
||||
baseUrl: 'https://api.hoonify.ai/v1',
|
||||
},
|
||||
{
|
||||
provider: 'meta',
|
||||
configKeys: ['meta'],
|
||||
baseUrl: 'https://api.meta.ai/v1',
|
||||
},
|
||||
{
|
||||
provider: 'elevenlabs',
|
||||
configKeys: ['elevenlabs'],
|
||||
baseUrl: 'https://api.elevenlabs.io/v1',
|
||||
format: 'elevenlabs',
|
||||
},
|
||||
{
|
||||
provider: 'replicate',
|
||||
configKeys: ['replicate-image-generation'],
|
||||
baseUrl: 'https://api.replicate.com/v1',
|
||||
format: 'replicate',
|
||||
},
|
||||
];
|
||||
|
||||
interface Snapshot {
|
||||
source: string;
|
||||
models: string[];
|
||||
}
|
||||
|
||||
export class AIModelMonitorService extends PuterService {
|
||||
override onServerStart(): void {
|
||||
this.services.jobs.register('ai-model-monitor', {
|
||||
every: EVERY_MS,
|
||||
scope: 'fleet',
|
||||
run: (ctx) => this.scan(ctx),
|
||||
});
|
||||
}
|
||||
|
||||
async scan({ signal }: JobRunContext): Promise<void> {
|
||||
const targets = ENDPOINTS.flatMap((endpoint) =>
|
||||
endpoint.configKeys.map((configKey) => ({
|
||||
...endpoint,
|
||||
configKey,
|
||||
})),
|
||||
);
|
||||
await runWithConcurrencyLimit(targets, 4, async (endpoint) => {
|
||||
signal.throwIfAborted();
|
||||
const config = this.config.providers[endpoint.configKey];
|
||||
const apiKey = readProviderKey(config);
|
||||
if (!apiKey || config?.enabled === false) return;
|
||||
const baseUrl =
|
||||
config?.apiURL ?? config?.apiBaseUrl ?? endpoint.baseUrl;
|
||||
if (!baseUrl) return;
|
||||
const format =
|
||||
endpoint.format === 'gemini' && config?.apiBaseUrl
|
||||
? 'openai'
|
||||
: (endpoint.format ?? 'openai');
|
||||
const url = `${baseUrl.replace(/\/$/, '')}/models`;
|
||||
const source = createHash('sha256')
|
||||
.update(url)
|
||||
.update(apiKey)
|
||||
.digest('hex');
|
||||
const key = endpoint.configKey;
|
||||
const opts = { systemPartition: 'aiModelMonitor' };
|
||||
let operation: 'readSnapshot' | 'fetch' | 'writeSnapshot' =
|
||||
'readSnapshot';
|
||||
let old: Snapshot | null;
|
||||
let models: string[];
|
||||
try {
|
||||
const [stored, catalog] = await Promise.allSettled([
|
||||
this.stores.kv.get({ key, consistentRead: true }, opts),
|
||||
fetchModels(url, apiKey, format, signal),
|
||||
]);
|
||||
signal.throwIfAborted();
|
||||
if (stored.status === 'rejected') throw stored.reason;
|
||||
old = stored.value.res as Snapshot | null;
|
||||
operation = 'fetch';
|
||||
if (catalog.status === 'rejected') throw catalog.reason;
|
||||
models = catalog.value;
|
||||
const snapshot = { source, models };
|
||||
if (Buffer.byteLength(JSON.stringify(snapshot)) > 350 * 1024)
|
||||
throw new Error('Model snapshot too large');
|
||||
operation = 'writeSnapshot';
|
||||
// Persist before notifying so a rejected write cannot replay a change.
|
||||
await this.stores.kv.set({ key, value: snapshot }, opts);
|
||||
} catch {
|
||||
signal.throwIfAborted();
|
||||
// Upstream and storage errors can embed private response details.
|
||||
const fetchFailed = operation === 'fetch';
|
||||
this.clients.alarm.create(
|
||||
fetchFailed
|
||||
? `ai_model_catalog_fetch_failed:${endpoint.provider}`
|
||||
: `ai_model_catalog_snapshot_failed:${endpoint.provider}:${key}`,
|
||||
fetchFailed
|
||||
? 'AI provider model catalog fetch failed'
|
||||
: 'AI provider model catalog snapshot failed',
|
||||
{
|
||||
provider: endpoint.provider,
|
||||
configKey: key,
|
||||
...(!fetchFailed
|
||||
? {
|
||||
operation:
|
||||
operation === 'readSnapshot'
|
||||
? 'read'
|
||||
: 'write',
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
'info',
|
||||
{ channel: 'ai_providers' },
|
||||
);
|
||||
return;
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
if (old?.source === source) {
|
||||
const transition = createHash('sha256')
|
||||
.update(JSON.stringify([source, old.models, models]))
|
||||
.digest('hex');
|
||||
const before = new Set(old.models);
|
||||
const after = new Set(models);
|
||||
for (const [change, ids] of [
|
||||
['added', models.filter((id) => !before.has(id))],
|
||||
['removed', old.models.filter((id) => !after.has(id))],
|
||||
] as const) {
|
||||
for (const model of ids) {
|
||||
const signature = createHash('sha256')
|
||||
.update(JSON.stringify([transition, change, model]))
|
||||
.digest('hex');
|
||||
this.clients.alarm.create(
|
||||
`ai_model_catalog_change:${endpoint.provider}:${signature}`,
|
||||
`AI provider model ${change}`,
|
||||
{
|
||||
provider: endpoint.provider,
|
||||
configKey: key,
|
||||
model,
|
||||
change,
|
||||
},
|
||||
'info',
|
||||
{ channel: 'ai_providers' },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
signal.throwIfAborted();
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchModels(
|
||||
startUrl: string,
|
||||
apiKey: string,
|
||||
format: Format,
|
||||
signal: AbortSignal,
|
||||
): Promise<string[]> {
|
||||
const headers: Record<string, string> =
|
||||
format === 'claude'
|
||||
? { 'x-api-key': apiKey, 'anthropic-version': '2023-06-01' }
|
||||
: format === 'gemini'
|
||||
? { 'x-goog-api-key': apiKey }
|
||||
: format === 'elevenlabs'
|
||||
? { 'xi-api-key': apiKey }
|
||||
: { Authorization: `Bearer ${apiKey}` };
|
||||
let url = new URL(startUrl);
|
||||
const visited = new Set<string>();
|
||||
const models = new Set<string>();
|
||||
for (let page = 0; page < MAX_PAGES; page++) {
|
||||
if (visited.has(url.href))
|
||||
throw new Error('Repeated model catalog page');
|
||||
visited.add(url.href);
|
||||
const { data: body } = await axios.get(url.href, {
|
||||
headers,
|
||||
signal,
|
||||
timeout: 15_000,
|
||||
maxContentLength: 8 * 1024 * 1024,
|
||||
maxRedirects: 0,
|
||||
});
|
||||
const rows =
|
||||
format === 'elevenlabs'
|
||||
? body
|
||||
: format === 'gemini'
|
||||
? body.models
|
||||
: format === 'replicate'
|
||||
? body.results
|
||||
: body.data;
|
||||
if (!Array.isArray(rows)) throw new Error('Invalid model catalog');
|
||||
for (const row of rows) {
|
||||
const id =
|
||||
format === 'elevenlabs'
|
||||
? row?.model_id
|
||||
: format === 'gemini'
|
||||
? row?.name
|
||||
: format === 'replicate'
|
||||
? row?.owner && row?.name
|
||||
? `${row.owner}/${row.name}`
|
||||
: undefined
|
||||
: row?.id;
|
||||
if (typeof id !== 'string' || !id || id.length > 256)
|
||||
throw new Error('Invalid model id');
|
||||
models.add(id);
|
||||
if (models.size > MAX_MODELS)
|
||||
throw new Error('Model catalog too large');
|
||||
}
|
||||
let next: URL | undefined;
|
||||
if (body.has_more === true) {
|
||||
if (typeof body.last_id !== 'string' || !body.last_id)
|
||||
throw new Error('Missing model cursor');
|
||||
next = new URL(url);
|
||||
next.searchParams.set('after_id', body.last_id);
|
||||
} else if (format === 'gemini' && body.nextPageToken) {
|
||||
if (typeof body.nextPageToken !== 'string')
|
||||
throw new Error('Invalid model cursor');
|
||||
next = new URL(url);
|
||||
next.searchParams.set('pageToken', body.nextPageToken);
|
||||
} else if (format === 'replicate' && body.next) {
|
||||
if (typeof body.next !== 'string')
|
||||
throw new Error('Invalid model cursor');
|
||||
next = new URL(body.next, url);
|
||||
}
|
||||
if (!next) return [...models].sort();
|
||||
if (
|
||||
next.origin !== url.origin ||
|
||||
next.pathname !== url.pathname ||
|
||||
next.username ||
|
||||
next.password
|
||||
)
|
||||
throw new Error('Invalid model page URL');
|
||||
url = next;
|
||||
}
|
||||
throw new Error('Incomplete model catalog');
|
||||
}
|
||||
|
||||
extension.registerService('aiModelMonitor', AIModelMonitorService);
|
||||
Reference in new issue
Block a user