Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

gemini-video.ts

212 lines7.1 KB

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 * model's schema is Google's create request with `model` pinned and
9 * `duration` narrowed to that range.
10 *
11 * Which pages: the models-index pages for the ids Google's video guide
12 * names. Every model section on those pages that states an output video
13 * limit gets a schema. Nothing here falls back: a document that lost the
14 * shape, or a guide that leads to no limit, throws with its URL, and the
15 * sync keeps the stored schemas.
16 */
17import { extractEndpointSchemas } from '../ingest/bundle.ts'
18import {
19 GEMINI_MODELS_INDEX_URL,
20 parseModelIndexDocs,
21 parsePageSections,
22} from './gemini-features.ts'
23import type { GeminiOutputVideo } from './gemini-features.ts'
24import { mapConcurrent } from './model-facts.ts'
25import { fetchText, sha256Text } from './types.ts'
26import type { BundledEndpoint, OpenApiDocument } from './types.ts'
27​
28export const GEMINI_INTERACTIONS_SPEC_URL =
29 'https://ai.google.dev/static/api/interactions.openapi.json'
30export const GEMINI_VIDEO_GUIDE_URL =
31 'https://aistudio.google.com/docs/video.md'
32​
33const CREATE_PATH = '/{api_version}/interactions'
34const REQUEST = 'CreateModelInteractionParams'
35const VIDEO_FORMAT = 'VideoResponseFormat'
36​
37export interface GeminiVideoModel extends GeminiOutputVideo {
38 rawId: string
39 /** The model page that states the limit. */
40 pageUrl: string
42​
43function isRecord(value: unknown): value is Record<string, unknown> {
44 return typeof value === 'object' && value !== null && !Array.isArray(value)
46​
47/** Each model code on a model page whose section states an output video limit. */
48export function parseVideoModels(
49 page: string,
50 pageUrl: string,
51): Array<GeminiVideoModel> {
52 return parsePageSections(page).flatMap(({ codes, outputVideo }) =>
53 outputVideo
54 ? codes.map((rawId) => ({ rawId, pageUrl, ...outputVideo }))
55 : [],
56 )
58​
59/**
60 * One model's video route: Google's create-interaction request with `model`
61 * pinned and `response_format.duration` an enum of whole seconds. The stored
62 * path is the real one (`/v1beta/interactions`); the model id is the
63 * endpoint id.
64 */
65export function geminiVideoEndpoint(
66 spec: OpenApiDocument,
67 model: GeminiVideoModel,
68 specHash: string,
69): { endpoint: BundledEndpoint; warnings: Array<string> } {
70 const lost = (what: string) =>
71 new Error(
72 `gemini video: ${GEMINI_INTERACTIONS_SPEC_URL} has no ${what}; ${model.rawId} gets no schema`,
73 )
74 const operation = spec.paths?.[CREATE_PATH]?.post
75 if (!operation) throw lost(`POST ${CREATE_PATH}`)
76 const version = spec.info?.version
77 if (typeof version !== 'string' || !/^v\d/.test(version)) {
78 throw lost('info.version to fill {api_version}')
79 }
80 const schemas = spec.components?.schemas ?? {}
81 const request = schemas[REQUEST]
82 if (
83 !isRecord(request) ||
84 !isRecord(request.properties) ||
85 !('model' in request.properties) ||
86 !('response_format' in request.properties)
87 ) {
88 throw lost(`${REQUEST} with model and response_format`)
89 }
90 const format = schemas[VIDEO_FORMAT]
91 const duration =
92 isRecord(format) && isRecord(format.properties)
93 ? format.properties.duration
94 : undefined
95 if (
96 !isRecord(format) ||
97 !isRecord(format.properties) ||
98 !isRecord(duration) ||
99 duration.type !== 'string'
100 ) {
101 throw lost(`${VIDEO_FORMAT}.duration string`)
102 }
103 const seconds = Array.from(
104 { length: model.maxSeconds - model.minSeconds + 1 },
105 (_, i) => `${String(model.minSeconds + i)}s`,
106 )
107 const range = `${String(model.minSeconds)}s to ${String(model.maxSeconds)}s`
108 const narrowed: OpenApiDocument = {
109 ...spec,
110 paths: {
111 [CREATE_PATH]: {
112 post: {
113 ...operation,
114 requestBody: {
115 required: true,
116 content: {
117 'application/json': {
118 schema: { $ref: `#/components/schemas/${REQUEST}` },
119 },
120 },
121 },
122 },
123 },
124 },
125 components: {
126 ...spec.components,
127 schemas: {
128 ...schemas,
129 [REQUEST]: {
130 ...request,
131 properties: {
132 ...request.properties,
133 model: {
134 type: 'string',
135 enum: [model.rawId],
136 description: 'The model that generates the video.',
137 },
138 },
139 },
140 [VIDEO_FORMAT]: {
141 ...format,
142 properties: {
143 ...format.properties,
144 duration: {
145 type: 'string',
146 enum: seconds,
147 description: `The duration for the video output, in whole seconds. ${model.rawId} generates ${range} (${model.pageUrl}, Output video).`,
148 },
149 },
150 },
151 },
152 },
153 }
154 const extracted = extractEndpointSchemas(narrowed, CREATE_PATH, 'post-200')
155 if (!extracted.input) throw lost('bundled request schema')
156 return {
157 endpoint: {
158 publicId: model.rawId,
159 path: CREATE_PATH.replace('{api_version}', version),
160 activity: 'video',
161 description: `Generate a video with ${model.rawId} (Interactions API). response_format.duration is ${range}.`,
162 source: { url: GEMINI_INTERACTIONS_SPEC_URL, hash: specHash },
163 // Google's document, plus one limit read from the model's docs page.
164 derivation: 'generated',
165 input: extracted.input,
166 ...(extracted.output ? { output: extracted.output } : {}),
167 },
168 warnings: extracted.warnings,
169 }
171​
172/** The models-index pages for the ids the video guide names. */
173export function videoModelPages(guide: string, index: string): Array<string> {
174 const named = new Set(
175 [...guide.matchAll(/`([a-z0-9][a-z0-9.-]*)`/g)].map((match) => match[1]),
176 )
177 return parseModelIndexDocs(index)
178 .filter((doc) => doc.ids.some((id) => named.has(id)))
179 .map((doc) => `${doc.url}.md`)
181​
182/** Every Gemini video model's endpoint, from the live documents. */
183export async function geminiVideoEndpoints(): Promise<{
184 endpoints: Array<BundledEndpoint>
185 warnings: Array<string>
186}> {
187 const [specText, guide, index] = await Promise.all([
188 fetchText(GEMINI_INTERACTIONS_SPEC_URL),
189 fetchText(GEMINI_VIDEO_GUIDE_URL),
190 fetchText(GEMINI_MODELS_INDEX_URL),
191 ])
192 const pages = videoModelPages(guide, index)
193 const models = (
194 await mapConcurrent(pages, 4, async (url) =>
195 parseVideoModels(await fetchText(url), url),
196 )
197 ).flat()
198 if (models.length === 0) {
199 throw new Error(
200 `gemini video: ${GEMINI_VIDEO_GUIDE_URL} leads to no model with an Output video limit (${String(pages.length)} model pages read: ${pages.join(', ') || 'none'})`,
201 )
202 }
203 const spec = JSON.parse(specText) as OpenApiDocument
204 const specHash = await sha256Text(specText)
205 const built = models.map((model) =>
206 geminiVideoEndpoint(spec, model, specHash),
207 )
208 return {
209 endpoints: built.map((item) => item.endpoint),
210 warnings: built.flatMap((item) => item.warnings),
211 }