Skip to main content

adk_vision/video/
gemini.rs

1//! [`GeminiVideoAnalyzer`]: Gemini native video (spec 3.7 §7.13, X8, X9), feature
2//! `gemini-video`.
3
4use std::collections::HashMap;
5use std::sync::Arc;
6use std::time::{Duration, Instant};
7
8use adk_core::{Content, GenerateContentConfig, Llm, LlmRequest, Part};
9use adk_model::GeminiModel;
10use adk_model::gemini::{GeminiFile, GeminiRequestOptions, VideoMetadata, video_part_annotations};
11use adk_model::pricing::PricingCatalog;
12use async_trait::async_trait;
13use serde_json::Value;
14use tokio::sync::Mutex;
15
16pub use adk_model::gemini::MediaResolution;
17
18use super::answer::{ModelAnswer, add_usage, ask_schema, generate, parse_time};
19use crate::backend::{BackendDescriptor, BackendId, Locality, PriceRef};
20use crate::cloud::extract_json;
21use crate::cx::VisionCx;
22use crate::digest::Digest;
23use crate::egress::{ReleasedClip, ReleasedImage};
24use crate::error::{Result, VisionError};
25use crate::geometry::{CoordFrame, RawRegion};
26use crate::traits::{
27    VideoAnalysis, VideoAnalyzer, VideoEvent, VideoInput, VideoPlan, VideoRequest,
28};
29
30/// The most a request carries inline: Gemini's 20 MB request limit.
31pub const GEMINI_INLINE_LIMIT: usize = 20 * 1024 * 1024;
32/// The AI Studio host, for a client that names none.
33const GEMINI_HOST: &str = "generativelanguage.googleapis.com";
34/// Uploaded files expire after 48 hours; reuse one for a little less.
35const UPLOAD_REUSE: Duration = Duration::from_secs(47 * 3600);
36
37/// Answers `Ask` over a clip with Gemini native video.
38///
39/// The clip comes from the egress gate ([`ReleasedClip`]). Up to
40/// [`inline_limit`](Self::with_inline_limit) (20 MB) it goes inline; above it, it is
41/// uploaded once through the File API, waited on until Gemini has processed it, and sent as
42/// a `fileData` part — a second question about the same clip reuses the upload. Gemini
43/// samples the clip at the call's [`Sampling::fps`](crate::Sampling) (its default is 1 fps)
44/// and tokenises each frame at the [`MediaResolution`]: about 100 tokens a second of video
45/// at `Low`, about 300 otherwise. The model answers in words with events as `m:ss.s`
46/// times; its tokens and cost are reported in [`VideoUsage`](crate::VideoUsage).
47///
48/// # Example
49///
50/// ```no_run
51/// use std::sync::Arc;
52/// use adk_model::GeminiModel;
53/// use adk_vision::{GeminiVideoAnalyzer, MediaResolution, VisionRuntime};
54///
55/// let gemini = Arc::new(GeminiModel::new(std::env::var("GEMINI_API_KEY").unwrap(), "gemini-3.8-flash").unwrap());
56/// let analyzer = GeminiVideoAnalyzer::new(gemini).with_media_resolution(MediaResolution::Low);
57/// let runtime = VisionRuntime::builder().remote_video_analyzer(Arc::new(analyzer)).build().unwrap();
58/// ```
59pub struct GeminiVideoAnalyzer {
60    model: Arc<GeminiModel>,
61    descriptor: BackendDescriptor,
62    media_resolution: Option<MediaResolution>,
63    inline_limit: usize,
64    max_output_tokens: u32,
65    poll: Duration,
66    processing_timeout: Duration,
67    uploads: Mutex<HashMap<Digest, (GeminiFile, Instant)>>,
68}
69
70impl std::fmt::Debug for GeminiVideoAnalyzer {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        f.debug_struct("GeminiVideoAnalyzer")
73            .field("descriptor", &self.descriptor)
74            .field("media_resolution", &self.media_resolution)
75            .field("inline_limit", &self.inline_limit)
76            .finish_non_exhaustive()
77    }
78}
79
80impl GeminiVideoAnalyzer {
81    /// Asks `model`, at the hosts its client names: AI Studio, a custom base URL, or a Vertex
82    /// AI endpoint.
83    pub fn new(model: Arc<GeminiModel>) -> Self {
84        let name = model.name().to_string();
85        let mut hosts = adk_core::DataDestination::all_hosts(&model.data_destinations());
86        if hosts.is_empty() {
87            hosts.push(GEMINI_HOST.into());
88        }
89        let descriptor = BackendDescriptor::new(
90            name.clone(),
91            Locality::Remote { hosts },
92            CoordFrame::SentPixels,
93        )
94        .with_provider("gemini")
95        .with_price(PriceRef::Tokens {
96            vendor: adk_core::vendor_for_model(&name).to_string(),
97            model: name,
98        });
99        Self {
100            model,
101            descriptor,
102            media_resolution: None,
103            inline_limit: GEMINI_INLINE_LIMIT,
104            max_output_tokens: 2_048,
105            poll: Duration::from_secs(2),
106            processing_timeout: Duration::from_secs(600),
107            uploads: Mutex::new(HashMap::new()),
108        }
109    }
110
111    /// Names the hosts the egress policy checks instead of AI Studio's, for a gateway.
112    pub fn with_hosts<H: Into<String>>(mut self, hosts: impl IntoIterator<Item = H>) -> Self {
113        self.descriptor.locality =
114            Locality::Remote { hosts: hosts.into_iter().map(Into::into).collect() };
115        self
116    }
117
118    /// Names the backend `id` instead of the model name.
119    pub fn with_id(mut self, id: impl Into<String>) -> Self {
120        self.descriptor.id = BackendId::new(id);
121        self
122    }
123
124    /// Tokenises frames at `resolution`; Gemini's default otherwise.
125    pub fn with_media_resolution(mut self, resolution: MediaResolution) -> Self {
126        self.media_resolution = Some(resolution);
127        self
128    }
129
130    /// Sends clips up to `bytes` inline and uploads larger ones; 0 always uploads.
131    pub fn with_inline_limit(mut self, bytes: usize) -> Self {
132        self.inline_limit = bytes.min(GEMINI_INLINE_LIMIT);
133        self
134    }
135
136    /// Caps the answer at `tokens`; 2,048 by default.
137    pub fn with_max_output_tokens(mut self, tokens: u32) -> Self {
138        self.max_output_tokens = tokens;
139        self
140    }
141
142    /// Polls an uploaded clip every `interval` for at most `timeout` while Gemini processes
143    /// it; every 2 s for up to 10 minutes by default.
144    pub fn with_processing_wait(mut self, interval: Duration, timeout: Duration) -> Self {
145        self.poll = interval;
146        self.processing_timeout = timeout;
147        self
148    }
149
150    /// Input tokens of a clip of `duration_ms` sampled at `fps`: each frame at the media
151    /// resolution (66 tokens at `Low`, 258 otherwise) and 32 tokens a second of audio.
152    ///
153    /// # Example
154    ///
155    /// ```
156    /// use adk_vision::{GeminiVideoAnalyzer, MediaResolution};
157    ///
158    /// // Twenty minutes at 1 fps: about 100 tokens a second at low resolution.
159    /// assert_eq!(GeminiVideoAnalyzer::video_tokens(1_200_000, 1.0, Some(MediaResolution::Low)), 117_600);
160    /// assert_eq!(GeminiVideoAnalyzer::video_tokens(1_200_000, 1.0, None), 348_000);
161    /// ```
162    pub fn video_tokens(duration_ms: u64, fps: f32, resolution: Option<MediaResolution>) -> u64 {
163        let per_frame = match resolution {
164            Some(MediaResolution::Low) => 66,
165            _ => 258,
166        };
167        let fps = if fps.is_finite() && fps > 0.0 { f64::from(fps) } else { 1.0 };
168        let frames = (duration_ms as f64 * fps / 1_000.0).ceil() as u64;
169        frames * per_frame + duration_ms.div_ceil(1_000) * 32
170    }
171
172    fn prompt(question: &str, duration_ms: u64) -> String {
173        format!(
174            "Question about the video above, which is {} long: {question}\n\nAnswer with JSON \
175             only: {{\"answer\": <the answer in words>, \"events\": [{{\"start\": \"m:ss.s\", \
176             \"end\": \"m:ss.s\", \"text\": <what happens>}}]}}, with times from the start of \
177             the video. List an event only for what the question asks about; if it does not \
178             happen, say so in the answer and give no events.",
179            super::timestamp(duration_ms)
180        )
181    }
182
183    /// The clip's part: inline, or a file uploaded once and processed.
184    async fn part(
185        &self,
186        cx: &VisionCx,
187        clip: &ReleasedClip,
188        metadata: &VideoMetadata,
189    ) -> Result<Part> {
190        let annotations = Some(video_part_annotations(metadata));
191        let mime_type = clip.mime_type().to_string();
192        if clip.bytes().len() <= self.inline_limit {
193            return Ok(Part::InlineData {
194                mime_type,
195                data: clip.bytes().to_vec(),
196                uri: None,
197                annotations,
198            });
199        }
200        let digest = clip.receipt().egress;
201        let mut uploads = self.uploads.lock().await;
202        uploads.retain(|_, (_, at)| at.elapsed() < UPLOAD_REUSE);
203        let file = match uploads.get(&digest) {
204            Some((file, _)) => file.clone(),
205            None => {
206                cx.check()?;
207                let backend = self.descriptor.id.to_string();
208                let unavailable = |e: adk_core::AdkError| VisionError::Unavailable {
209                    backend: backend.clone(),
210                    message: e.to_string(),
211                };
212                let uploaded = self
213                    .model
214                    .upload_file(clip.bytes().to_vec(), &mime_type, Some(&digest.to_string()))
215                    .await
216                    .map_err(unavailable)?;
217                tracing::info!(vision.backend = %backend, gemini.file = %uploaded.name, clip.bytes = clip.bytes().len(), "clip uploaded through the File API");
218                let ready = tokio::select! {
219                    () = cx.cancellation().cancelled() => return Err(VisionError::Cancelled),
220                    ready = self.model.wait_for_file(&uploaded.name, self.poll, self.processing_timeout) => ready.map_err(unavailable)?,
221                };
222                uploads.insert(digest, (ready.clone(), Instant::now()));
223                ready
224            }
225        };
226        Ok(Part::FileData { mime_type, file_uri: file.uri, annotations })
227    }
228}
229
230#[async_trait]
231impl VideoAnalyzer<ReleasedImage> for GeminiVideoAnalyzer {
232    fn descriptor(&self) -> &BackendDescriptor {
233        &self.descriptor
234    }
235
236    fn frames(&self, plan: &VideoPlan) -> u64 {
237        match &plan.clip {
238            Some(clip) => clip.sampled_frames(plan.sampling.fps),
239            None => plan.frames(),
240        }
241    }
242
243    fn max_cost_micro_usd(&self, plan: &VideoPlan, request: &VideoRequest) -> Option<u64> {
244        let PriceRef::Tokens { vendor, model } = self.descriptor.price.as_ref()? else {
245            return None;
246        };
247        let price = PricingCatalog::standard().lookup(Some(vendor), model)?;
248        let question = match request {
249            VideoRequest::Ask { question } => question.len() as u64,
250            _ => 0,
251        };
252        let input = Self::video_tokens(plan.duration_ms, plan.sampling.fps, self.media_resolution)
253            + question
254            + 1_024;
255        let today = chrono::Utc::now().date_naive();
256        let usd = price.max_cost_usd(input, u64::from(self.max_output_tokens), today);
257        adk_core::usd_to_micro_usd(usd).map(|m| m.saturating_add(1))
258    }
259
260    async fn analyze(
261        &self,
262        cx: &VisionCx,
263        video: &VideoInput<ReleasedImage>,
264        request: &VideoRequest,
265    ) -> Result<VideoAnalysis<RawRegion>> {
266        let VideoRequest::Ask { question } = request else {
267            return Err(VisionError::Unsupported(format!(
268                "`{}` answers `Ask`; track with `sam-3.1` video",
269                self.descriptor.id
270            )));
271        };
272        let Some(clip) = video.clip.as_ref() else {
273            return Err(VisionError::Unsupported(format!(
274                "`{}` reads clips; ask about sampled frames with a `FramesAnalyzer`",
275                self.descriptor.id
276            )));
277        };
278        if !clip.is_for(&self.descriptor.id) {
279            return Err(VisionError::NotReleased {
280                backend: format!(
281                    "{} (the clip was released to `{}`)",
282                    self.descriptor.id,
283                    clip.receipt().backend
284                ),
285            });
286        }
287        let info = clip.info();
288        let fps = f64::from(video.sampling.fps);
289        let metadata = if fps.is_finite() && fps > 0.0 {
290            VideoMetadata::default().with_fps(fps)
291        } else {
292            VideoMetadata::default()
293        };
294        let part = self.part(cx, clip, &metadata).await?;
295        let mut config = GenerateContentConfig {
296            max_output_tokens: i32::try_from(self.max_output_tokens).ok(),
297            response_schema: Some(ask_schema("time")),
298            ..GenerateContentConfig::default()
299        };
300        if let Some(resolution) = self.media_resolution {
301            GeminiRequestOptions::default()
302                .with_media_resolution(resolution)
303                .insert_into(&mut config);
304        }
305        let parts = vec![part, Part::Text { text: Self::prompt(question, info.duration_ms) }];
306        let llm_request = LlmRequest {
307            config: Some(config),
308            ..LlmRequest::new(self.model.name(), vec![Content { role: "user".into(), parts }])
309        };
310        let plan = VideoPlan {
311            clip: Some(info.clone()),
312            frame_sizes: Vec::new(),
313            duration_ms: info.duration_ms,
314            sampling: video.sampling,
315        };
316        let bound = self.max_cost_micro_usd(&plan, request);
317        let backend = self.descriptor.id.to_string();
318        let llm: Arc<dyn Llm> = self.model.clone();
319        let ModelAnswer { text, usage } = generate(cx, &llm, bound, llm_request, &backend).await?;
320        let mut analysis = VideoAnalysis::default();
321        add_usage(&mut analysis.usage, &self.descriptor, usage.as_ref());
322        analysis.usage.frames = info.sampled_frames(video.sampling.fps);
323        let root = extract_json(&text).ok_or_else(|| VisionError::Parse {
324            backend: backend.clone(),
325            message: format!("the answer holds no JSON: {text}"),
326        })?;
327        analysis.answer = root.get("answer").and_then(Value::as_str).map(str::to_string);
328        for event in root.get("events").and_then(Value::as_array).into_iter().flatten() {
329            let Some(start) = event.get("start").and_then(parse_time) else { continue };
330            let start = start.min(info.duration_ms);
331            let end = event
332                .get("end")
333                .and_then(parse_time)
334                .unwrap_or(start)
335                .clamp(start, info.duration_ms);
336            let text = event.get("text").and_then(Value::as_str).unwrap_or_default();
337            analysis.events.push(VideoEvent::new(start, end, text));
338        }
339        analysis.events.sort_by_key(|e| e.start_ms);
340        Ok(analysis)
341    }
342}