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