Open History to see the last commit
1/**
2 * Replicate — public OpenAPI at api.replicate.com/openapi.json.
3 * Generation is POST /predictions (and official model run paths).
4 * listModels walks the paginated public catalog; requires REPLICATE_API_TOKEN.
5 *
6 * Every listed model carries its own request schema
7 * (`latest_version.openapi_schema`). A language model is read off that
8 * schema, never off its name, and its chat facts come from the same place.
9 * Official language models also get their run route synced with that schema
10 * as the `input` object.
11 */
12import type { Activity } from '#/db/schema.ts'
13import { contentHash } from '#/server/kv.ts'
14import { walkRequestSchema } from '../fact-sources.ts'
15import { cachedDocs, mapConcurrent } from '../model-facts.ts'
16import { isoToEpochSeconds } from '../release-dates.ts'
17import {
18 fetchJson,
19 fetchOpenApi,
20 fetchText,
21 sha256Text,
22 skippedResult,
23} from '../types.ts'
24import {
25 BILLING_MARKER,
26 compileReplicateBilling,
27 replicateBillingFromHtml,
28} from '../replicate-pricing.ts'
29import { replicateReadmeFacts } from '../replicate-readme.ts'
30import type { ReplicateBilling } from '../replicate-pricing.ts'
31import type {
32 FactSource,
33 ListModelsResult,
34 ModelFactSources,
35 ModelInfo,
36 ModelReasoning,
37 OpenApiDocument,
38 OpenApiOperation,
39 ProviderConfig,
40 ProviderSecrets,
41 SpecFetchResult,
42} from '../types.ts'
43
44const REPLICATE_OPENAPI_URL = 'https://api.replicate.com/openapi.json'
45const REPLICATE_MODELS_URL = 'https://api.replicate.com/v1/models'
46
47/** Public catalog is huge; stay inside the Worker subrequest budget. */
48const MAX_MODEL_PAGES = 20
49const FETCH_TIMEOUT_MS = 20_000
50
51/** The run route the spec documents for official models. */
52const OFFICIAL_RUN_PATH = '/models/{model_owner}/{model_name}/predictions'
53/** Set on the per-model routes fetchSpec adds; classify reads it back. */
54const ACTIVITY_MARKER = 'x-modelschemas-replicate-activity'
55const INPUT_POINTER = '/latest_version/openapi_schema/components/schemas/Input'
56const SCHEMA_REF = '#/components/schemas/'
57
58const PROMPT_FIELDS = ['prompt', 'messages', 'message']
59const MAX_TOKENS_FIELD = /^max_(?:new_|completion_|output_)?tokens$/
60
61function stripV1(path: string): string {
62 return path.startsWith('/v1/') ? path.slice(3) : path
63}
64
65/**
66 * Official-model slugs refine the activity. Generic prediction creates
67 * (`/predictions`, templated `/models/{owner}/{name}/predictions`) default
68 * to image — Replicate's core generation surface.
69 */
70function activityFromHaystack(
71 haystack: string,
72 allowChat = true,
73): Activity | null {
74 const hay = haystack.toLowerCase()
75 if (
76 /text-to-video|image-to-video|video-to-video|stable-video|hunyuan-video|wan-video|ltx-video|cogvideo|animate-?diff|hailuo|kling|pixverse|runway|mochi-1|luma\/|\/veo|veo-\d|video-01|\/video-/.test(
77 hay,
78 )
79 ) {
80 return 'video'
81 }
82 if (
83 /whisper|musicgen|audiogen|riffusion|text-to-speech|speech-to-text|text-to-audio|xtts|zonos|kokoro|chatterbox|\bbark\b|styletts|stable-audio|audio-ldm|mmaudio|ace-step|orpheus|\btts\b|voice-clone/.test(
84 hay,
85 )
86 ) {
87 return 'audio'
88 }
89 if (
90 allowChat &&
91 /llama|mistral|mixtral|qwen|gemma|deepseek|gpt-oss|phi-[34]|dbrx|nemotron|granite|arctic|\byi-|vicuna|wizardlm|zephyr|command-r|\bllm\b|instruct|\bchat\b/.test(
92 hay,
93 )
94 ) {
95 return 'chat'
96 }
97 if (
98 /flux|sdxl|stable-diffusion|\bsd3\b|imagen|ideogram|recraft|playground|auraflow|hidream|seedream|esrgan|upscale|controlnet|pulid|text-to-image|image-to-image/.test(
99 hay,
100 )
101 ) {
102 return 'image'
103 }
104 return null
105}
106
107/** POST /predictions and POST /models/{owner}/{name}/predictions only. */
108function isGenerationCreate(path: string): boolean {
109 const bare = stripV1(path)
110 if (bare === '/predictions') return true
111 return /^\/models\/[^/]+\/[^/]+\/predictions$/.test(bare)
112}
113
114function classify(path: string, op: OpenApiOperation): Activity | null {
115 if (op[ACTIVITY_MARKER] === 'chat') return 'chat'
116 if (!isGenerationCreate(path)) return null
117 return activityFromHaystack(path) ?? 'image'
118}
119
120type Json = Record<string, unknown>
121
122function isRecord(value: unknown): value is Json {
123 return typeof value === 'object' && value !== null && !Array.isArray(value)
124}
125
126export interface ReplicateModel {
127 owner?: string
128 name?: string
129 description?: string | null
130 visibility?: string
131 created_at?: string
132 is_official?: boolean
133 latest_version?: {
134 created_at?: string
135 /** The model's own request and response schema (Cog). */
136 openapi_schema?: { components?: { schemas?: unknown } }
137 }
138 /** Present when the models API includes the prediction price. */
139 billing_config?: ReplicateBilling | null
140 billingConfig?: ReplicateBilling | null
141}
142
143interface ReplicateModelPage {
144 next?: string | null
145 results?: Array<ReplicateModel>
146}
147
148function isSafeModelsUrl(url: string): boolean {
149 try {
150 const parsed = new URL(url)
151 return (
152 parsed.protocol === 'https:' &&
153 parsed.hostname === 'api.replicate.com' &&
154 parsed.pathname.startsWith('/v1/models')
155 )
156 } catch {
157 return false
158 }
159}
160
161function modelSchemas(model: ReplicateModel): Json | null {
162 const schemas = model.latest_version?.openapi_schema?.components?.schemas
163 return isRecord(schemas) ? schemas : null
164}
165
166/** Cog writes an enum field as `allOf: [{ $ref }]`. */
167function deref(schemas: Json, node: unknown): Json | null {
168 if (!isRecord(node)) return null
169 const only =
170 Array.isArray(node.allOf) && node.allOf.length === 1
171 ? (node.allOf[0] as unknown)
172 : node
173 if (!isRecord(only)) return null
174 if (typeof only.$ref !== 'string') return only
175 const target = schemas[only.$ref.replace(SCHEMA_REF, '')]
176 return isRecord(target) ? target : null
177}
178
179function isText(node: unknown): boolean {
180 return isRecord(node) && node.type === 'string' && node.format === undefined
181}
182
183/**
184 * Input properties of a language model, null for anything else. The model's
185 * schema decides: it returns text, takes a prompt, and caps output tokens.
186 * A name like `qwen-image` says nothing about what a model returns.
187 */
188function chatInputProperties(model: ReplicateModel): Json | null {
189 const schemas = modelSchemas(model)
190 const output = schemas?.Output
191 const input = schemas?.Input
192 if (!isRecord(output) || !isRecord(input) || !isRecord(input.properties)) {
193 return null
194 }
195 if (!isText(output) && !(output.type === 'array' && isText(output.items))) {
196 return null
197 }
198 const names = Object.keys(input.properties)
199 if (!PROMPT_FIELDS.some((name) => names.includes(name))) return null
200 if (!names.some((name) => MAX_TOKENS_FIELD.test(name))) return null
201 return input.properties
202}
203
204/** A number or a switch (`video_fps`, `max_image_resolution`) carries no media. */
205function isScalarSetting(node: unknown): boolean {
206 return (
207 isRecord(node) &&
208 ['integer', 'number', 'boolean'].includes(String(node.type))
209 )
210}
211
212const MEDIA_NOUN = { image: 'images?', audio: 'audio', video: 'videos?' }
213
214/**
215 * A string the schema names for a medium and describes as that medium
216 * (`image_input`: "List of images to send"). No `format: uri`, but
217 * text-only would be a wrong claim and the description states the medium.
218 */
219function describedMedium(
220 node: unknown,
221 kind: keyof typeof MEDIA_NOUN,
222): boolean {
223 if (!isRecord(node)) return false
224 const items = isRecord(node.items) ? node.items.type : undefined
225 const textual =
226 node.type === 'string' || (node.type === 'array' && items === 'string')
227 if (!textual || typeof node.description !== 'string') return false
228 const noun = MEDIA_NOUN[kind]
229 return (
230 new RegExp(`\\b${noun}\\b`, 'i').test(node.description) &&
231 /\b(send|input|include|upload)\b/i.test(node.description)
232 )
233}
234
235/**
236 * `text` plus one modality per file input. The whole fact is unstated when
237 * a file input's name does not say what it carries, or when an input named
238 * for a medium is neither a file nor described as that medium.
239 */
240function inputModalities(properties: Json): Array<string> | null {
241 const media = ['image', 'audio', 'video'] as const
242 const found = new Set<string>()
243 for (const [name, node] of Object.entries(properties)) {
244 const file = JSON.stringify(node).includes('"format":"uri"')
245 const kind = media.find((word) => name.includes(word))
246 if (!file && (!kind || isScalarSetting(node))) continue
247 if (file && kind) {
248 found.add(kind)
249 continue
250 }
251 if (kind && describedMedium(node, kind)) {
252 found.add(kind)
253 continue
254 }
255 return null
256 }
257 // Fixed order: a reordered schema must not read as a changed model.
258 return ['text', ...media.filter((kind) => found.has(kind))]
259}
260
261/**
262 * The stated maximum of the output-token field. Null when the schema states
263 * none, or when two such fields disagree. The maximum is that field's cap,
264 * including one above 128k (Llama 4 states 131072 on `max_tokens`).
265 */
266function maxOutputField(
267 properties: Json,
268): { name: string; maximum: number } | null {
269 const fields = Object.keys(properties).filter((name) =>
270 MAX_TOKENS_FIELD.test(name),
271 )
272 const maxima = new Set(
273 fields.map((name) => {
274 const node = properties[name]
275 return isRecord(node) ? node.maximum : undefined
276 }),
277 )
278 const [name] = fields
279 const [maximum] = [...maxima]
280 if (!name || maxima.size !== 1) return null
281 if (typeof maximum !== 'number' || !Number.isInteger(maximum)) return null
282 return maximum > 0 ? { name, maximum } : null
283}
284
285/** The names Replicate models give a level field. A model has at most one. */
286const EFFORT_FIELDS = [
287 'reasoning_effort',
288 'thinking_level',
289 'effort',
290 'thinking',
291]
292
293/** Values of a field named `thinking` that make it a switch, not a level. */
294const SWITCH_VALUES = ['enabled', 'disabled', 'true', 'false', 'on', 'off']
295
296/** A description naming the level that turns thinking off, in group 1 or 2. */
297const STATED_OFF = /'([^']+)' disables thinking|\b[Uu]se '([^']+)' to disable\b/
298
299/**
300 * The model's own thinking control, read off its Input schema; null when it
301 * has none this can read. Every schema here is one model's own.
302 *
303 * - A level enum is `effort`. `mandatory` is false when the description
304 * says a level turns thinking off ("'low' disables thinking", "Use 'none'
305 * to disable"), or when `reasoning_effort` accepts `none`. Otherwise it is
306 * unstated. On any other field a `none` that is the default is "unset",
307 * not a level ("leave as None for default behavior"): it is left out.
308 * - An integer `thinking_budget` is `budget`; "0 to disable thinking" in its
309 * description says it can be turned off.
310 * - A boolean `enable_thinking` and nothing else is a `toggle` with an off
311 * position.
312 */
313function reasoningField(
314 schemas: Json,
315 properties: Json,
316): { name: string; reasoning: ModelReasoning } | null {
317 const names = EFFORT_FIELDS.filter((field) => field in properties)
318 const [name] = names
319 if (names.length > 1) return null
320 if (name !== undefined) {
321 const field = properties[name]
322 const values = deref(schemas, field)?.enum
323 if (!Array.isArray(values)) return null
324 const listed = values.filter((value) => typeof value === 'string')
325 if (listed.length !== values.length) return null
326 if (listed.some((value) => SWITCH_VALUES.includes(value))) return null
327 const described = isRecord(field) ? field.description : undefined
328 const description = typeof described === 'string' ? described : ''
329 const stated = description.match(STATED_OFF)
330 const off = listed.includes(stated?.[1] ?? stated?.[2] ?? '')
331 if (off || (name === 'reasoning_effort' && listed.includes('none'))) {
332 return {
333 name,
334 reasoning: { mode: 'effort', mandatory: false, efforts: listed },
335 }
336 }
337 const unset = isRecord(field) ? field.default : undefined
338 const efforts = listed.filter(
339 (value) => !(value === unset && value.toLowerCase() === 'none'),
340 )
341 if (efforts.length === 0) return null
342 return { name, reasoning: { mode: 'effort', mandatory: null, efforts } }
343 }
344
345 const budget = properties.thinking_budget
346 if (isRecord(budget)) {
347 if (budget.type !== 'integer') return null
348 const stated =
349 typeof budget.description === 'string' &&
350 /\b0 to disable thinking\b/.test(budget.description)
351 return {
352 name: 'thinking_budget',
353 reasoning: { mode: 'budget', mandatory: stated ? false : null },
354 }
355 }
356
357 const toggle = properties.enable_thinking
358 if (isRecord(toggle) && toggle.type === 'boolean' && !('enum' in toggle)) {
359 return {
360 name: 'enable_thinking',
361 reasoning: { mode: 'toggle', mandatory: false },
362 }
363 }
364 return null
365}
366
367function runPath(owner: string, name: string): string {
368 return `/models/${owner}/${name}/predictions`
369}
370
371type ChatFacts = Pick<
372 ModelInfo,
373 | 'capabilities'
374 | 'modalities'
375 | 'maxOutput'
376 | 'reasoning'
377 | 'schemaEndpointId'
378 | 'factSources'
379>
380
381/**
382 * Chat facts read from one model's own Input schema; null when the model is
383 * not a language model. Schemas are never merged across models.
384 */
385export function replicateChatFacts(model: ReplicateModel): ChatFacts | null {
386 const schemas = modelSchemas(model)
387 const properties = chatInputProperties(model)
388 if (!schemas || !properties || !model.owner || !model.name) return null
389 const sourceUrl = `${REPLICATE_MODELS_URL}/${model.owner}/${model.name}`
390 const source = (pointer: string): FactSource => ({
391 derivation: 'listing',
392 sourceUrl,
393 path: `${INPUT_POINTER}${pointer}`,
394 })
395 const facts: ChatFacts = {}
396 const factSources: ModelFactSources = {}
397
398 const flags =
399 walkRequestSchema(schemas.Input, { derivation: 'listing', endpointId: '' })
400 ?.sources.capabilities ?? {}
401 // Sorted: a reordered schema must not read as a changed model.
402 facts.capabilities =
403 Object.keys(flags).length > 0 ? Object.keys(flags).sort() : null
404 if (facts.capabilities) {
405 factSources.capabilities = Object.fromEntries(
406 Object.entries(flags).map(([flag, at]) => [flag, source(at.path ?? '')]),
407 )
408 }
409
410 const input = inputModalities(properties)
411 if (input) {
412 facts.modalities = { input, output: ['text'] }
413 factSources.modalities = source('/properties')
414 }
415
416 const cap = maxOutputField(properties)
417 if (cap) {
418 facts.maxOutput = cap.maximum
419 factSources.maxOutput = source(`/properties/${cap.name}/maximum`)
420 }
421
422 const control = reasoningField(schemas, properties)
423 if (control) {
424 facts.reasoning = control.reasoning
425 factSources.reasoning = source(`/properties/${control.name}`)
426 }
427
428 // Only official models have a run route of their own. The poller drops
429 // this until the route is synced (`bindSyncedRoutesOnly`).
430 if (model.is_official === true) {
431 facts.schemaEndpointId = runPath(model.owner, model.name).slice(1)
432 }
433 return { ...facts, factSources }
434}
435
436function refName(node: unknown): string | null {
437 if (!isRecord(node) || typeof node.$ref !== 'string') return null
438 return node.$ref.startsWith(SCHEMA_REF)
439 ? node.$ref.slice(SCHEMA_REF.length)
440 : null
441}
442
443function jsonBody(node: unknown): unknown {
444 if (!isRecord(node) || !isRecord(node.content)) return undefined
445 const media = node.content['application/json']
446 return isRecord(media) ? media.schema : undefined
447}
448
449/**
450 * One official language model's run route: the spec's official-model
451 * operation with `input` (and the response's `output`) narrowed to the
452 * model's own schemas. Null when the spec no longer has that shape.
453 */
454export function replicateModelSpec(
455 spec: OpenApiDocument,
456 model: ReplicateModel,
457): OpenApiDocument | null {
458 const operation = spec.paths?.[OFFICIAL_RUN_PATH]?.post
459 const shared = spec.components?.schemas
460 const own = modelSchemas(model)
461 if (!operation || !shared || !own || !model.owner || !model.name) return null
462 const requestName = refName(jsonBody(operation.requestBody))
463 const request = requestName ? shared[requestName] : null
464 if (!requestName || !isRecord(request) || !isRecord(request.properties)) {
465 return null
466 }
467 if (!('input' in request.properties)) return null
468
469 const schemas: Json = {
470 ...shared,
471 ...own,
472 [requestName]: {
473 ...request,
474 properties: {
475 ...request.properties,
476 input: { $ref: `${SCHEMA_REF}Input` },
477 },
478 },
479 }
480 const responses = isRecord(operation.responses) ? operation.responses : {}
481 const responseName = refName(
482 Object.values(responses).map(jsonBody).find(Boolean),
483 )
484 const response = responseName ? shared[responseName] : null
485 if (responseName && isRecord(response) && isRecord(response.properties)) {
486 schemas[responseName] = {
487 ...response,
488 properties: {
489 ...response.properties,
490 output: { $ref: `${SCHEMA_REF}Output` },
491 },
492 }
493 }
494 return {
495 openapi: spec.openapi,
496 paths: {
497 [runPath(model.owner, model.name)]: {
498 post: { ...operation, [ACTIVITY_MARKER]: 'chat' },
499 },
500 },
501 components: { schemas },
502 }
503}
504
505/** The first pages of the public catalog, one entry per `owner/name`. */
506async function listCatalog(key: string): Promise<Array<ReplicateModel>> {
507 const headers = { Authorization: `Bearer ${key}` }
508 const listed = new Map<string, ReplicateModel>()
509 let url: string | null = REPLICATE_MODELS_URL
510 for (let page = 0; url && page < MAX_MODEL_PAGES; page++) {
511 // A short walk would read as routes removed: fail instead.
512 if (!isSafeModelsUrl(url)) {
513 throw new Error(`replicate: unexpected catalog page url ${url}`)
514 }
515 const body = (await fetchJson(url, {
516 headers,
517 signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
518 })) as ReplicateModelPage
519 for (const row of body.results ?? []) {
520 if (!row.owner || !row.name) continue
521 const rawId = `${row.owner}/${row.name}`
522 if (!listed.has(rawId)) listed.set(rawId, row)
523 }
524 url =
525 typeof body.next === 'string' && body.next.length > 0 ? body.next : null
526 }
527 return [...listed.values()]
528}
529
530/**
531 * The public spec, plus one route per official language model in the
532 * catalog. A missing token skips the sync and a failed catalog read fails
533 * it: stale routes are better than half of them.
534 */
535async function fetchSpec(env: ProviderSecrets): Promise<SpecFetchResult> {
536 const key = env.REPLICATE_API_TOKEN
537 if (!key) {
538 return {
539 specs: [],
540 sources: [],
541 outputStrategy: 'post-200',
542 ...skippedResult('replicate', 'REPLICATE_API_TOKEN'),
543 }
544 }
545 const { spec, hash } = await fetchOpenApi(REPLICATE_OPENAPI_URL)
546 const result: SpecFetchResult = {
547 specs: [spec],
548 sources: [{ url: REPLICATE_OPENAPI_URL, hash }],
549 outputStrategy: 'post-200',
550 }
551 const warnings: Array<string> = []
552 for (const model of await listCatalog(key)) {
553 if (!replicateChatFacts(model)?.schemaEndpointId) continue
554 const rawId = `${model.owner}/${model.name}`
555 const document = replicateModelSpec(spec, model)
556 if (!document) {
557 warnings.push(`replicate ${rawId}: no official run route in the spec`)
558 continue
559 }
560 result.specs.push(document)
561 result.sources.push({
562 url: `${REPLICATE_MODELS_URL}/${rawId}`,
563 hash: await contentHash(model.latest_version?.openapi_schema),
564 })
565 }
566 return warnings.length > 0 ? { ...result, warnings } : result
567}
568
569function modelPageUrl(owner: string, name: string): string {
570 return `https://replicate.com/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`
571}
572
573function readmeUrl(owner: string, name: string): string {
574 return `${REPLICATE_MODELS_URL}/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/readme`
575}
576
577function inlineBilling(model: ReplicateModel): ReplicateBilling | null {
578 const raw = model.billing_config ?? model.billingConfig
579 if (!raw || typeof raw !== 'object') return null
580 return raw
581}
582
583/**
584 * Official models publish a prediction price on the model page (the models
585 * list often omits it). A page with no billing config, or a fetch failure,
586 * leaves the row unpriced. Community models are not fetched.
587 */
588async function withPredictionPrice(
589 model: ReplicateModel,
590 info: ModelInfo,
591 kv?: KVNamespace,
592): Promise<ModelInfo> {
593 const owner = model.owner
594 const name = model.name
595 if (!owner || !name) return info
596 const pageUrl = modelPageUrl(owner, name)
597 const inline = inlineBilling(model)
598 if (inline) {
599 const extractedAt = new Date().toISOString()
600 const source = {
601 url: pageUrl,
602 hash: await sha256Text(JSON.stringify(inline)),
603 extractedAt,
604 }
605 const pricing = compileReplicateBilling(inline, source)
606 if (!pricing) return info
607 return {
608 ...info,
609 pricing,
610 factSources: {
611 ...info.factSources,
612 pricing: {
613 derivation: 'docs-derived',
614 sourceUrl: pageUrl,
615 sourceHash: source.hash,
616 path: 'billing_config',
617 },
618 },
619 }
620 }
621 if (model.is_official !== true) return info
622 try {
623 const doc = await cachedDocs(kv, pageUrl, async () => {
624 const html = await fetchText(pageUrl, {
625 signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
626 })
627 // Every official model page embeds this. A 200 without it is an error
628 // or challenge page: throw, so it is neither priced nor cached.
629 if (!html.includes(BILLING_MARKER)) {
630 throw new Error(`replicate: ${pageUrl} has no billing config`)
631 }
632 return {
633 billing: replicateBillingFromHtml(html),
634 hash: await sha256Text(html),
635 extractedAt: new Date().toISOString(),
636 }
637 })
638 const source = {
639 url: pageUrl,
640 hash: doc.hash,
641 extractedAt: doc.extractedAt,
642 }
643 const pricing = compileReplicateBilling(doc.billing, source)
644 if (!pricing) return info
645 return {
646 ...info,
647 pricing,
648 factSources: {
649 ...info.factSources,
650 pricing: {
651 derivation: 'docs-derived',
652 sourceUrl: pageUrl,
653 sourceHash: doc.hash,
654 path: 'billingConfig',
655 },
656 },
657 }
658 } catch {
659 return info
660 }
661}
662
663/**
664 * Context window, and an output cap the schema leaves unset, from the
665 * model's README and listing description. A fetch failure leaves both
666 * null. The schema's own maximum is kept when the README also states one.
667 */
668async function withReadmeFacts(
669 model: ReplicateModel,
670 info: ModelInfo,
671 key: string,
672 kv?: KVNamespace,
673): Promise<ModelInfo> {
674 const owner = model.owner
675 const name = model.name
676 if (info.activity !== 'chat' || !owner || !name) return info
677 const page = readmeUrl(owner, name)
678 let markdown = ''
679 let hash: string | undefined
680 try {
681 const doc = await cachedDocs(kv, page, async () => {
682 const response = await fetch(page, {
683 headers: { Authorization: `Bearer ${key}` },
684 signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
685 })
686 // No README is a fact, not a failed fetch.
687 if (response.status === 404) {
688 return { markdown: '', hash: await sha256Text('') }
689 }
690 if (!response.ok) {
691 throw new Error(
692 `replicate: ${page} → ${String(response.status)} ${response.statusText}`,
693 )
694 }
695 const body = await response.text()
696 const trimmed = body.trimStart()
697 // An error document or the models list is not a README.
698 if (trimmed.startsWith('{') || trimmed.startsWith('<!')) {
699 throw new Error(`replicate: ${page} is not a README`)
700 }
701 return { markdown: body, hash: await sha256Text(body) }
702 })
703 markdown = doc.markdown
704 hash = doc.hash
705 } catch {
706 return info
707 }
708 const facts = replicateReadmeFacts(markdown, model.description ?? '')
709 const factSources = { ...info.factSources }
710 const listing = `${REPLICATE_MODELS_URL}/${owner}/${name}`
711 let changed = false
712 if (
713 info.contextWindow == null &&
714 facts.contextWindow != null &&
715 facts.context
716 ) {
717 info = { ...info, contextWindow: facts.contextWindow }
718 factSources.contextWindow =
719 facts.context.from === 'description'
720 ? { derivation: 'listing', sourceUrl: listing, path: 'description' }
721 : {
722 derivation: 'docs-derived',
723 sourceUrl: page,
724 ...(hash ? { sourceHash: hash } : {}),
725 path: facts.context.path,
726 }
727 changed = true
728 }
729 if (info.maxOutput == null && facts.maxOutput != null && facts.max) {
730 info = { ...info, maxOutput: facts.maxOutput }
731 factSources.maxOutput = {
732 derivation: 'docs-derived',
733 sourceUrl: page,
734 ...(hash ? { sourceHash: hash } : {}),
735 path: facts.max.path,
736 }
737 changed = true
738 }
739 return changed ? { ...info, factSources } : info
740}
741
742function toModelInfo(model: ReplicateModel): ModelInfo | null {
743 if (typeof model.owner !== 'string' || typeof model.name !== 'string') {
744 return null
745 }
746 if (model.owner.length === 0 || model.name.length === 0) return null
747 const rawId = `${model.owner}/${model.name}`
748 const chat = replicateChatFacts(model)
749 return {
750 rawId,
751 displayName: model.name,
752 activity: chat
753 ? 'chat'
754 : activityFromHaystack(`${rawId} ${model.description ?? ''}`, false),
755 releasedAt:
756 isoToEpochSeconds(model.created_at) ??
757 isoToEpochSeconds(model.latest_version?.created_at),
758 providerMetadata: {
759 visibility: model.visibility,
760 official: model.is_official,
761 },
762 // A chat row carries request flags as well.
763 ...chat,
764 }
765}
766
767async function listModels(
768 env: ProviderSecrets,
769 kv?: KVNamespace,
770): Promise<ListModelsResult> {
771 const key = env.REPLICATE_API_TOKEN
772 if (!key) {
773 return { models: [], ...skippedResult('replicate', 'REPLICATE_API_TOKEN') }
774 }
775 const listed = (await listCatalog(key)).flatMap((model) => {
776 const info = toModelInfo(model)
777 return info ? [{ info, model }] : []
778 })
779 return {
780 models: await mapConcurrent(listed, 8, async ({ info, model }) =>
781 withReadmeFacts(
782 model,
783 await withPredictionPrice(model, info, kv),
784 key,
785 kv,
786 ),
787 ),
788 }
789}
790
791export const provider: ProviderConfig = {
792 id: 'replicate',
793 displayName: 'Replicate',
794 authEnvVar: 'REPLICATE_API_TOKEN',
795 specSourceUrl: REPLICATE_OPENAPI_URL,
796 modelsEndpoint: REPLICATE_MODELS_URL,
797 defaultDerivation: 'upstream-spec',
798 bindSyncedRoutesOnly: true,
799 fetchSpec,
800 listModels,
801 classify,
802}