Skip to main content

gemini_adk_rs/llm/
mod.rs

1//! LLM abstraction — decouples agents from specific model providers.
2//!
3//! The `BaseLlm` trait provides a unified interface for generating content
4//! from any LLM. The `GeminiLlm` implementation wraps gemini-live's `Client`
5//! for Gemini models.
6
7pub mod gemini;
8mod mock;
9pub mod registry;
10
11pub use gemini::{GeminiLlm, GeminiLlmParams};
12pub use mock::MockLlm;
13pub use registry::LlmRegistry;
14
15use async_trait::async_trait;
16use futures_util::StreamExt;
17use serde::{Deserialize, Serialize};
18
19use gemini_genai_rs::prelude::{Content, Part, Tool};
20
21/// Provides access tokens for VertexAI authentication.
22///
23/// Implement this trait to supply dynamically refreshed tokens.
24/// The default implementation reads `GOOGLE_ACCESS_TOKEN` from the environment.
25pub trait TokenProvider: Send + Sync {
26    /// Return a valid access token. Called before each `generate()` request
27    /// when using VertexAI variant.
28    fn token(&self) -> String;
29}
30
31/// Default token provider — reads `GOOGLE_ACCESS_TOKEN` from environment.
32pub struct EnvTokenProvider;
33
34impl TokenProvider for EnvTokenProvider {
35    fn token(&self) -> String {
36        std::env::var("GOOGLE_ACCESS_TOKEN").unwrap_or_default()
37    }
38}
39
40/// Token provider that shells out to `gcloud auth print-access-token`,
41/// caching the result with a configurable TTL.
42pub struct GcloudTokenProvider {
43    cache: parking_lot::Mutex<(String, std::time::Instant)>,
44    ttl: std::time::Duration,
45}
46
47impl GcloudTokenProvider {
48    /// Create a new provider with the given cache TTL (recommended: 45 minutes).
49    pub fn new(ttl: std::time::Duration) -> Self {
50        Self {
51            cache: parking_lot::Mutex::new((String::new(), std::time::Instant::now())),
52            ttl,
53        }
54    }
55}
56
57impl TokenProvider for GcloudTokenProvider {
58    fn token(&self) -> String {
59        let mut guard = self.cache.lock();
60        let (ref mut cached_token, ref mut fetched_at) = *guard;
61        if !cached_token.is_empty() && fetched_at.elapsed() < self.ttl {
62            return cached_token.clone();
63        }
64        // Shell out to gcloud
65        match std::process::Command::new("gcloud")
66            .args(["auth", "print-access-token"])
67            .output()
68        {
69            Ok(output) if output.status.success() => {
70                let token = String::from_utf8_lossy(&output.stdout).trim().to_string();
71                *cached_token = token.clone();
72                *fetched_at = std::time::Instant::now();
73                token
74            }
75            _ => {
76                // Fall back to env var
77                std::env::var("GOOGLE_ACCESS_TOKEN").unwrap_or_default()
78            }
79        }
80    }
81}
82
83/// Configuration for an LLM generation request.
84///
85/// Every field a provider can honour is here, and [`GeminiLlm`] sends every
86/// one of them. New fields may be added; build requests with
87/// `..Default::default()` or [`LlmRequest::from_text`].
88#[derive(Debug, Clone, Default, Serialize, Deserialize)]
89pub struct LlmRequest {
90    /// The messages/contents to send.
91    pub contents: Vec<Content>,
92    /// The model for this request, overriding the provider's default model
93    /// (e.g. `"gemini-2.5-pro"`). `None` uses [`BaseLlm::model_id`].
94    #[serde(skip_serializing_if = "Option::is_none")]
95    pub model: Option<String>,
96    /// System instruction.
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub system_instruction: Option<String>,
99    /// Available tools.
100    #[serde(skip_serializing_if = "Vec::is_empty", default)]
101    pub tools: Vec<Tool>,
102    /// Temperature for generation.
103    #[serde(skip_serializing_if = "Option::is_none")]
104    pub temperature: Option<f32>,
105    /// Maximum output tokens.
106    #[serde(skip_serializing_if = "Option::is_none")]
107    pub max_output_tokens: Option<u32>,
108    /// Nucleus sampling threshold.
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub top_p: Option<f32>,
111    /// Number of highest-probability tokens to sample from.
112    #[serde(skip_serializing_if = "Option::is_none")]
113    pub top_k: Option<u32>,
114    /// Strings that end generation when produced.
115    #[serde(skip_serializing_if = "Vec::is_empty", default)]
116    pub stop_sequences: Vec<String>,
117    /// Token budget for the model's thinking, on models that think.
118    #[serde(skip_serializing_if = "Option::is_none")]
119    pub thinking_budget: Option<u32>,
120    /// MIME type for structured output (e.g., `"application/json"`).
121    #[serde(skip_serializing_if = "Option::is_none")]
122    pub response_mime_type: Option<String>,
123    /// JSON Schema for structured output. Requires `response_mime_type = "application/json"`.
124    #[serde(skip_serializing_if = "Option::is_none")]
125    pub response_json_schema: Option<serde_json::Value>,
126}
127
128impl LlmRequest {
129    /// Create a request from a single user message.
130    pub fn from_text(text: impl Into<String>) -> Self {
131        Self {
132            contents: vec![Content {
133                role: Some(gemini_genai_rs::prelude::Role::User),
134                parts: vec![Part::Text { text: text.into() }],
135            }],
136            ..Default::default()
137        }
138    }
139
140    /// Create a request from existing contents.
141    pub fn from_contents(contents: Vec<Content>) -> Self {
142        Self {
143            contents,
144            ..Default::default()
145        }
146    }
147}
148
149/// The response from an LLM generation request.
150#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct LlmResponse {
152    /// The generated content.
153    pub content: Content,
154    /// Finish reason (if available).
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub finish_reason: Option<String>,
157    /// Token usage (if available).
158    #[serde(skip_serializing_if = "Option::is_none")]
159    pub usage: Option<TokenUsage>,
160}
161
162impl LlmResponse {
163    /// A model turn that says `text` and finishes.
164    pub fn from_text(text: impl Into<String>) -> Self {
165        Self::from_parts(vec![Part::Text { text: text.into() }], Some("STOP"))
166    }
167
168    /// A model turn that calls one tool.
169    pub fn tool_call(name: impl Into<String>, args: serde_json::Value) -> Self {
170        Self::tool_calls([(name, args)])
171    }
172
173    /// A model turn that calls several tools at once, in order.
174    pub fn tool_calls<N: Into<String>>(
175        calls: impl IntoIterator<Item = (N, serde_json::Value)>,
176    ) -> Self {
177        let parts = calls
178            .into_iter()
179            .map(|(name, args)| Part::FunctionCall {
180                function_call: gemini_genai_rs::prelude::FunctionCall {
181                    name: name.into(),
182                    args,
183                    id: None,
184                    thought_signature: None,
185                },
186            })
187            .collect();
188        Self::from_parts(parts, None)
189    }
190
191    fn from_parts(parts: Vec<Part>, finish_reason: Option<&str>) -> Self {
192        Self {
193            content: Content {
194                role: Some(gemini_genai_rs::prelude::Role::Model),
195                parts,
196            },
197            finish_reason: finish_reason.map(str::to_owned),
198            usage: None,
199        }
200    }
201
202    /// Add a streamed chunk to this response: its parts are appended (adjacent
203    /// text merged), and its finish reason and usage, when present, replace
204    /// these — a provider's streamed usage is cumulative.
205    pub fn append(&mut self, chunk: LlmResponse) {
206        for part in chunk.content.parts {
207            match (self.content.parts.last_mut(), part) {
208                (Some(Part::Text { text }), Part::Text { text: more }) => text.push_str(&more),
209                (_, part) => self.content.parts.push(part),
210            }
211        }
212        if chunk.finish_reason.is_some() {
213            self.finish_reason = chunk.finish_reason;
214        }
215        if chunk.usage.is_some() {
216            self.usage = chunk.usage;
217        }
218    }
219
220    /// Attach token usage, as a provider reports it.
221    pub fn with_usage(mut self, prompt_tokens: u32, completion_tokens: u32) -> Self {
222        self.usage = Some(TokenUsage::new(prompt_tokens, completion_tokens));
223        self
224    }
225
226    /// Extract text from the response, concatenating all text parts.
227    pub fn text(&self) -> String {
228        self.content
229            .parts
230            .iter()
231            .filter_map(|p| match p {
232                Part::Text { text } => Some(text.as_str()),
233                _ => None,
234            })
235            .collect::<Vec<_>>()
236            .join("")
237    }
238
239    /// Extract function calls from the response.
240    pub fn function_calls(&self) -> Vec<&gemini_genai_rs::prelude::FunctionCall> {
241        self.content
242            .parts
243            .iter()
244            .filter_map(|p| match p {
245                Part::FunctionCall { function_call } => Some(function_call),
246                _ => None,
247            })
248            .collect()
249    }
250}
251
252/// Token usage statistics.
253#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
254pub struct TokenUsage {
255    /// Input/prompt tokens.
256    pub prompt_tokens: u32,
257    /// Output/completion tokens.
258    pub completion_tokens: u32,
259    /// Total tokens.
260    pub total_tokens: u32,
261}
262
263impl TokenUsage {
264    /// Usage for one call; the total is the sum of the two.
265    pub fn new(prompt_tokens: u32, completion_tokens: u32) -> Self {
266        Self {
267            prompt_tokens,
268            completion_tokens,
269            total_tokens: prompt_tokens.saturating_add(completion_tokens),
270        }
271    }
272}
273
274impl std::ops::Add for TokenUsage {
275    type Output = Self;
276
277    fn add(self, other: Self) -> Self {
278        Self {
279            prompt_tokens: self.prompt_tokens.saturating_add(other.prompt_tokens),
280            completion_tokens: self
281                .completion_tokens
282                .saturating_add(other.completion_tokens),
283            total_tokens: self.total_tokens.saturating_add(other.total_tokens),
284        }
285    }
286}
287
288impl std::ops::AddAssign for TokenUsage {
289    fn add_assign(&mut self, other: Self) {
290        *self = *self + other;
291    }
292}
293
294/// Errors from LLM operations.
295///
296/// Errors keep what the provider said — the HTTP status, the reason content
297/// was blocked — so a caller can decide what to do without parsing a message:
298///
299/// ```
300/// use gemini_adk_rs::llm::LlmError;
301///
302/// let err = LlmError::Api { status: 429, message: "quota exceeded".into() };
303/// assert!(err.is_rate_limited() && err.is_retryable());
304/// assert_eq!(err.status(), Some(429));
305/// ```
306#[derive(Debug, thiserror::Error)]
307#[non_exhaustive]
308pub enum LlmError {
309    /// The provider answered with an error status.
310    #[error("the model API returned HTTP {status}: {message}")]
311    Api {
312        /// The HTTP status code.
313        status: u16,
314        /// The provider's error message.
315        message: String,
316    },
317    /// Credentials are missing or were rejected. The message says how to fix it.
318    #[error("{0}")]
319    Auth(String),
320    /// The provider could not be reached: connection, TLS or timeout.
321    #[error("could not reach the model API: {0}")]
322    Transport(String),
323    /// The client is configured in a way no request can succeed with. The
324    /// message says what to change.
325    #[error("{0}")]
326    Config(String),
327    /// The HTTP request to the LLM API failed for another reason.
328    #[error("LLM request failed: {0}")]
329    RequestFailed(String),
330    /// The requested model is not available.
331    #[error("Model not available: {0}")]
332    ModelNotAvailable(String),
333    /// The request was rate-limited by the provider.
334    #[error("Rate limited")]
335    RateLimited,
336    /// The prompt or the reply was blocked by content safety; carries the
337    /// provider's reason (e.g. `"SAFETY"`, `"PROHIBITED_CONTENT"`).
338    #[error("blocked by content safety: {0}")]
339    ContentFiltered(String),
340    /// A catch-all for other LLM errors.
341    #[error("{0}")]
342    Other(String),
343}
344
345impl LlmError {
346    /// The HTTP status the provider answered with, when there was one.
347    pub fn status(&self) -> Option<u16> {
348        match self {
349            Self::Api { status, .. } => Some(*status),
350            Self::RateLimited => Some(429),
351            _ => None,
352        }
353    }
354
355    /// The provider is rate-limiting or out of quota (HTTP 429).
356    pub fn is_rate_limited(&self) -> bool {
357        self.status() == Some(429)
358    }
359
360    /// Credentials are missing, invalid or lack permission (HTTP 401/403).
361    pub fn is_auth(&self) -> bool {
362        matches!(self, Self::Auth(_)) || matches!(self.status(), Some(401 | 403))
363    }
364
365    /// The prompt or reply was blocked by content safety.
366    pub fn is_content_filtered(&self) -> bool {
367        matches!(self, Self::ContentFiltered(_))
368    }
369
370    /// Trying the same request again later may succeed: rate limits, server
371    /// errors (5xx) and transport failures. Auth, configuration, content
372    /// safety and other client errors will fail the same way again.
373    pub fn is_retryable(&self) -> bool {
374        matches!(self, Self::Transport(_)) || matches!(self.status(), Some(429 | 500..=599))
375    }
376}
377
378/// Capability declaration for a model — what callers may rely on without
379/// probing. See [`BaseLlm::capabilities`].
380#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
381pub struct ModelCapabilities {
382    /// Accepts a thinking budget / emits thought summaries.
383    pub thinking: bool,
384    /// Serves bidiGenerateContent (Live) sessions.
385    pub live_bidi: bool,
386    /// Produces native audio output.
387    pub audio_output: bool,
388    /// Accepts inline image/media parts in requests (vision).
389    pub vision_input: bool,
390    /// Honors cached-content references.
391    pub context_caching: bool,
392}
393
394impl ModelCapabilities {
395    /// Conservative inference from a model id string. Known family
396    /// substrings light up capabilities; unknown ids report text-only.
397    pub fn infer_from_id(id: &str) -> Self {
398        let id = id.to_ascii_lowercase();
399        let gemini = id.contains("gemini");
400        let live = id.contains("live") || id.contains("native-audio");
401        Self {
402            thinking: gemini && (id.contains("2.5") || id.contains("thinking")),
403            live_bidi: live,
404            audio_output: live || id.contains("tts"),
405            vision_input: gemini,
406            context_caching: gemini,
407        }
408    }
409}
410
411/// A reply streamed in chunks; see [`BaseLlm::generate_stream`].
412pub type LlmStream = futures_util::stream::BoxStream<'static, Result<LlmResponse, LlmError>>;
413
414/// Trait for LLM providers — decouples agents from specific models.
415///
416/// Implementations must be `Send + Sync` for use across async tasks.
417#[async_trait]
418pub trait BaseLlm: Send + Sync {
419    /// The model identifier (e.g., "gemini-2.5-flash").
420    fn model_id(&self) -> &str;
421
422    /// What this model supports — the ADK model-capability-declaration
423    /// pattern: the model states its capabilities instead of every caller
424    /// re-inferring them from the id string. The default derives a
425    /// conservative estimate from [`model_id`](Self::model_id); back-ends
426    /// with authoritative knowledge should override.
427    fn capabilities(&self) -> ModelCapabilities {
428        ModelCapabilities::infer_from_id(self.model_id())
429    }
430
431    /// Generate content from the LLM.
432    async fn generate(&self, request: LlmRequest) -> Result<LlmResponse, LlmError>;
433
434    /// Generate content as a stream of chunks, in the order the model
435    /// produced them. [`LlmResponse::append`] folds them into the whole reply;
436    /// usage, when a chunk carries it, is cumulative.
437    ///
438    /// The default yields [`generate`](Self::generate)'s reply as one chunk,
439    /// so every provider supports it; `GeminiLlm` streams for real.
440    async fn generate_stream(&self, request: LlmRequest) -> Result<LlmStream, LlmError> {
441        let response = self.generate(request).await?;
442        Ok(futures_util::stream::once(async move { Ok(response) }).boxed())
443    }
444
445    /// Pre-warm the HTTP connection pool to avoid cold-start latency.
446    ///
447    /// The default implementation is a no-op. `GeminiLlm` overrides this to
448    /// establish the TCP+TLS connection so the first real `generate()` call
449    /// doesn't pay the ~100-300ms handshake penalty.
450    async fn warm_up(&self) -> Result<(), LlmError> {
451        Ok(())
452    }
453}
454
455/// A shared model is a model, so `Arc<GeminiLlm>`, `Arc<dyn BaseLlm>` and a
456/// bare `GeminiLlm` are interchangeable wherever a [`BaseLlm`] is accepted.
457#[async_trait]
458impl<L: BaseLlm + ?Sized> BaseLlm for std::sync::Arc<L> {
459    fn model_id(&self) -> &str {
460        (**self).model_id()
461    }
462
463    fn capabilities(&self) -> ModelCapabilities {
464        (**self).capabilities()
465    }
466
467    async fn generate(&self, request: LlmRequest) -> Result<LlmResponse, LlmError> {
468        (**self).generate(request).await
469    }
470
471    async fn generate_stream(&self, request: LlmRequest) -> Result<LlmStream, LlmError> {
472        (**self).generate_stream(request).await
473    }
474
475    async fn warm_up(&self) -> Result<(), LlmError> {
476        (**self).warm_up().await
477    }
478}
479
480/// A boxed model is a model; see the `Arc` implementation.
481#[async_trait]
482impl<L: BaseLlm + ?Sized> BaseLlm for Box<L> {
483    fn model_id(&self) -> &str {
484        (**self).model_id()
485    }
486
487    fn capabilities(&self) -> ModelCapabilities {
488        (**self).capabilities()
489    }
490
491    async fn generate(&self, request: LlmRequest) -> Result<LlmResponse, LlmError> {
492        (**self).generate(request).await
493    }
494
495    async fn generate_stream(&self, request: LlmRequest) -> Result<LlmStream, LlmError> {
496        (**self).generate_stream(request).await
497    }
498
499    async fn warm_up(&self) -> Result<(), LlmError> {
500        (**self).warm_up().await
501    }
502}
503
504#[cfg(test)]
505mod tests {
506    use super::*;
507
508    #[test]
509    fn llm_request_from_text() {
510        let req = LlmRequest::from_text("Hello!");
511        assert_eq!(req.contents.len(), 1);
512        assert!(req.system_instruction.is_none());
513        assert!(req.tools.is_empty());
514    }
515
516    #[test]
517    fn llm_request_from_contents() {
518        let contents = vec![Content {
519            role: Some(gemini_genai_rs::prelude::Role::User),
520            parts: vec![Part::Text {
521                text: "Hello".into(),
522            }],
523        }];
524        let req = LlmRequest::from_contents(contents);
525        assert_eq!(req.contents.len(), 1);
526    }
527
528    #[test]
529    fn llm_response_text() {
530        let resp = LlmResponse {
531            content: Content {
532                role: Some(gemini_genai_rs::prelude::Role::Model),
533                parts: vec![
534                    Part::Text {
535                        text: "Hello ".into(),
536                    },
537                    Part::Text {
538                        text: "world!".into(),
539                    },
540                ],
541            },
542            finish_reason: Some("STOP".into()),
543            usage: None,
544        };
545        assert_eq!(resp.text(), "Hello world!");
546    }
547
548    #[test]
549    fn llm_response_function_calls() {
550        let resp = LlmResponse {
551            content: Content {
552                role: Some(gemini_genai_rs::prelude::Role::Model),
553                parts: vec![Part::FunctionCall {
554                    function_call: gemini_genai_rs::prelude::FunctionCall {
555                        name: "get_weather".into(),
556                        args: serde_json::json!({"city": "London"}),
557                        id: None,
558                        thought_signature: None,
559                    },
560                }],
561            },
562            finish_reason: None,
563            usage: None,
564        };
565        let calls = resp.function_calls();
566        assert_eq!(calls.len(), 1);
567        assert_eq!(calls[0].name, "get_weather");
568    }
569
570    #[test]
571    fn errors_classify_by_status_not_by_message() {
572        let api = |status| LlmError::Api {
573            status,
574            message: String::new(),
575        };
576        assert!(api(429).is_rate_limited() && api(429).is_retryable());
577        assert!(api(503).is_retryable() && !api(503).is_rate_limited());
578        assert!(api(401).is_auth() && api(403).is_auth() && !api(401).is_retryable());
579        assert!(!api(400).is_retryable() && !api(404).is_auth());
580        assert!(LlmError::Transport("reset".into()).is_retryable());
581        assert!(LlmError::RateLimited.is_rate_limited());
582        assert!(LlmError::Auth("no key".into()).is_auth());
583        assert!(LlmError::ContentFiltered("SAFETY".into()).is_content_filtered());
584        assert_eq!(api(418).status(), Some(418));
585        assert_eq!(LlmError::Other("x".into()).status(), None);
586    }
587
588    #[test]
589    fn append_folds_streamed_chunks_into_one_reply() {
590        let mut whole = LlmResponse::from_parts(vec![Part::Text { text: "Hel".into() }], None);
591        whole.append(LlmResponse::from_parts(
592            vec![Part::Text { text: "lo".into() }],
593            None,
594        ));
595        whole.append(LlmResponse::tool_call("f", serde_json::json!({})).with_usage(3, 1));
596        whole.append(LlmResponse::from_text("!").with_usage(3, 2));
597        assert_eq!(whole.text(), "Hello!");
598        assert_eq!(whole.function_calls().len(), 1);
599        assert_eq!(whole.finish_reason.as_deref(), Some("STOP"));
600        assert_eq!(
601            whole.usage,
602            Some(TokenUsage::new(3, 2)),
603            "usage is cumulative, not summed"
604        );
605    }
606
607    #[tokio::test]
608    async fn every_model_can_stream() {
609        let chunks: Vec<_> = MockLlm::text("one two three")
610            .generate_stream(LlmRequest::from_text("x"))
611            .await
612            .unwrap()
613            .map(Result::unwrap)
614            .collect()
615            .await;
616        assert_eq!(chunks.len(), 3, "the mock streams one word at a time");
617        let mut whole = chunks[0].clone();
618        for chunk in chunks.into_iter().skip(1) {
619            whole.append(chunk);
620        }
621        assert_eq!(whole.text(), "one two three");
622    }
623
624    #[test]
625    fn base_llm_is_object_safe() {
626        fn _assert(_: &dyn BaseLlm) {}
627    }
628
629    #[test]
630    fn token_usage() {
631        let usage = TokenUsage::new(10, 20);
632        assert_eq!(usage.total_tokens, 30);
633        assert_eq!((usage + TokenUsage::new(1, 2)).total_tokens, 33);
634    }
635
636    #[test]
637    fn response_constructors_build_model_turns() {
638        let said = LlmResponse::from_text("hi").with_usage(3, 4);
639        assert_eq!(said.text(), "hi");
640        assert_eq!(
641            said.content.role,
642            Some(gemini_genai_rs::prelude::Role::Model)
643        );
644        assert_eq!(said.finish_reason.as_deref(), Some("STOP"));
645        assert_eq!(said.usage, Some(TokenUsage::new(3, 4)));
646
647        let called = LlmResponse::tool_calls([
648            ("a", serde_json::json!({})),
649            ("b", serde_json::json!({ "x": 1 })),
650        ]);
651        let names: Vec<_> = called
652            .function_calls()
653            .iter()
654            .map(|c| c.name.as_str())
655            .collect();
656        assert_eq!(names, ["a", "b"]);
657        assert!(called.text().is_empty());
658    }
659
660    /// `Arc<L>`, `Arc<dyn BaseLlm>` and `Box<L>` all satisfy a generic bound,
661    /// so no call site needs to know which one it was handed.
662    #[tokio::test]
663    async fn shared_and_boxed_models_are_models() {
664        async fn ask(llm: impl BaseLlm) -> String {
665            llm.generate(LlmRequest::from_text("q"))
666                .await
667                .unwrap()
668                .text()
669        }
670        let mock = MockLlm::text("a").with_model_id("m");
671        let shared: std::sync::Arc<dyn BaseLlm> = std::sync::Arc::new(mock.clone());
672        assert_eq!(shared.model_id(), "m");
673        assert_eq!(ask(shared).await, "a");
674        assert_eq!(ask(std::sync::Arc::new(mock.clone())).await, "a");
675        assert_eq!(ask(Box::new(mock.clone()) as Box<dyn BaseLlm>).await, "a");
676        assert_eq!(mock.call_count(), 3);
677    }
678}