1pub 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
21pub trait TokenProvider: Send + Sync {
26 fn token(&self) -> String;
29}
30
31pub 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
40pub struct GcloudTokenProvider {
43 cache: parking_lot::Mutex<(String, std::time::Instant)>,
44 ttl: std::time::Duration,
45}
46
47impl GcloudTokenProvider {
48 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 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 std::env::var("GOOGLE_ACCESS_TOKEN").unwrap_or_default()
78 }
79 }
80 }
81}
82
83#[derive(Debug, Clone, Default, Serialize, Deserialize)]
89pub struct LlmRequest {
90 pub contents: Vec<Content>,
92 #[serde(skip_serializing_if = "Option::is_none")]
95 pub model: Option<String>,
96 #[serde(skip_serializing_if = "Option::is_none")]
98 pub system_instruction: Option<String>,
99 #[serde(skip_serializing_if = "Vec::is_empty", default)]
101 pub tools: Vec<Tool>,
102 #[serde(skip_serializing_if = "Option::is_none")]
104 pub temperature: Option<f32>,
105 #[serde(skip_serializing_if = "Option::is_none")]
107 pub max_output_tokens: Option<u32>,
108 #[serde(skip_serializing_if = "Option::is_none")]
110 pub top_p: Option<f32>,
111 #[serde(skip_serializing_if = "Option::is_none")]
113 pub top_k: Option<u32>,
114 #[serde(skip_serializing_if = "Vec::is_empty", default)]
116 pub stop_sequences: Vec<String>,
117 #[serde(skip_serializing_if = "Option::is_none")]
119 pub thinking_budget: Option<u32>,
120 #[serde(skip_serializing_if = "Option::is_none")]
122 pub response_mime_type: Option<String>,
123 #[serde(skip_serializing_if = "Option::is_none")]
125 pub response_json_schema: Option<serde_json::Value>,
126}
127
128impl LlmRequest {
129 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 pub fn from_contents(contents: Vec<Content>) -> Self {
142 Self {
143 contents,
144 ..Default::default()
145 }
146 }
147}
148
149#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct LlmResponse {
152 pub content: Content,
154 #[serde(skip_serializing_if = "Option::is_none")]
156 pub finish_reason: Option<String>,
157 #[serde(skip_serializing_if = "Option::is_none")]
159 pub usage: Option<TokenUsage>,
160}
161
162impl LlmResponse {
163 pub fn from_text(text: impl Into<String>) -> Self {
165 Self::from_parts(vec![Part::Text { text: text.into() }], Some("STOP"))
166 }
167
168 pub fn tool_call(name: impl Into<String>, args: serde_json::Value) -> Self {
170 Self::tool_calls([(name, args)])
171 }
172
173 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 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 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 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 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
254pub struct TokenUsage {
255 pub prompt_tokens: u32,
257 pub completion_tokens: u32,
259 pub total_tokens: u32,
261}
262
263impl TokenUsage {
264 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#[derive(Debug, thiserror::Error)]
307#[non_exhaustive]
308pub enum LlmError {
309 #[error("the model API returned HTTP {status}: {message}")]
311 Api {
312 status: u16,
314 message: String,
316 },
317 #[error("{0}")]
319 Auth(String),
320 #[error("could not reach the model API: {0}")]
322 Transport(String),
323 #[error("{0}")]
326 Config(String),
327 #[error("LLM request failed: {0}")]
329 RequestFailed(String),
330 #[error("Model not available: {0}")]
332 ModelNotAvailable(String),
333 #[error("Rate limited")]
335 RateLimited,
336 #[error("blocked by content safety: {0}")]
339 ContentFiltered(String),
340 #[error("{0}")]
342 Other(String),
343}
344
345impl LlmError {
346 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 pub fn is_rate_limited(&self) -> bool {
357 self.status() == Some(429)
358 }
359
360 pub fn is_auth(&self) -> bool {
362 matches!(self, Self::Auth(_)) || matches!(self.status(), Some(401 | 403))
363 }
364
365 pub fn is_content_filtered(&self) -> bool {
367 matches!(self, Self::ContentFiltered(_))
368 }
369
370 pub fn is_retryable(&self) -> bool {
374 matches!(self, Self::Transport(_)) || matches!(self.status(), Some(429 | 500..=599))
375 }
376}
377
378#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
381pub struct ModelCapabilities {
382 pub thinking: bool,
384 pub live_bidi: bool,
386 pub audio_output: bool,
388 pub vision_input: bool,
390 pub context_caching: bool,
392}
393
394impl ModelCapabilities {
395 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
411pub type LlmStream = futures_util::stream::BoxStream<'static, Result<LlmResponse, LlmError>>;
413
414#[async_trait]
418pub trait BaseLlm: Send + Sync {
419 fn model_id(&self) -> &str;
421
422 fn capabilities(&self) -> ModelCapabilities {
428 ModelCapabilities::infer_from_id(self.model_id())
429 }
430
431 async fn generate(&self, request: LlmRequest) -> Result<LlmResponse, LlmError>;
433
434 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 async fn warm_up(&self) -> Result<(), LlmError> {
451 Ok(())
452 }
453}
454
455#[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#[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 #[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}