Skip to main content

adk_vision/cloud/
describer.rs

1//! [`LlmDescriber`]: any `adk_core::Llm` that takes images, as a [`Describer`].
2
3use std::marker::PhantomData;
4use std::sync::Arc;
5
6use adk_core::{
7    Content, DataLocality, Effort, FinishReason, GenerateContentConfig, Llm, LlmRequest, Part,
8};
9use async_trait::async_trait;
10use futures::StreamExt;
11use serde_json::{Value, json};
12
13use super::adapter::{RegionAdapter, adapter_for_model, extract_json};
14use super::preflight::{Preflight, Preflighted};
15use crate::backend::{BackendDescriptor, InputLimits, Locality, PriceRef};
16use crate::cx::VisionCx;
17use crate::egress::ReleasedImage;
18use crate::error::{Result, VisionError};
19use crate::geometry::CoordFrame;
20use crate::sent::{SentImage, VisionInput};
21use crate::traits::{DescribeRequest, Describer, Description, ImageRegion};
22
23/// A [`Describer`] over any `adk_core::Llm` that takes images: Gemini, Claude, Muse, an
24/// NVIDIA NIM, or a model on this machine.
25///
26/// It sends the images as inline parts, the caller's schema as the response schema, and,
27/// when regions are asked for, the region format of a [`RegionAdapter`] picked by model ID
28/// ([`adapter_for_model`]). The descriptor's frame and input limits are the adapter's, so
29/// the runtime maps every region to source pixels and the egress gate never sends an image
30/// the provider would resize. A model with no adapter answers in text and values only; a
31/// request for regions is refused with `Unsupported` rather than a guessed frame.
32///
33/// The model call is metered as one model call under the call's [`VisionCx`] scope: its
34/// spend hold is sized by [`preflight`](Self::preflight) from the provider's image-token
35/// formula, the prompt and the output cap, and its tokens are committed from the
36/// response. The runtime records the call's images as units.
37///
38/// A remote describer ([`remote`](Self::remote)) takes only [`ReleasedImage`]s; a local
39/// one ([`local`](Self::local)), for a model in this process or on a loopback address,
40/// takes [`SentImage`]s.
41///
42/// # Example
43///
44/// ```
45/// use std::sync::Arc;
46/// use adk_model::MockLlm;
47/// use adk_vision::{CoordFrame, Describer, LlmDescriber};
48///
49/// let model = Arc::new(MockLlm::new("claude-sonnet-5-5"));
50/// let describer = LlmDescriber::remote_with_hosts(model, ["api.anthropic.com"]).unwrap();
51/// assert_eq!(describer.descriptor().frame, CoordFrame::SentPixels);
52/// assert_eq!(describer.descriptor().limits.max_long_edge, Some(2576));
53/// ```
54pub struct LlmDescriber<I = ReleasedImage> {
55    llm: Arc<dyn Llm>,
56    descriptor: BackendDescriptor,
57    adapter: Option<Arc<dyn RegionAdapter>>,
58    effort: Option<Effort>,
59    max_output_tokens: Option<u32>,
60    unpriced_hold: Option<u64>,
61    input: PhantomData<fn() -> I>,
62}
63
64impl<I> std::fmt::Debug for LlmDescriber<I> {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        f.debug_struct("LlmDescriber")
67            .field("model", &self.llm.name())
68            .field("descriptor", &self.descriptor)
69            .field("adapter", &self.adapter.as_ref().map(|a| a.name()))
70            .finish_non_exhaustive()
71    }
72}
73
74impl LlmDescriber<ReleasedImage> {
75    /// A describer for a model off the machine; it takes only images the egress gate
76    /// released to it.
77    ///
78    /// The hosts and providers come from the model ([`Llm::data_destinations`]): every
79    /// `adk-model` provider names the host of its configured endpoint, so a custom base URL,
80    /// a Vertex location or a Bedrock region is the host the egress policy and rules see.
81    ///
82    /// # Errors
83    ///
84    /// [`VisionError::InvalidInput`] when the model names no host; pass them with
85    /// [`remote_with_hosts`](Self::remote_with_hosts).
86    ///
87    /// # Example
88    ///
89    /// ```
90    /// use std::sync::Arc;
91    /// use adk_model::anthropic::AnthropicConfig;
92    /// use adk_model::AnthropicClient;
93    /// use adk_vision::{Locality, LlmDescriber};
94    ///
95    /// let claude = AnthropicClient::new(AnthropicConfig::new("key", "claude-sonnet-5-5")).unwrap();
96    /// let describer = LlmDescriber::remote(Arc::new(claude)).unwrap();
97    /// let descriptor = adk_vision::Describer::descriptor(&describer);
98    /// assert_eq!(descriptor.locality, Locality::Remote { hosts: vec!["api.anthropic.com".into()] });
99    /// assert_eq!(descriptor.providers, ["anthropic"]);
100    /// ```
101    pub fn remote(llm: Arc<dyn Llm>) -> Result<Self> {
102        Self::remote_with_hosts(llm, Vec::<String>::new())
103    }
104
105    /// A describer for a model off the machine that sends to `hosts` in place of the hosts
106    /// the model names, for a model that names none or a gateway its client does not know
107    /// about. With no `hosts`, the model's.
108    ///
109    /// # Errors
110    ///
111    /// [`VisionError::InvalidInput`] when neither `hosts` nor the model names a host: the
112    /// egress policy checks each host before an image is released.
113    pub fn remote_with_hosts<H: Into<String>>(
114        llm: Arc<dyn Llm>,
115        hosts: impl IntoIterator<Item = H>,
116    ) -> Result<Self> {
117        let destinations = llm.data_destinations();
118        let mut hosts: Vec<String> = hosts.into_iter().map(Into::into).collect();
119        if hosts.is_empty() {
120            hosts = adk_core::DataDestination::all_hosts(&destinations);
121        }
122        if hosts.is_empty() {
123            return Err(VisionError::InvalidInput(format!(
124                "model `{}` names no host it sends to, so the egress policy cannot check \
125                 one; pass them with `LlmDescriber::remote_with_hosts`",
126                llm.name()
127            )));
128        }
129        let mut describer = Self::with_locality(llm, Locality::Remote { hosts });
130        for destination in destinations {
131            describer.descriptor = describer.descriptor.with_provider(destination.provider);
132        }
133        Ok(describer)
134    }
135}
136
137impl LlmDescriber<SentImage> {
138    /// A describer for a model in this process or on a loopback address, such as
139    /// `adk-mistralrs` or a `mistralrs serve` endpoint on `127.0.0.1`.
140    ///
141    /// # Errors
142    ///
143    /// [`VisionError::InvalidInput`] when the model reports that it sends data off the
144    /// machine ([`Llm::data_locality`]); use [`LlmDescriber::remote`] so its images pass the
145    /// egress gate.
146    pub fn local(llm: Arc<dyn Llm>) -> Result<Self> {
147        let locality = match llm.data_locality() {
148            DataLocality::InProcess => Locality::InProcess,
149            DataLocality::Loopback => Locality::Loopback,
150            _ => {
151                return Err(VisionError::InvalidInput(format!(
152                    "model `{}` sends data off the machine; describe with \
153                     `LlmDescriber::remote` so its images pass the egress gate",
154                    llm.name()
155                )));
156            }
157        };
158        Ok(Self::with_locality(llm, locality))
159    }
160}
161
162impl<I> LlmDescriber<I> {
163    fn with_locality(llm: Arc<dyn Llm>, locality: Locality) -> Self {
164        let adapter = adapter_for_model(llm.name());
165        let mut describer = Self {
166            descriptor: BackendDescriptor::new(llm.name(), locality, CoordFrame::SentPixels),
167            llm,
168            adapter: None,
169            effort: None,
170            max_output_tokens: None,
171            unpriced_hold: None,
172            input: PhantomData,
173        };
174        describer.set_adapter(adapter);
175        describer
176    }
177
178    fn set_adapter(&mut self, adapter: Option<Arc<dyn RegionAdapter>>) {
179        let model = self.llm.name().to_string();
180        let vendor = adapter
181            .as_ref()
182            .and_then(|a| a.vendor().map(str::to_string))
183            .unwrap_or_else(|| adk_core::vendor_for_model(&model).to_string());
184        self.descriptor.frame = adapter.as_ref().map_or(CoordFrame::SentPixels, |a| a.frame());
185        self.descriptor.limits =
186            adapter.as_ref().map_or_else(InputLimits::unlimited, |a| a.limits());
187        self.descriptor.price = match self.descriptor.locality {
188            Locality::Remote { .. } => Some(PriceRef::Tokens { vendor, model }),
189            _ => None,
190        };
191        self.adapter = adapter;
192        self.refresh_estimate();
193    }
194
195    /// The runtime holds this estimate before an image is released (V-I6); the model call
196    /// then holds and commits its own tokens.
197    fn refresh_estimate(&mut self) {
198        self.descriptor.token_estimate = match (&self.descriptor.price, &self.adapter) {
199            (Some(PriceRef::Tokens { .. }), Some(adapter)) => super::preflight::token_estimate(
200                self.llm.name(),
201                adapter.image_tokens(),
202                self.max_output_tokens,
203            ),
204            _ => None,
205        };
206    }
207
208    /// Reads regions with `adapter` instead of the one picked by model ID; the descriptor
209    /// takes its frame and limits.
210    pub fn with_adapter(mut self, adapter: Arc<dyn RegionAdapter>) -> Self {
211        self.set_adapter(Some(adapter));
212        self
213    }
214
215    /// Answers in text and values only, refusing requests for regions.
216    pub fn without_regions(mut self) -> Self {
217        self.set_adapter(None);
218        self
219    }
220
221    /// Names the backend `id` instead of the model name.
222    pub fn with_id(mut self, id: impl Into<String>) -> Self {
223        self.descriptor.id = crate::backend::BackendId::new(id);
224        self
225    }
226
227    /// Names the manifest the model was loaded from.
228    #[cfg(feature = "mistralrs")]
229    pub(crate) fn with_manifest(mut self, id: &str) -> Self {
230        self.descriptor.manifest = Some(id.to_string());
231        self
232    }
233
234    /// Sets the input limits, for a provider whose limit is lower than its adapter's.
235    pub fn with_limits(mut self, limits: InputLimits) -> Self {
236        self.descriptor.limits = limits;
237        self
238    }
239
240    /// Sets the reasoning effort of every call.
241    pub fn with_effort(mut self, effort: Effort) -> Self {
242        self.effort = Some(effort);
243        self
244    }
245
246    /// Caps output tokens when the request does not.
247    pub fn with_max_output_tokens(mut self, tokens: u32) -> Self {
248        self.max_output_tokens = Some(tokens);
249        self.refresh_estimate();
250        self
251    }
252
253    /// Holds and commits `micro_usd` per call when the `adk-model` catalog does not price
254    /// the model, instead of the run's unpriced-call estimate. NVIDIA publishes no price
255    /// for its hosted trial endpoints, so `NimConfig` describers hold 0 and
256    /// are bounded by unit caps.
257    pub fn with_unpriced_hold(mut self, micro_usd: u64) -> Self {
258        self.unpriced_hold = Some(micro_usd);
259        self
260    }
261
262    /// The region adapter, when the describer returns regions.
263    pub fn adapter(&self) -> Option<&dyn RegionAdapter> {
264        self.adapter.as_deref()
265    }
266
267    /// The model.
268    pub fn model(&self) -> &Arc<dyn Llm> {
269        &self.llm
270    }
271
272    /// The cost estimate a call on images of `sizes` (as sent) holds before its request:
273    /// the provider's image tokens, the prompt bounded at one token per byte, and the
274    /// output cap, priced from the `adk-model` catalog.
275    ///
276    /// # Example
277    ///
278    /// ```
279    /// use std::sync::Arc;
280    /// use adk_model::MockLlm;
281    /// use adk_vision::{DescribeSpec, LlmDescriber};
282    ///
283    /// let model = Arc::new(MockLlm::new("claude-haiku-5-5"));
284    /// let describer = LlmDescriber::remote_with_hosts(model, ["api.anthropic.com"]).unwrap();
285    /// let spec = DescribeSpec::new("Where is the save button?").with_regions()
286    ///     .with_max_output_tokens(1_000);
287    /// let estimate = describer.preflight(&[(2356, 1530)], &spec);
288    /// assert_eq!(estimate.image_tokens, 4675);
289    /// assert!(estimate.max_cost_micro_usd.is_some());
290    /// ```
291    pub fn preflight(&self, sizes: &[(u32, u32)], spec: &crate::DescribeSpec) -> Preflight {
292        let request = self.build_request(
293            sizes.iter().map(|_| Part::Text { text: String::new() }).collect(),
294            sizes,
295            &spec.prompt,
296            spec.output_schema.as_ref(),
297            spec.want_regions,
298            spec.max_output_tokens,
299        );
300        Preflight::estimate(self.llm.name(), &request, self.adapter.as_deref(), sizes)
301    }
302
303    fn build_request(
304        &self,
305        images: Vec<Part>,
306        sizes: &[(u32, u32)],
307        prompt: &str,
308        schema: Option<&Value>,
309        want_regions: bool,
310        max_output_tokens: Option<u32>,
311    ) -> LlmRequest {
312        let mut text = prompt.to_string();
313        let mut config = GenerateContentConfig {
314            max_output_tokens: max_output_tokens
315                .or(self.max_output_tokens)
316                .and_then(|t| i32::try_from(t).ok()),
317            effort: self.effort,
318            ..GenerateContentConfig::default()
319        };
320        match (want_regions, &self.adapter) {
321            (true, Some(adapter)) => {
322                let mut item = adapter.region_schema();
323                if sizes.len() > 1
324                    && let Some(props) = item.get_mut("properties").and_then(Value::as_object_mut)
325                {
326                    props.insert("image".into(), json!({"type": "integer"}));
327                }
328                let mut properties = json!({
329                    "regions": {"type": "array", "items": item}
330                });
331                let mut required = vec!["regions"];
332                match schema {
333                    Some(value) => {
334                        properties["value"] = value.clone();
335                        required.insert(0, "value");
336                    }
337                    None => {
338                        properties["text"] = json!({"type": "string"});
339                        required.insert(0, "text");
340                    }
341                }
342                let wrapper = json!({
343                    "type": "object",
344                    "properties": properties,
345                    "required": required,
346                    "additionalProperties": false
347                });
348                text.push_str("\n\n");
349                text.push_str(&adapter.instructions(sizes));
350                text.push_str(&format!(
351                    " Answer with JSON only, in this shape: {}.",
352                    if schema.is_some() {
353                        "{\"value\": <the answer>, \"regions\": [...]}"
354                    } else {
355                        "{\"text\": <the answer>, \"regions\": [...]}"
356                    }
357                ));
358                if adapter.structured_output() {
359                    config.response_schema = Some(wrapper);
360                }
361                adapter.configure(&mut config);
362            }
363            (_, adapter) => {
364                if let Some(value) = schema {
365                    config.response_schema = Some(value.clone());
366                    text.push_str("\n\nAnswer with JSON only.");
367                }
368                if let Some(adapter) = adapter {
369                    adapter.configure(&mut config);
370                }
371            }
372        }
373        let mut parts = images;
374        parts.push(Part::Text { text });
375        LlmRequest {
376            config: Some(config),
377            ..LlmRequest::new(self.llm.name(), vec![Content { role: "user".into(), parts }])
378        }
379    }
380
381    async fn run<T: VisionInput>(
382        &self,
383        cx: &VisionCx,
384        request: &DescribeRequest<T>,
385        part: impl Fn(&T) -> Result<Part>,
386    ) -> Result<Description<ImageRegion>> {
387        cx.check()?;
388        let adapter = match (request.want_regions, &self.adapter) {
389            (true, None) => {
390                return Err(VisionError::Unsupported(format!(
391                    "`{}` has no region adapter, so its regions would be in an unknown frame; \
392                     ask it for text and values, or give the describer a `RegionAdapter`",
393                    self.llm.name()
394                )));
395            }
396            (true, Some(adapter)) => Some(adapter.as_ref()),
397            (false, _) => None,
398        };
399        if request.images.is_empty() {
400            return Err(VisionError::InvalidInput("describe needs at least one image".into()));
401        }
402        let sizes: Vec<(u32, u32)> = request.images.iter().map(|i| i.sent().size()).collect();
403        let images = request.images.iter().map(&part).collect::<Result<Vec<_>>>()?;
404        let llm_request = self.build_request(
405            images,
406            &sizes,
407            &request.prompt,
408            request.output_schema.as_ref(),
409            request.want_regions,
410            request.max_output_tokens,
411        );
412        let preflight =
413            Preflight::estimate(self.llm.name(), &llm_request, self.adapter.as_deref(), &sizes);
414        let bound = preflight.max_cost_micro_usd.or(self.unpriced_hold);
415        let model = Preflighted::new(Arc::clone(&self.llm), bound);
416        let mut stream = cx.scope().generate(&model, llm_request, false).await?;
417        let mut text = String::new();
418        let mut partial = String::new();
419        let mut finish = None;
420        while let Some(response) = stream.next().await {
421            let response = response?;
422            if response.finish_reason.is_some() {
423                finish = response.finish_reason;
424            }
425            let target = if response.partial { &mut partial } else { &mut text };
426            for p in response.content.iter().flat_map(|c| c.parts.iter()) {
427                if let Part::Text { text } = p {
428                    target.push_str(text);
429                }
430            }
431        }
432        if text.is_empty() {
433            text = partial;
434        }
435        let backend = self.descriptor.id.to_string();
436        match finish {
437            Some(FinishReason::Refusal | FinishReason::Safety) => {
438                return Err(VisionError::Backend {
439                    backend,
440                    message: format!("the model declined to answer ({finish:?}): {text}"),
441                });
442            }
443            Some(FinishReason::MaxTokens) if text.trim().is_empty() => {
444                return Err(VisionError::Backend {
445                    backend,
446                    message: "the answer was empty at the output cap; raise \
447                              `max_output_tokens` or lower the model's reasoning"
448                        .into(),
449                });
450            }
451            _ => {}
452        }
453        parse_answer(&backend, &text, adapter, request.output_schema.is_some(), &sizes)
454    }
455}
456
457/// Reads a model's text into a description.
458fn parse_answer(
459    backend: &str,
460    text: &str,
461    adapter: Option<&dyn RegionAdapter>,
462    has_schema: bool,
463    sizes: &[(u32, u32)],
464) -> Result<Description<ImageRegion>> {
465    let parse = |message: String| VisionError::Parse { backend: backend.to_string(), message };
466    let Some(adapter) = adapter else {
467        if has_schema {
468            let value = extract_json(text)
469                .ok_or_else(|| parse(format!("the answer holds no JSON value: {text}")))?;
470            return Ok(Description { value: Some(value), ..Description::default() });
471        }
472        return Ok(Description { text: Some(text.to_string()), ..Description::default() });
473    };
474    let root =
475        extract_json(text).ok_or_else(|| parse(format!("the answer holds no JSON: {text}")))?;
476    let (items, answer) = match &root {
477        Value::Array(items) => (items.clone(), None),
478        Value::Object(fields) => {
479            let items = ["regions", "objects", "boxes"]
480                .iter()
481                .find_map(|k| fields.get(*k)?.as_array().cloned())
482                .ok_or_else(|| parse(format!("the answer has no `regions` list: {root}")))?;
483            let answer = if has_schema { fields.get("value") } else { fields.get("text") };
484            (items, answer.cloned())
485        }
486        other => return Err(parse(format!("the answer is not an object: {other}"))),
487    };
488    let mut regions = Vec::with_capacity(items.len());
489    for item in &items {
490        if let Some(region) = adapter.parse_region(item, sizes).map_err(&parse)? {
491            regions.push(region);
492        }
493    }
494    let mut description = Description { regions, ..Description::default() };
495    match (has_schema, answer) {
496        (true, value) => description.value = value,
497        (false, Some(Value::String(s))) => description.text = Some(s),
498        (false, Some(other)) => description.text = Some(other.to_string()),
499        (false, None) => {}
500    }
501    Ok(description)
502}
503
504fn released_part(image: &ReleasedImage) -> Result<Part> {
505    check_inline(image.bytes().len(), image.receipt().backend.as_str())?;
506    Ok(image.to_part())
507}
508
509fn sent_part(image: &SentImage) -> Result<Part> {
510    let bytes = image.encode_png()?;
511    check_inline(bytes.len(), "local describer")?;
512    Ok(Part::InlineData {
513        mime_type: "image/png".into(),
514        data: bytes,
515        uri: None,
516        annotations: None,
517    })
518}
519
520fn check_inline(len: usize, backend: &str) -> Result<()> {
521    if len > adk_core::MAX_INLINE_DATA_SIZE {
522        return Err(VisionError::InputTooLarge {
523            backend: backend.to_string(),
524            limit: format!("{} bytes inline", adk_core::MAX_INLINE_DATA_SIZE),
525            actual: format!("{len} bytes"),
526        });
527    }
528    Ok(())
529}
530
531#[async_trait]
532impl Describer<ReleasedImage> for LlmDescriber<ReleasedImage> {
533    fn descriptor(&self) -> &BackendDescriptor {
534        &self.descriptor
535    }
536
537    async fn describe(
538        &self,
539        cx: &VisionCx,
540        request: &DescribeRequest<ReleasedImage>,
541    ) -> Result<Description<ImageRegion>> {
542        if let Some(other) = request.images.iter().find(|i| !i.is_for(&self.descriptor.id)) {
543            return Err(VisionError::NotReleased {
544                backend: format!(
545                    "{} (the image was released to `{}`)",
546                    self.descriptor.id,
547                    other.receipt().backend
548                ),
549            });
550        }
551        self.run(cx, request, released_part).await
552    }
553}
554
555#[async_trait]
556impl Describer<SentImage> for LlmDescriber<SentImage> {
557    fn descriptor(&self) -> &BackendDescriptor {
558        &self.descriptor
559    }
560
561    async fn describe(
562        &self,
563        cx: &VisionCx,
564        request: &DescribeRequest<SentImage>,
565    ) -> Result<Description<ImageRegion>> {
566        self.run(cx, request, sent_part).await
567    }
568}
569
570#[cfg(test)]
571mod tests {
572    use super::*;
573    use crate::cloud::{ClaudePixels, GeminiBox2d};
574    use crate::geometry::{BBox, Shape};
575
576    #[test]
577    fn answers_are_read_with_the_adapter() {
578        let claude = ClaudePixels::for_model("claude-sonnet-5-5");
579        let text = r#"{"text": "two boxes", "regions": [
580            {"label": "red", "box": [100, 80, 260, 200]},
581            {"label": "blue", "box": [380, 260, 560, 420]}]}"#;
582        let d = parse_answer("c", text, Some(&claude), false, &[(640, 480)]).unwrap();
583        assert_eq!(d.text.as_deref(), Some("two boxes"));
584        assert_eq!(d.regions.len(), 2);
585        assert_eq!(d.regions[1].region.shape, Shape::Box(BBox::new(380.0, 260.0, 560.0, 420.0)));
586    }
587
588    #[test]
589    fn values_and_regions_come_back_together() {
590        let gemini = GeminiBox2d::for_model("gemini-3.8-flash");
591        let text = r#"```json
592{"value": {"kind": "invoice"}, "regions": [{"label": "total", "box_2d": [1, 2, 3, 4]}]}
593```"#;
594        let d = parse_answer("g", text, Some(&gemini), true, &[(10, 10)]).unwrap();
595        assert_eq!(d.value, Some(json!({"kind": "invoice"})));
596        assert_eq!(d.regions.len(), 1);
597    }
598
599    #[test]
600    fn a_malformed_answer_is_refused() {
601        let claude = ClaudePixels::for_model("claude-sonnet-5-5");
602        for text in [
603            "I cannot see any boxes.",
604            r#"{"text": "x"}"#,
605            r#"{"text": "x", "regions": [{"label": "a", "box": [1, 2]}]}"#,
606        ] {
607            let err = parse_answer("c", text, Some(&claude), false, &[(10, 10)]).unwrap_err();
608            assert!(matches!(err, VisionError::Parse { .. }), "{text}: {err}");
609        }
610    }
611
612    #[test]
613    fn text_without_an_adapter_is_the_answer() {
614        let d = parse_answer("m", "A receipt.", None, false, &[(10, 10)]).unwrap();
615        assert_eq!(d.text.as_deref(), Some("A receipt."));
616    }
617}