Open History to see the last commit
1/**
2 * Gemini video request schemas, one per model (issue #658).
3 *
4 * Video runs on the Interactions API (`POST /v1beta/interactions`), which
5 * the Discovery document does not have. Google publishes it as OpenAPI.
6 * That document's `VideoResponseFormat.duration` is an unbounded string;
7 * the range is on each model's docs page (`Output video 3s-15s`). Each
8 * clip model's schema is Google's create request with `model` pinned and
9 * `duration` narrowed to that range.
10 *
11 * A page that states a resolution, fps and token rate (#697) is a
12 * real-time stream. The Interactions document publishes no `world_setup`
13 * or connect operation for it, so it gets no fixed-duration schema and a
14 * named warning. A page that fails to fetch, or a limit shape the parser
15 * does not know, rejects this whole fetch. A partial run would mark every
16 * missing video endpoint removed (`sync.ts`).
17 *
18 * Which pages: the models-index pages for the ids Google's video guide
19 * names. Nothing here falls back: a document that lost the shape, or a
20 * guide that leads to no output-video limit, throws with its URL, and the
21 * sync keeps the stored schemas.
22 */
23import { extractEndpointSchemas } from '../ingest/bundle.ts'
24import {
25 GEMINI_MODELS_INDEX_URL,
26 parseModelIndexDocs,
27 parsePageSections,
28} from './gemini-features.ts'
29import type { GeminiOutputVideo } from './gemini-features.ts'
30import { mapConcurrent } from './model-facts.ts'
31import { fetchText, sha256Text } from './types.ts'
32import type { BundledEndpoint, OpenApiDocument } from './types.ts'
33
34export const GEMINI_INTERACTIONS_SPEC_URL =
35 'https://ai.google.dev/static/api/interactions.openapi.json'
36export const GEMINI_VIDEO_GUIDE_URL =
37 'https://aistudio.google.com/docs/video.md'
38
39const CREATE_PATH = '/{api_version}/interactions'
40const REQUEST = 'CreateModelInteractionParams'
41const VIDEO_FORMAT = 'VideoResponseFormat'
42
43export type GeminiVideoModel = {
44 rawId: string
45 /** The model page that states the limit. */
46 pageUrl: string
47} & GeminiOutputVideo
48
49/** The clip half of {@link GeminiVideoModel}: a page that stated `Ns-Ms`. */
50interface GeminiClipModel {
51 rawId: string
52 pageUrl: string
53 minSeconds: number
54 maxSeconds: number
55}
56
57function isRecord(value: unknown): value is Record<string, unknown> {
58 return typeof value === 'object' && value !== null && !Array.isArray(value)
59}
60
61/** Each model code on a model page whose section states an output video limit. */
62export function parseVideoModels(
63 page: string,
64 pageUrl: string,
65): Array<GeminiVideoModel> {
66 return parsePageSections(page).flatMap(({ codes, outputVideo }) =>
67 outputVideo
68 ? codes.map((rawId) => ({ rawId, pageUrl, ...outputVideo }))
69 : [],
70 )
71}
72
73function isClipModel(model: GeminiVideoModel): model is GeminiClipModel {
74 return 'minSeconds' in model && 'maxSeconds' in model
75}
76
77/** Issue #697: the Interactions spec has no stream create body to narrow. */
78export function streamVideoWarning(rawId: string): string {
79 return `${rawId}: real-time stream, no fixed-duration create schema`
80}
81
82/**
83 * One model's video route: Google's create-interaction request with `model`
84 * pinned and `response_format.duration` an enum of whole seconds. The stored
85 * path is the real one (`/v1beta/interactions`); the model id is the
86 * endpoint id.
87 */
88export function geminiVideoEndpoint(
89 spec: OpenApiDocument,
90 model: GeminiClipModel,
91 specHash: string,
92): { endpoint: BundledEndpoint; warnings: Array<string> } {
93 const lost = (what: string) =>
94 new Error(
95 `gemini video: ${GEMINI_INTERACTIONS_SPEC_URL} has no ${what}; ${model.rawId} gets no schema`,
96 )
97 const operation = spec.paths?.[CREATE_PATH]?.post
98 if (!operation) throw lost(`POST ${CREATE_PATH}`)
99 const version = spec.info?.version
100 if (typeof version !== 'string' || !/^v\d/.test(version)) {
101 throw lost('info.version to fill {api_version}')
102 }
103 const schemas = spec.components?.schemas ?? {}
104 const request = schemas[REQUEST]
105 if (
106 !isRecord(request) ||
107 !isRecord(request.properties) ||
108 !('model' in request.properties) ||
109 !('response_format' in request.properties)
110 ) {
111 throw lost(`${REQUEST} with model and response_format`)
112 }
113 const format = schemas[VIDEO_FORMAT]
114 const duration =
115 isRecord(format) && isRecord(format.properties)
116 ? format.properties.duration
117 : undefined
118 if (
119 !isRecord(format) ||
120 !isRecord(format.properties) ||
121 !isRecord(duration) ||
122 duration.type !== 'string'
123 ) {
124 throw lost(`${VIDEO_FORMAT}.duration string`)
125 }
126 const seconds = Array.from(
127 { length: model.maxSeconds - model.minSeconds + 1 },
128 (_, i) => `${String(model.minSeconds + i)}s`,
129 )
130 const range = `${String(model.minSeconds)}s to ${String(model.maxSeconds)}s`
131 const narrowed: OpenApiDocument = {
132 ...spec,
133 paths: {
134 [CREATE_PATH]: {
135 post: {
136 ...operation,
137 requestBody: {
138 required: true,
139 content: {
140 'application/json': {
141 schema: { $ref: `#/components/schemas/${REQUEST}` },
142 },
143 },
144 },
145 },
146 },
147 },
148 components: {
149 ...spec.components,
150 schemas: {
151 ...schemas,
152 [REQUEST]: {
153 ...request,
154 properties: {
155 ...request.properties,
156 model: {
157 type: 'string',
158 enum: [model.rawId],
159 description: 'The model that generates the video.',
160 },
161 },
162 },
163 [VIDEO_FORMAT]: {
164 ...format,
165 properties: {
166 ...format.properties,
167 duration: {
168 type: 'string',
169 enum: seconds,
170 description: `The duration for the video output, in whole seconds. ${model.rawId} generates ${range} (${model.pageUrl}, Output video).`,
171 },
172 },
173 },
174 },
175 },
176 }
177 const extracted = extractEndpointSchemas(narrowed, CREATE_PATH, 'post-200')
178 if (!extracted.input) throw lost('bundled request schema')
179 return {
180 endpoint: {
181 publicId: model.rawId,
182 path: CREATE_PATH.replace('{api_version}', version),
183 activity: 'video',
184 description: `Generate a video with ${model.rawId} (Interactions API). response_format.duration is ${range}.`,
185 source: { url: GEMINI_INTERACTIONS_SPEC_URL, hash: specHash },
186 // Google's document, plus one limit read from the model's docs page.
187 derivation: 'generated',
188 input: extracted.input,
189 ...(extracted.output ? { output: extracted.output } : {}),
190 },
191 warnings: extracted.warnings,
192 }
193}
194
195/** The models-index pages for the ids the video guide names. */
196export function videoModelPages(guide: string, index: string): Array<string> {
197 const named = new Set(
198 [...guide.matchAll(/`([a-z0-9][a-z0-9.-]*)`/g)].map((match) => match[1]),
199 )
200 return parseModelIndexDocs(index)
201 .filter((doc) => doc.ids.some((id) => named.has(id)))
202 .map((doc) => `${doc.url}.md`)
203}
204
205/** Every Gemini video model's endpoint, from the live documents. */
206export async function geminiVideoEndpoints(): Promise<{
207 endpoints: Array<BundledEndpoint>
208 warnings: Array<string>
209}> {
210 const [specText, guide, index] = await Promise.all([
211 fetchText(GEMINI_INTERACTIONS_SPEC_URL),
212 fetchText(GEMINI_VIDEO_GUIDE_URL),
213 fetchText(GEMINI_MODELS_INDEX_URL),
214 ])
215 const pages = videoModelPages(guide, index)
216 const models = (
217 await mapConcurrent(pages, 4, async (url) =>
218 parseVideoModels(await fetchText(url), url),
219 )
220 ).flat()
221 if (models.length === 0) {
222 throw new Error(
223 `gemini video: ${GEMINI_VIDEO_GUIDE_URL} leads to no model with an Output video limit (${String(pages.length)} model pages read: ${pages.join(', ') || 'none'})`,
224 )
225 }
226 const warnings: Array<string> = []
227 const clips = models.filter(isClipModel)
228 for (const model of models) {
229 if (isClipModel(model)) continue
230 const warning = streamVideoWarning(model.rawId)
231 warnings.push(warning)
232 console.error(`gemini video: ${warning}`)
233 }
234 const spec = JSON.parse(specText) as OpenApiDocument
235 const specHash = await sha256Text(specText)
236 const built = clips.map((model) => geminiVideoEndpoint(spec, model, specHash))
237 return {
238 endpoints: built.map((item) => item.endpoint),
239 warnings: [...warnings, ...built.flatMap((item) => item.warnings)],
240 }
241}