Skip to main content

gadk_model/
llm.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! The [`Llm`] trait and its request/response types.
17
18use std::any::Any;
19use std::collections::HashMap;
20use std::fmt;
21use std::sync::Arc;
22use std::time::Duration;
23
24use futures::future::BoxFuture;
25use futures::stream::BoxStream;
26use gadk_genai::serde_util::is_zero;
27use gadk_genai::{
28    CitationMetadata, Content, FinishReason, GenerateContentConfig,
29    GenerateContentResponseUsageMetadata, GroundingMetadata, LiveConnectConfig, LogprobsResult,
30    Transcription,
31};
32use serde::{Deserialize, Serialize};
33use serde_json::Value;
34
35use crate::error::ModelError;
36use crate::live::LiveConnection;
37
38/// Which Google backend serves a model; an unspecified backend is represented as `None`.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40pub enum Backend {
41    /// The Gemini Developer API.
42    GeminiApi,
43    /// Vertex AI.
44    VertexAi,
45}
46
47/// Access to an underlying LLM.
48pub trait Llm: Send + Sync {
49    /// The model name.
50    fn name(&self) -> &str;
51
52    /// Generates content for `req`. With `stream == false` the stream yields one final
53    /// response; with `stream == true` it yields partial responses followed by the final one.
54    fn generate_content(
55        &self,
56        req: LlmRequest,
57        stream: bool,
58    ) -> BoxStream<'static, Result<LlmResponse, ModelError>>;
59
60    /// The Google backend variant, for Google models.
61    fn google_variant(&self) -> Option<Backend> {
62        None
63    }
64
65    /// Opens a live (bidi streaming) connection. Models without live support keep this default,
66    /// which fails with `model does not support live connection`.
67    fn connect_live<'a>(
68        &'a self,
69        cfg: LiveConnectConfig,
70    ) -> BoxFuture<'a, Result<Box<dyn LiveConnection>, ModelError>> {
71        let _ = cfg;
72        Box::pin(async {
73            Err(ModelError::Other(
74                "model does not support live connection".into(),
75            ))
76        })
77    }
78
79    /// Downcasting support: lets a holder of `Arc<dyn Llm>` reach the concrete model
80    /// (for example to open a Live connection on a Gemini model). Implementations return
81    /// `self`.
82    fn as_any(&self) -> &dyn Any;
83}
84
85/// Hook that may add or rewrite fields of the outgoing JSON request body.
86pub type ExtrasRequestProvider =
87    Arc<dyn Fn(serde_json::Map<String, Value>) -> serde_json::Map<String, Value> + Send + Sync>;
88
89/// Per-request HTTP options.
90///
91/// The `Debug` output lists header names only; header values are redacted.
92#[derive(Clone, Default)]
93pub struct HttpOptions {
94    /// Overrides the backend base URL.
95    pub base_url: Option<String>,
96    /// Overrides the API version (e.g. `v1beta`).
97    pub api_version: Option<String>,
98    /// Extra headers sent with the request.
99    pub headers: http::HeaderMap,
100    /// Request timeout.
101    pub timeout: Option<Duration>,
102    /// Hook applied to the JSON request body before sending.
103    pub extras_request_provider: Option<ExtrasRequestProvider>,
104}
105
106impl fmt::Debug for HttpOptions {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        f.debug_struct("HttpOptions")
109            .field("base_url", &self.base_url)
110            .field("api_version", &self.api_version)
111            .field("headers", &RedactedHeaders(&self.headers))
112            .field("timeout", &self.timeout)
113            .field(
114                "extras_request_provider",
115                &self.extras_request_provider.as_ref().map(|_| "<fn>"),
116            )
117            .finish()
118    }
119}
120
121/// Debug view of a header map that prints each header name with its value redacted, so
122/// credentials passed as headers never reach logs.
123struct RedactedHeaders<'a>(&'a http::HeaderMap);
124
125impl fmt::Debug for RedactedHeaders<'_> {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        f.debug_map()
128            .entries(self.0.keys().map(|k| (k.as_str(), "<redacted>")))
129            .finish()
130    }
131}
132
133/// The raw LLM request.
134#[derive(Clone, Default)]
135pub struct LlmRequest {
136    /// The model name.
137    pub model: String,
138    /// The conversation contents.
139    pub contents: Vec<Content>,
140    /// Generation config.
141    pub config: Option<GenerateContentConfig>,
142    /// HTTP options for this request.
143    pub http_options: Option<HttpOptions>,
144    /// Tools available to this request, keyed by name (not serialized).
145    pub tools: HashMap<String, Arc<dyn Any + Send + Sync>>,
146}
147
148impl fmt::Debug for LlmRequest {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        let mut tool_names: Vec<&String> = self.tools.keys().collect();
151        tool_names.sort();
152        f.debug_struct("LlmRequest")
153            .field("model", &self.model)
154            .field("contents", &self.contents)
155            .field("config", &self.config)
156            .field("http_options", &self.http_options)
157            .field("tools", &tool_names)
158            .finish()
159    }
160}
161
162/// The raw LLM response.
163/// It provides the first candidate response from the model if available.
164#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
165#[serde(rename_all = "camelCase")]
166pub struct LlmResponse {
167    /// Content of the first candidate.
168    #[serde(default, skip_serializing_if = "Option::is_none")]
169    pub content: Option<Content>,
170    /// Citation metadata.
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub citation_metadata: Option<CitationMetadata>,
173    /// Grounding metadata.
174    #[serde(default, skip_serializing_if = "Option::is_none")]
175    pub grounding_metadata: Option<GroundingMetadata>,
176    /// Usage metadata.
177    #[serde(default, skip_serializing_if = "Option::is_none")]
178    pub usage_metadata: Option<GenerateContentResponseUsageMetadata>,
179    /// Arbitrary caller metadata.
180    #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
181    pub custom_metadata: serde_json::Map<String, Value>,
182    /// Log-probability results.
183    #[serde(default, skip_serializing_if = "Option::is_none")]
184    pub logprobs_result: Option<LogprobsResult>,
185    /// Transcription of audio input (live).
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub input_transcription: Option<Transcription>,
188    /// Transcription of audio output (live).
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub output_transcription: Option<Transcription>,
191    /// Model version that produced the response.
192    #[serde(default, skip_serializing_if = "is_zero")]
193    pub model_version: String,
194    /// Whether the content is part of an unfinished content stream.
195    #[serde(default, skip_serializing_if = "is_zero")]
196    pub partial: bool,
197    /// Whether the response from the model is complete (streaming only).
198    #[serde(default, skip_serializing_if = "is_zero")]
199    pub turn_complete: bool,
200    /// Whether the LLM was interrupted while generating.
201    #[serde(default, skip_serializing_if = "is_zero")]
202    pub interrupted: bool,
203    /// Live session resumption handle.
204    #[serde(default, skip_serializing_if = "is_zero")]
205    pub session_resumption_handle: String,
206    /// Error code, if any.
207    #[serde(default, skip_serializing_if = "is_zero")]
208    pub error_code: String,
209    /// Error message, if any.
210    #[serde(default, skip_serializing_if = "is_zero")]
211    pub error_message: String,
212    /// Finish reason of the first candidate.
213    #[serde(default, skip_serializing_if = "Option::is_none")]
214    pub finish_reason: Option<FinishReason>,
215    /// Average log probability of the first candidate.
216    #[serde(default, skip_serializing_if = "is_zero")]
217    pub avg_logprobs: f64,
218}