Open History to see the last commit
1/**
2 * Lovable AI Gateway — the keyless `GET /v1/models` listing is the catalog:
3 * ids, limits, modalities, knowledge cutoff, release and deprecation, and
4 * the API surfaces each model serves. Prices there are in Lovable credits
5 * with no stated USD rate, so no rate card is stored
6 * (docs/source-silent/lovable.md). The routes are OpenAI-compatible under
7 * https://ai.gateway.lovable.dev/v1. Chat, image, and audio schemas are
8 * generated from OpenAI's document. Video is rewritten per model
9 * (`lovable-video.ts`): the gateway runs Veo and Gemini Omni, not Sora.
10 */
11import type { Activity } from '#/db/schema.ts'
12
13import { applyLovableVideoSchema } from '../lovable-video.ts'
14import { bearerConnect } from '../connect.ts'
15import {
16 classifyOpenAiCompat,
17 fetchOpenAiCompatibleSpec,
18} from '../openai-compat.ts'
19import { fetchJson } from '../types.ts'
20import { namespacedUpstreamIdentity } from '../upstream-model.ts'
21import type {
22 ListModelsResult,
23 ModelInfo,
24 ProviderConfig,
25 ProviderSecrets,
26 SpecFetchResult,
27} from '../types.ts'
28
29export const LOVABLE_MODELS_URL = 'https://ai.gateway.lovable.dev/v1/models'
30export const LOVABLE_SERVER_URL = 'https://ai.gateway.lovable.dev/v1'
31const LOVABLE_DOCS_URL = 'https://docs.lovable.dev/features/ai'
32
33/**
34 * Listing `supported_surfaces` → the route under /v1. `messages`
35 * (Anthropic), `live`, `music`, and `systemone` have no OpenAI-compatible
36 * route here, so a model with only those binds no schema.
37 */
38const SURFACE_ROUTES: Record<string, string> = {
39 'chat-completions': 'chat/completions',
40 responses: 'responses',
41 embeddings: 'embeddings',
42 'image-generation': 'images/generations',
43 'image-edit': 'images/edits',
44 speech: 'audio/speech',
45 transcription: 'audio/transcriptions',
46 videos: 'videos',
47}
48
49/** Every surface the listing names; `systemone` (decisions) is no generation activity. */
50const SURFACE_ACTIVITIES: Record<string, Activity | null> = {
51 systemone: null,
52 'chat-completions': 'chat',
53 responses: 'chat',
54 messages: 'chat',
55 embeddings: 'embeddings',
56 'image-generation': 'image',
57 'image-edit': 'image',
58 speech: 'audio',
59 transcription: 'audio',
60 live: 'audio',
61 music: 'audio',
62 videos: 'video',
63}
64
65function isRecord(value: unknown): value is Record<string, unknown> {
66 return typeof value === 'object' && value !== null && !Array.isArray(value)
67}
68
69function positive(value: unknown): number | null {
70 return typeof value === 'number' && Number.isFinite(value) && value > 0
71 ? value
72 : null
73}
74
75function stringList(value: unknown): Array<string> | null {
76 if (!Array.isArray(value)) return null
77 return value.every((item): item is string => typeof item === 'string')
78 ? value
79 : null
80}
81
82function modalities(value: unknown): ModelInfo['modalities'] {
83 if (!isRecord(value)) return null
84 const input = stringList(value.input)
85 const output = stringList(value.output)
86 return input && output && input.length > 0 ? { input, output } : null
87}
88
89export function parseLovableModels(payload: unknown): Array<ModelInfo> {
90 const data = isRecord(payload) ? payload.data : undefined
91 if (!Array.isArray(data)) {
92 throw new Error('lovable: models payload has no data array')
93 }
94 const models: Array<ModelInfo> = []
95 for (const row of data) {
96 if (!isRecord(row) || typeof row.id !== 'string' || row.id === '') {
97 throw new Error('lovable: models row has no id')
98 }
99 const surfaces = stringList(row.supported_surfaces) ?? []
100 const unknown = surfaces.find((s) => !(s in SURFACE_ACTIVITIES))
101 if (unknown !== undefined) {
102 throw new Error(`lovable: ${row.id} lists unknown surface ${unknown}`)
103 }
104 const activity =
105 surfaces.map((s) => SURFACE_ACTIVITIES[s]).find((a) => a) ?? null
106 const route = surfaces.map((s) => SURFACE_ROUTES[s]).find((r) => r) ?? null
107 const knowledge =
108 typeof row.knowledge === 'string' &&
109 /^\d{4}-\d{2}(?:-\d{2})?$/.test(row.knowledge)
110 ? row.knowledge
111 : null
112 models.push({
113 rawId: row.id,
114 displayName: typeof row.name === 'string' ? row.name : null,
115 activity,
116 schemaEndpointId: route,
117 contextWindow: positive(row.context_window),
118 maxOutput: positive(row.max_tokens),
119 modalities: modalities(row.modalities),
120 knowledgeCutoff: knowledge,
121 releasedAt: positive(row.released),
122 deprecated: row.deprecated === true,
123 })
124 }
125 if (models.length === 0)
126 throw new Error('lovable: models payload listed no ids')
127 return models
128}
129
130async function listModels(_env: ProviderSecrets): Promise<ListModelsResult> {
131 return { models: parseLovableModels(await fetchJson(LOVABLE_MODELS_URL)) }
132}
133
134async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
135 const { spec, url, hash } = await fetchOpenAiCompatibleSpec({
136 title: 'Lovable AI Gateway',
137 serverUrl: LOVABLE_SERVER_URL,
138 include: [
139 '/chat/completions',
140 '/responses',
141 '/embeddings',
142 '/images/generations',
143 '/images/edits',
144 '/audio/speech',
145 '/audio/transcriptions',
146 '/videos',
147 ],
148 })
149 const videoIds = parseLovableModels(await fetchJson(LOVABLE_MODELS_URL))
150 .filter((model) => model.activity === 'video')
151 .map((model) => model.rawId)
152 applyLovableVideoSchema(spec, videoIds)
153 return { specs: [spec], sources: [{ url, hash }], outputStrategy: 'post-200' }
154}
155
156export const provider: ProviderConfig = {
157 id: 'lovable',
158 displayName: 'Lovable AI Gateway',
159 specSourceUrl: LOVABLE_DOCS_URL,
160 modelsEndpoint: LOVABLE_MODELS_URL,
161 defaultDerivation: 'generated',
162 // `openai/gpt-5.5`: the listing names the maker in the id and `owned_by`.
163 upstreamModelIdentity: (rawId) =>
164 namespacedUpstreamIdentity(rawId, {
165 derivation: 'listing',
166 sourceUrl: LOVABLE_MODELS_URL,
167 path: 'data[].id',
168 }),
169 bindSyncedRoutesOnly: true,
170 connect: bearerConnect(LOVABLE_SERVER_URL, 'Lovable AI Gateway'),
171 fetchSpec,
172 listModels,
173 classify: classifyOpenAiCompat,
174}