adk_core/model.rs
1use crate::schema_adapter::{GenericSchemaAdapter, SchemaAdapter};
2use crate::{Result, types::Content};
3use async_trait::async_trait;
4use futures::stream::Stream;
5use serde::{Deserialize, Serialize};
6use std::pin::Pin;
7
8/// A pinned, boxed stream of [`LlmResponse`] results from a model.
9pub type LlmResponseStream = Pin<Box<dyn Stream<Item = Result<LlmResponse>> + Send>>;
10
11/// The core trait for all LLM providers.
12///
13/// Implementations wrap a specific model API (Gemini, OpenAI, Anthropic, etc.)
14/// and produce a stream of responses for a given request.
15#[async_trait]
16pub trait Llm: Send + Sync {
17 /// Returns the model identifier (e.g., "gemini-3.8-flash").
18 fn name(&self) -> &str;
19 /// Generates content from the given request, optionally streaming.
20 async fn generate_content(&self, req: LlmRequest, stream: bool) -> Result<LlmResponseStream>;
21
22 /// Generates content with every provider call it makes metered against `scope`.
23 ///
24 /// [`ModelCallScope::generate`](crate::ModelCallScope::generate) calls this for every
25 /// metered call, after checking the scope's kill switches. The default meters the call as
26 /// one model call ([`ModelCallScope::generate_one_call`](crate::ModelCallScope::generate_one_call)):
27 /// one hold in the spend ledger, reserved under the vendor of `req.model`, and one model
28 /// call in the run budget.
29 ///
30 /// A model that sends one request to several providers, such as a fallback chain,
31 /// overrides it to call each of them through `scope.generate`, so every provider call is
32 /// reserved, counted and committed under the provider and model that served it. A
33 /// wrapper that only changes the request or the stream keeps the default and is metered
34 /// as one call.
35 ///
36 /// # Errors
37 ///
38 /// Returns what [`ModelCallScope::generate`](crate::ModelCallScope::generate) returns.
39 ///
40 /// # Example
41 ///
42 /// ```rust
43 /// use std::sync::Arc;
44 /// use adk_core::{
45 /// InMemorySpendLedger, Llm, LlmRequest, LlmResponseStream, ModelCallScope, SpendKey,
46 /// SpendLedger, SpendPeriod,
47 /// };
48 ///
49 /// struct Local;
50 ///
51 /// #[async_trait::async_trait]
52 /// impl Llm for Local {
53 /// fn name(&self) -> &str {
54 /// "gemini-local"
55 /// }
56 /// async fn generate_content(&self, _: LlmRequest, _: bool) -> adk_core::Result<LlmResponseStream> {
57 /// Ok(Box::pin(futures::stream::empty()))
58 /// }
59 /// }
60 ///
61 /// # futures::executor::block_on(async {
62 /// let ledger = Arc::new(InMemorySpendLedger::default());
63 /// let scope = ModelCallScope::new().with_spend_ledger(ledger.clone(), "acme");
64 /// // The default meters the call as one; a call with no response commits nothing.
65 /// let request = LlmRequest::new("gemini-local", vec![]);
66 /// let _ = Local.generate_content_metered(&scope, request, false).await?;
67 /// assert_eq!(ledger.spent(&SpendKey::org("acme"), SpendPeriod::Day).await?, 0);
68 /// # Ok::<(), adk_core::AdkError>(())
69 /// # }).unwrap();
70 /// ```
71 async fn generate_content_metered(
72 &self,
73 scope: &crate::ModelCallScope,
74 req: LlmRequest,
75 stream: bool,
76 ) -> Result<LlmResponseStream> {
77 scope.generate_one_call(self, req, stream).await
78 }
79
80 /// Returns the schema adapter for this provider.
81 ///
82 /// The schema adapter normalizes raw JSON Schema from MCP tools into the
83 /// format accepted by this provider's function-calling API.
84 ///
85 /// Default implementation returns [`GenericSchemaAdapter`], which applies
86 /// safe transforms suitable for most providers. Override this method to
87 /// return a provider-specific adapter (e.g., `GeminiSchemaAdapter`,
88 /// `OpenAiStrictSchemaAdapter`).
89 fn schema_adapter(&self) -> &dyn SchemaAdapter {
90 &GenericSchemaAdapter
91 }
92
93 /// Returns `true` if this model is configured to use a server-managed
94 /// environment (e.g., Gemini Interactions API) where the provider owns
95 /// the tool-calling loop and filesystem.
96 ///
97 /// This is used at agent build time to detect conflicts with client-side
98 /// sandbox tools that would produce competing filesystems.
99 ///
100 /// Default implementation returns `false`. Override in providers that
101 /// support server-managed environments.
102 fn uses_interactions_api(&self) -> bool {
103 false
104 }
105
106 /// Returns an upper bound, in micro-USD, on what `request` can cost on this model.
107 ///
108 /// The spend ledger reserves this amount before the call, so the call's committed
109 /// cost never exceeds its reservation and a hard cap is never overshot. Providers
110 /// derive it from the request's size, its output cap (or the model's maximum output),
111 /// and the highest per-token rate that can apply. `None` means the call cannot be
112 /// bounded — an unpriced model, or a request whose size is unknown; see
113 /// [`ModelCallScope`](crate::ModelCallScope) for how such calls are reserved.
114 ///
115 /// The default returns `None`. Wrappers forward to the model they wrap.
116 fn max_cost_micro_usd(&self, request: &LlmRequest) -> Option<u64> {
117 let _ = request;
118 None
119 }
120
121 /// The most tokens a request to this model may carry, as its provider documents it, if
122 /// known.
123 ///
124 /// Auto-compaction ([`IntraCompactionConfig`](crate::IntraCompactionConfig)) compacts an
125 /// agent's history before it nears this window. `adk-model` providers read it from the
126 /// pricing catalog, which records each vendor's published figure.
127 ///
128 /// The default returns `None`, which compacts at
129 /// [`DEFAULT_TOKEN_THRESHOLD`](crate::intra_compaction::DEFAULT_TOKEN_THRESHOLD).
130 /// Wrappers forward to the model they wrap.
131 ///
132 /// # Example
133 ///
134 /// ```rust
135 /// use adk_core::{Llm, LlmRequest, LlmResponseStream};
136 ///
137 /// struct Local;
138 ///
139 /// #[async_trait::async_trait]
140 /// impl Llm for Local {
141 /// fn name(&self) -> &str {
142 /// "local-8k"
143 /// }
144 /// async fn generate_content(&self, _: LlmRequest, _: bool) -> adk_core::Result<LlmResponseStream> {
145 /// unimplemented!()
146 /// }
147 /// fn context_window(&self) -> Option<u64> {
148 /// Some(8_192)
149 /// }
150 /// }
151 ///
152 /// assert_eq!(Local.context_window(), Some(8_192));
153 /// ```
154 fn context_window(&self) -> Option<u64> {
155 None
156 }
157
158 /// The provider-executed web search this model's transport serves, if any (spec 3.1
159 /// §7.20 "Provider-native search and fetch").
160 ///
161 /// Read from the client, never from the model's output: an agent that wants the
162 /// provider's search declares the built-in tool this names, and a model that returns
163 /// `None` gets web search only through a tool the application runs itself.
164 ///
165 /// The default returns `None`. Wrappers forward to the model they wrap.
166 ///
167 /// # Example
168 ///
169 /// ```rust
170 /// use adk_core::{Llm, LlmRequest, LlmResponseStream, NativeWebSearch, NativeWebSearchTool};
171 ///
172 /// struct Hosted;
173 ///
174 /// #[async_trait::async_trait]
175 /// impl Llm for Hosted {
176 /// fn name(&self) -> &str {
177 /// "hosted"
178 /// }
179 /// async fn generate_content(&self, _: LlmRequest, _: bool) -> adk_core::Result<LlmResponseStream> {
180 /// unimplemented!()
181 /// }
182 /// fn native_web_search(&self) -> Option<NativeWebSearch> {
183 /// Some(NativeWebSearch::new("anthropic", NativeWebSearchTool::AnthropicWebSearch, true))
184 /// }
185 /// }
186 ///
187 /// assert_eq!(Hosted.native_web_search().unwrap().provider, "anthropic");
188 /// ```
189 fn native_web_search(&self) -> Option<NativeWebSearch> {
190 None
191 }
192
193 /// The conversation compaction this model's provider performs itself, if any.
194 ///
195 /// The runner's auto-compaction asks such a model for the summary
196 /// ([`NativeCompactionRequest`](crate::intra_compaction::NativeCompactionRequest)) in place
197 /// of writing one with its own summarizer, and keeps the provider's signed result in the
198 /// history so the provider reads it back
199 /// ([`is_native_compaction`](crate::intra_compaction::is_native_compaction)).
200 ///
201 /// The default returns `None`. Wrappers forward to the model they wrap.
202 ///
203 /// # Example
204 ///
205 /// ```rust
206 /// use adk_core::{Llm, LlmRequest, LlmResponseStream, NativeCompaction};
207 ///
208 /// struct Hosted;
209 ///
210 /// #[async_trait::async_trait]
211 /// impl Llm for Hosted {
212 /// fn name(&self) -> &str {
213 /// "hosted"
214 /// }
215 /// async fn generate_content(&self, _: LlmRequest, _: bool) -> adk_core::Result<LlmResponseStream> {
216 /// unimplemented!()
217 /// }
218 /// fn native_compaction(&self) -> Option<NativeCompaction> {
219 /// Some(NativeCompaction::new("anthropic").keeping_thinking())
220 /// }
221 /// }
222 ///
223 /// assert!(Hosted.native_compaction().unwrap().keeps_thinking);
224 /// ```
225 fn native_compaction(&self) -> Option<NativeCompaction> {
226 None
227 }
228
229 /// Opens what the first call to this model would otherwise open, such as the pooled
230 /// TLS connection to the provider, so a turn that follows soon after starts on it.
231 ///
232 /// It sends no prompt and spends no tokens. What it opens lasts as long as the client
233 /// keeps an idle connection (90 seconds for `adk-anthropic`); call it again after that.
234 /// The default does nothing. Wrappers forward to the model they wrap.
235 ///
236 /// # Errors
237 ///
238 /// Returns the provider's error when it cannot be reached; a turn would meet the same
239 /// error, so a caller may log it and carry on.
240 ///
241 /// # Example
242 ///
243 /// ```rust
244 /// use adk_core::{Llm, LlmRequest, LlmResponseStream};
245 ///
246 /// struct Local;
247 ///
248 /// #[async_trait::async_trait]
249 /// impl Llm for Local {
250 /// fn name(&self) -> &str {
251 /// "local"
252 /// }
253 /// async fn generate_content(&self, _: LlmRequest, _: bool) -> adk_core::Result<LlmResponseStream> {
254 /// Ok(Box::pin(futures::stream::empty()))
255 /// }
256 /// }
257 ///
258 /// # futures::executor::block_on(async {
259 /// Local.prewarm().await?;
260 /// # Ok::<(), adk_core::AdkError>(())
261 /// # }).unwrap();
262 /// ```
263 async fn prewarm(&self) -> Result<()> {
264 Ok(())
265 }
266
267 /// Where a call's request data goes: into another machine ([`DataLocality::Remote`]),
268 /// to a server on this machine ([`DataLocality::Loopback`]), or nowhere outside this
269 /// process ([`DataLocality::InProcess`]).
270 ///
271 /// The image privacy guardrail reads it to tell which model calls leave the machine.
272 /// The default is `Remote`, so a model that does not say is treated as remote. Wrappers
273 /// forward the wrapped model's locality; a wrapper over several models answers the
274 /// least local of them ([`DataLocality::least_local`]).
275 ///
276 /// # Example
277 ///
278 /// ```rust
279 /// use adk_core::{DataLocality, Llm, LlmRequest, LlmResponseStream};
280 ///
281 /// struct OnDevice;
282 ///
283 /// #[async_trait::async_trait]
284 /// impl Llm for OnDevice {
285 /// fn name(&self) -> &str {
286 /// "qwen3-vl-2b"
287 /// }
288 /// async fn generate_content(&self, _: LlmRequest, _: bool) -> adk_core::Result<LlmResponseStream> {
289 /// Ok(Box::pin(futures::stream::empty()))
290 /// }
291 /// fn data_locality(&self) -> DataLocality {
292 /// DataLocality::InProcess
293 /// }
294 /// }
295 ///
296 /// assert_eq!(OnDevice.data_locality(), DataLocality::InProcess);
297 /// assert!(!OnDevice.data_locality().leaves_machine());
298 /// ```
299 fn data_locality(&self) -> DataLocality {
300 DataLocality::Remote
301 }
302
303 /// Where a call's request data is sent: each provider the model may call, by the id its
304 /// responses carry in [`LlmResponse::provider`], with the hosts its client connects to.
305 ///
306 /// `adk-model` providers answer from their configured endpoint, so a custom base URL, a
307 /// Vertex or Bedrock region, or an Azure resource names its own host. A loopback server
308 /// names its loopback host; [`data_locality`](Self::data_locality) says whether the data
309 /// leaves the machine. Image egress rules and the privacy guardrail read it to name the
310 /// hosts a remote model's images go to.
311 ///
312 /// The default returns none, meaning the destination is unknown. Wrappers forward to the
313 /// model they wrap; a wrapper over several models answers every model's destinations, or
314 /// none when any of them is unknown.
315 ///
316 /// # Example
317 ///
318 /// ```rust
319 /// use adk_core::{DataDestination, Llm, LlmRequest, LlmResponseStream};
320 ///
321 /// struct Hosted;
322 ///
323 /// #[async_trait::async_trait]
324 /// impl Llm for Hosted {
325 /// fn name(&self) -> &str {
326 /// "claude-sonnet-5-5"
327 /// }
328 /// async fn generate_content(&self, _: LlmRequest, _: bool) -> adk_core::Result<LlmResponseStream> {
329 /// unimplemented!()
330 /// }
331 /// fn data_destinations(&self) -> Vec<DataDestination> {
332 /// vec![DataDestination::of_url("anthropic", "https://api.anthropic.com/v1")]
333 /// }
334 /// }
335 ///
336 /// let destinations = Hosted.data_destinations();
337 /// assert_eq!(destinations[0].provider, "anthropic");
338 /// assert_eq!(destinations[0].hosts, ["api.anthropic.com"]);
339 /// ```
340 fn data_destinations(&self) -> Vec<DataDestination> {
341 Vec::new()
342 }
343}
344
345/// One provider a model sends request data to, and the hosts its client connects to.
346///
347/// Read from the client's configuration, never from a response: [`Llm::data_destinations`]
348/// returns one per provider a model may call.
349///
350/// # Example
351///
352/// ```rust
353/// use adk_core::DataDestination;
354///
355/// let vertex = DataDestination::of_url("gemini", "https://europe-west4-aiplatform.googleapis.com/v1");
356/// assert_eq!(vertex.hosts, ["europe-west4-aiplatform.googleapis.com"]);
357///
358/// let ollama = DataDestination::of_url("ollama", "http://localhost:11434");
359/// assert_eq!(ollama.hosts, ["localhost:11434"]);
360///
361/// assert!(DataDestination::of_url("openai", "not a url").hosts.is_empty());
362/// ```
363#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
364#[serde(rename_all = "camelCase")]
365#[non_exhaustive]
366pub struct DataDestination {
367 /// The provider's id, as its responses carry it in [`LlmResponse::provider`]:
368 /// `anthropic`, `gemini`, `openai`, `bedrock`, or the name an OpenAI-compatible client
369 /// is configured with.
370 pub provider: String,
371 /// The hosts request data is sent to, each as `host`, or `host:port` when the port is
372 /// not 443.
373 pub hosts: Vec<String>,
374}
375
376impl DataDestination {
377 /// A destination at `hosts`, each `host` or `host:port`.
378 pub fn new(
379 provider: impl Into<String>,
380 hosts: impl IntoIterator<Item = impl Into<String>>,
381 ) -> Self {
382 Self { provider: provider.into(), hosts: hosts.into_iter().map(Into::into).collect() }
383 }
384
385 /// The destination of a client whose endpoint is `url`: its host, with the port when
386 /// it is not 443. A URL that does not parse, or names no host, gives no host.
387 pub fn of_url(provider: impl Into<String>, url: &str) -> Self {
388 let host = url::Url::parse(url.trim()).ok().and_then(|parsed| {
389 let host = parsed.host_str()?.trim_end_matches('.').to_ascii_lowercase();
390 Some(match parsed.port_or_known_default() {
391 Some(443) | None => host,
392 Some(port) => format!("{host}:{port}"),
393 })
394 });
395 Self { provider: provider.into(), hosts: host.into_iter().collect() }
396 }
397
398 /// Every destination's hosts, in order and without repeats.
399 ///
400 /// # Example
401 ///
402 /// ```rust
403 /// use adk_core::DataDestination;
404 ///
405 /// let both = [
406 /// DataDestination::new("anthropic", ["api.anthropic.com"]),
407 /// DataDestination::new("gemini", ["generativelanguage.googleapis.com", "api.anthropic.com"]),
408 /// ];
409 /// assert_eq!(
410 /// DataDestination::all_hosts(&both),
411 /// ["api.anthropic.com", "generativelanguage.googleapis.com"]
412 /// );
413 /// ```
414 pub fn all_hosts(destinations: &[DataDestination]) -> Vec<String> {
415 let mut hosts: Vec<String> = Vec::new();
416 for host in destinations.iter().flat_map(|d| d.hosts.iter()) {
417 if !hosts.contains(host) {
418 hosts.push(host.clone());
419 }
420 }
421 hosts
422 }
423}
424
425/// Where a model call's request data goes, from most to least local.
426///
427/// Ordered by how far data travels, so the greater of two localities is the less local one.
428///
429/// | Locality | Request data | Example |
430/// |----------|--------------|---------|
431/// | [`InProcess`](Self::InProcess) | Stays in this process | `adk-mistralrs` models |
432/// | [`Loopback`](Self::Loopback) | Leaves the process for a server on this machine | Ollama or an OpenAI-compatible server at `localhost` |
433/// | [`Remote`](Self::Remote) | Leaves the machine | Every hosted provider |
434///
435/// A loopback server can itself forward a request elsewhere; `Loopback` says only that the
436/// framework sends it no further than this machine.
437///
438/// # Example
439///
440/// ```rust
441/// use adk_core::DataLocality;
442///
443/// assert_eq!(DataLocality::of_url("http://localhost:11434"), DataLocality::Loopback);
444/// assert_eq!(DataLocality::of_url("http://[::1]:8000/v1"), DataLocality::Loopback);
445/// assert_eq!(DataLocality::of_url("https://api.openai.com/v1"), DataLocality::Remote);
446/// assert_eq!(
447/// DataLocality::least_local([DataLocality::InProcess, DataLocality::Loopback]),
448/// DataLocality::Loopback
449/// );
450/// assert_eq!(serde_json::to_value(DataLocality::InProcess).unwrap(), "inProcess");
451/// ```
452#[derive(
453 Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
454)]
455#[serde(rename_all = "camelCase")]
456#[non_exhaustive]
457pub enum DataLocality {
458 /// The model runs in this process; request data never leaves it.
459 InProcess,
460 /// The model is served on this machine over the loopback interface.
461 Loopback,
462 /// The model is served by another machine; request data leaves this one.
463 #[default]
464 Remote,
465}
466
467impl DataLocality {
468 /// The locality of a server at `url`: [`Loopback`](Self::Loopback) when its host is
469 /// `localhost` or a loopback address (`127.0.0.0/8`, `::1`), otherwise
470 /// [`Remote`](Self::Remote). A URL that does not parse is `Remote`.
471 pub fn of_url(url: &str) -> Self {
472 let Ok(parsed) = url::Url::parse(url.trim()) else {
473 return Self::Remote;
474 };
475 let loopback = match parsed.host() {
476 Some(url::Host::Domain(domain)) => {
477 let domain = domain.trim_end_matches('.').to_ascii_lowercase();
478 domain == "localhost" || domain.ends_with(".localhost")
479 }
480 Some(url::Host::Ipv4(address)) => address.is_loopback(),
481 Some(url::Host::Ipv6(address)) => {
482 address.is_loopback()
483 || address.to_ipv4_mapped().is_some_and(|mapped| mapped.is_loopback())
484 }
485 None => false,
486 };
487 if loopback { Self::Loopback } else { Self::Remote }
488 }
489
490 /// The least local of `localities`: where the data of a call that may go to any of
491 /// them can end up. [`Remote`](Self::Remote) when there are none.
492 pub fn least_local(localities: impl IntoIterator<Item = DataLocality>) -> Self {
493 localities.into_iter().max().unwrap_or(Self::Remote)
494 }
495
496 /// Whether request data leaves this machine.
497 pub fn leaves_machine(self) -> bool {
498 self == Self::Remote
499 }
500
501 /// Whether request data leaves this process.
502 pub fn leaves_process(self) -> bool {
503 self != Self::InProcess
504 }
505}
506
507/// Tool declarations keyed by tool name, in the order the agent declares them.
508///
509/// Providers send the tools in this order, so a request is the same on every run, as in
510/// adk-python and adk-go. Inserting a name already present replaces its declaration in place.
511///
512/// ```rust
513/// use adk_core::ToolDeclarations;
514/// use serde_json::json;
515///
516/// let mut tools = ToolDeclarations::new();
517/// tools.insert("search".into(), json!({"name": "search"}));
518/// tools.insert("add".into(), json!({"name": "add"}));
519/// tools.insert("search".into(), json!({"name": "search", "description": "Find pages"}));
520///
521/// let names: Vec<&str> = tools.keys().map(String::as_str).collect();
522/// assert_eq!(names, ["search", "add"]);
523/// assert_eq!(tools["search"]["description"], "Find pages");
524/// ```
525#[derive(Debug, Clone, Default, PartialEq)]
526pub struct ToolDeclarations {
527 entries: Vec<(String, serde_json::Value)>,
528}
529
530impl ToolDeclarations {
531 /// No declarations.
532 pub fn new() -> Self {
533 Self::default()
534 }
535
536 /// The number of declarations.
537 pub fn len(&self) -> usize {
538 self.entries.len()
539 }
540
541 /// Whether there are no declarations.
542 pub fn is_empty(&self) -> bool {
543 self.entries.is_empty()
544 }
545
546 /// Declares `name`, at the end, or in its place when it is already declared. Returns the
547 /// declaration it replaced.
548 pub fn insert(
549 &mut self,
550 name: String,
551 declaration: serde_json::Value,
552 ) -> Option<serde_json::Value> {
553 match self.entries.iter_mut().find(|(existing, _)| *existing == name) {
554 Some((_, slot)) => Some(std::mem::replace(slot, declaration)),
555 None => {
556 self.entries.push((name, declaration));
557 None
558 }
559 }
560 }
561
562 /// The declaration of `name`.
563 pub fn get(&self, name: &str) -> Option<&serde_json::Value> {
564 self.entries.iter().find(|(existing, _)| existing == name).map(|(_, value)| value)
565 }
566
567 /// The declaration of `name`, to change.
568 pub fn get_mut(&mut self, name: &str) -> Option<&mut serde_json::Value> {
569 self.entries.iter_mut().find(|(existing, _)| existing == name).map(|(_, value)| value)
570 }
571
572 /// Whether `name` is declared.
573 pub fn contains_key(&self, name: &str) -> bool {
574 self.get(name).is_some()
575 }
576
577 /// Removes `name`, keeping the order of the rest. Returns its declaration.
578 pub fn remove(&mut self, name: &str) -> Option<serde_json::Value> {
579 let index = self.entries.iter().position(|(existing, _)| existing == name)?;
580 Some(self.entries.remove(index).1)
581 }
582
583 /// Keeps the declarations `keep` accepts, in order.
584 pub fn retain(&mut self, mut keep: impl FnMut(&String, &mut serde_json::Value) -> bool) {
585 self.entries.retain_mut(|(name, value)| keep(name, value));
586 }
587
588 /// Names and declarations, in declaration order.
589 pub fn iter(&self) -> ToolDeclarationsIter<'_> {
590 self.entries.iter().map(|(name, value)| (name, value))
591 }
592
593 /// Names, in declaration order.
594 pub fn keys(&self) -> ToolDeclarationsKeys<'_> {
595 ToolDeclarationsKeys { entries: self.entries.iter() }
596 }
597
598 /// Declarations, in declaration order.
599 pub fn values(&self) -> ToolDeclarationsValues<'_> {
600 ToolDeclarationsValues { entries: self.entries.iter() }
601 }
602}
603
604/// The names in [`ToolDeclarations`], in declaration order. Prints as a list of the names,
605/// as a `HashMap`'s keys do.
606#[derive(Clone)]
607pub struct ToolDeclarationsKeys<'a> {
608 entries: std::slice::Iter<'a, (String, serde_json::Value)>,
609}
610
611impl<'a> Iterator for ToolDeclarationsKeys<'a> {
612 type Item = &'a String;
613
614 fn next(&mut self) -> Option<&'a String> {
615 self.entries.next().map(|(name, _)| name)
616 }
617
618 fn size_hint(&self) -> (usize, Option<usize>) {
619 self.entries.size_hint()
620 }
621}
622
623impl DoubleEndedIterator for ToolDeclarationsKeys<'_> {
624 fn next_back(&mut self) -> Option<Self::Item> {
625 self.entries.next_back().map(|(name, _)| name)
626 }
627}
628
629impl ExactSizeIterator for ToolDeclarationsKeys<'_> {}
630
631impl std::fmt::Debug for ToolDeclarationsKeys<'_> {
632 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
633 f.debug_list().entries(self.clone()).finish()
634 }
635}
636
637/// The declarations in [`ToolDeclarations`], in declaration order. Prints as a list of the
638/// declarations, as a `HashMap`'s values do.
639#[derive(Clone)]
640pub struct ToolDeclarationsValues<'a> {
641 entries: std::slice::Iter<'a, (String, serde_json::Value)>,
642}
643
644impl<'a> Iterator for ToolDeclarationsValues<'a> {
645 type Item = &'a serde_json::Value;
646
647 fn next(&mut self) -> Option<&'a serde_json::Value> {
648 self.entries.next().map(|(_, value)| value)
649 }
650
651 fn size_hint(&self) -> (usize, Option<usize>) {
652 self.entries.size_hint()
653 }
654}
655
656impl DoubleEndedIterator for ToolDeclarationsValues<'_> {
657 fn next_back(&mut self) -> Option<Self::Item> {
658 self.entries.next_back().map(|(_, value)| value)
659 }
660}
661
662impl ExactSizeIterator for ToolDeclarationsValues<'_> {}
663
664impl std::fmt::Debug for ToolDeclarationsValues<'_> {
665 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
666 f.debug_list().entries(self.clone()).finish()
667 }
668}
669
670/// An iterator over [`ToolDeclarations`], in declaration order.
671pub type ToolDeclarationsIter<'a> = std::iter::Map<
672 std::slice::Iter<'a, (String, serde_json::Value)>,
673 fn(&'a (String, serde_json::Value)) -> (&'a String, &'a serde_json::Value),
674>;
675
676impl std::ops::Index<&str> for ToolDeclarations {
677 type Output = serde_json::Value;
678
679 /// The declaration of `name`; panics when it is not declared.
680 fn index(&self, name: &str) -> &serde_json::Value {
681 self.get(name).unwrap_or_else(|| panic!("tool {name} is not declared"))
682 }
683}
684
685impl<'a> IntoIterator for &'a ToolDeclarations {
686 type Item = (&'a String, &'a serde_json::Value);
687 type IntoIter = ToolDeclarationsIter<'a>;
688
689 fn into_iter(self) -> Self::IntoIter {
690 self.iter()
691 }
692}
693
694impl IntoIterator for ToolDeclarations {
695 type Item = (String, serde_json::Value);
696 type IntoIter = std::vec::IntoIter<(String, serde_json::Value)>;
697
698 fn into_iter(self) -> Self::IntoIter {
699 self.entries.into_iter()
700 }
701}
702
703impl<K: Into<String>> FromIterator<(K, serde_json::Value)> for ToolDeclarations {
704 fn from_iter<I: IntoIterator<Item = (K, serde_json::Value)>>(iter: I) -> Self {
705 let mut tools = Self::new();
706 tools.extend(iter);
707 tools
708 }
709}
710
711impl<K: Into<String>> Extend<(K, serde_json::Value)> for ToolDeclarations {
712 fn extend<I: IntoIterator<Item = (K, serde_json::Value)>>(&mut self, iter: I) {
713 for (name, declaration) in iter {
714 self.insert(name.into(), declaration);
715 }
716 }
717}
718
719/// A request to an LLM provider.
720#[derive(Debug, Clone, Serialize, Deserialize)]
721pub struct LlmRequest {
722 /// The model identifier to use for generation.
723 pub model: String,
724 /// The conversation contents (system, user, model messages).
725 pub contents: Vec<Content>,
726 /// Optional generation configuration (temperature, tokens, etc.).
727 pub config: Option<GenerateContentConfig>,
728 /// Tool declarations keyed by tool name, in declaration order.
729 #[serde(skip)]
730 pub tools: ToolDeclarations,
731 /// Provider-neutral identifier of the previous response to continue from.
732 /// The agent populates this from the most recent event's `interaction_id`.
733 /// Maps to `previous_interaction_id` for the Gemini Interactions transport;
734 /// ignored by transports that do not support response chaining.
735 #[serde(skip_serializing_if = "Option::is_none", default)]
736 pub previous_response_id: Option<String>,
737}
738
739/// How much reasoning effort a model spends (spec 3.1 §7.23, §10 C4).
740///
741/// Each provider maps a level to its own control: Anthropic `output_config.effort` with
742/// adaptive thinking, OpenAI `reasoning_effort`, Gemini `thinking_level`. Levels above
743/// `High` (`xhigh`, `max`) and below `Low` (`minimal`, `none`) are reachable only through a
744/// provider's own configuration.
745///
746/// # Example
747///
748/// ```rust
749/// use adk_core::Effort;
750///
751/// assert_eq!("high".parse::<Effort>(), Ok(Effort::High));
752/// assert_eq!(Effort::Low.to_string(), "low");
753/// assert!(Effort::Low < Effort::High);
754/// ```
755#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
756#[serde(rename_all = "lowercase")]
757pub enum Effort {
758 /// The least reasoning a provider offers short of none.
759 Low,
760 /// Balanced reasoning.
761 Medium,
762 /// Thorough reasoning.
763 High,
764}
765
766impl Effort {
767 /// Every level, lowest first.
768 pub const ALL: [Effort; 3] = [Effort::Low, Effort::Medium, Effort::High];
769
770 /// The level's name as flags and configuration files spell it.
771 pub const fn as_str(self) -> &'static str {
772 match self {
773 Effort::Low => "low",
774 Effort::Medium => "medium",
775 Effort::High => "high",
776 }
777 }
778}
779
780impl std::fmt::Display for Effort {
781 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
782 f.write_str(self.as_str())
783 }
784}
785
786impl std::str::FromStr for Effort {
787 type Err = String;
788
789 fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
790 match value.trim().to_ascii_lowercase().as_str() {
791 "low" => Ok(Effort::Low),
792 "medium" => Ok(Effort::Medium),
793 "high" => Ok(Effort::High),
794 other => Err(format!("unknown effort '{other}'; use low, medium or high")),
795 }
796 }
797}
798
799/// Configuration for LLM content generation.
800#[derive(Debug, Clone, Default, Serialize, Deserialize)]
801pub struct GenerateContentConfig {
802 /// Sampling temperature (0.0 = deterministic, higher = more random).
803 pub temperature: Option<f32>,
804 /// Nucleus sampling threshold.
805 pub top_p: Option<f32>,
806 /// Top-k sampling parameter.
807 pub top_k: Option<i32>,
808 /// Frequency penalty to reduce repetition.
809 #[serde(skip_serializing_if = "Option::is_none", default)]
810 pub frequency_penalty: Option<f32>,
811 /// Presence penalty to encourage topic diversity.
812 #[serde(skip_serializing_if = "Option::is_none", default)]
813 pub presence_penalty: Option<f32>,
814 /// Maximum number of output tokens to generate.
815 pub max_output_tokens: Option<i32>,
816 /// Random seed for reproducible generation.
817 #[serde(skip_serializing_if = "Option::is_none", default)]
818 pub seed: Option<i64>,
819 /// Number of top log probabilities to return per token.
820 #[serde(skip_serializing_if = "Option::is_none", default)]
821 pub top_logprobs: Option<u8>,
822 /// Sequences that stop generation when encountered.
823 #[serde(default, skip_serializing_if = "Vec::is_empty")]
824 pub stop_sequences: Vec<String>,
825 /// JSON Schema for structured output.
826 #[serde(skip_serializing_if = "Option::is_none")]
827 pub response_schema: Option<serde_json::Value>,
828
829 /// Output modalities requested from Gemini, such as `["TEXT", "IMAGE"]`.
830 /// Other clients reject this field rather than silently dropping it.
831 ///
832 /// # Example
833 ///
834 /// ```
835 /// use adk_core::GenerateContentConfig;
836 /// let config = GenerateContentConfig {
837 /// response_modalities: Some(vec!["TEXT".into(), "IMAGE".into()]),
838 /// ..Default::default()
839 /// };
840 /// assert_eq!(config.response_modalities.as_ref().unwrap().len(), 2);
841 /// ```
842 #[serde(skip_serializing_if = "Option::is_none", default)]
843 pub response_modalities: Option<Vec<String>>,
844
845 /// Optional cached content name for Gemini provider.
846 /// When set, the Gemini provider attaches this to the generation request.
847 #[serde(skip_serializing_if = "Option::is_none", default)]
848 pub cached_content: Option<String>,
849
850 /// The reasoning effort of this call (spec 3.1 §7.23, §10 C4).
851 ///
852 /// A set value wins over the effort the client was built with: Anthropic sends it as
853 /// `output_config.effort` with adaptive thinking, OpenAI as `reasoning_effort` (Chat
854 /// Completions) or `reasoning.effort` (Responses), Gemini as `thinking_level`, and
855 /// OpenRouter and DeepSeek as their reasoning effort. A provider or model with no effort
856 /// control ignores it and logs at debug level. `None` keeps the client's own
857 /// configuration.
858 ///
859 /// # Example
860 ///
861 /// ```
862 /// use adk_core::{Effort, GenerateContentConfig};
863 ///
864 /// let config = GenerateContentConfig { effort: Some(Effort::High), ..Default::default() };
865 /// assert_eq!(serde_json::to_value(&config).unwrap()["effort"], "high");
866 /// assert!(serde_json::to_value(GenerateContentConfig::default()).unwrap().get("effort").is_none());
867 /// ```
868 #[serde(default, skip_serializing_if = "Option::is_none")]
869 pub effort: Option<Effort>,
870
871 /// Provider-specific request options keyed by provider namespace.
872 #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
873 pub extensions: serde_json::Map<String, serde_json::Value>,
874}
875
876/// A response from an LLM provider.
877#[derive(Debug, Clone, Default, Serialize, Deserialize)]
878pub struct LlmResponse {
879 /// The generated content (text, function calls, etc.).
880 pub content: Option<Content>,
881 /// Token usage statistics.
882 pub usage_metadata: Option<UsageMetadata>,
883 /// Reason the model stopped generating.
884 pub finish_reason: Option<FinishReason>,
885 /// Citation sources referenced in the response.
886 #[serde(skip_serializing_if = "Option::is_none")]
887 pub citation_metadata: Option<CitationMetadata>,
888 /// Whether this is a partial streaming chunk.
889 pub partial: bool,
890 /// Whether the model has finished its turn.
891 pub turn_complete: bool,
892 /// Whether the response was interrupted.
893 pub interrupted: bool,
894 /// Error code from the provider, if any.
895 pub error_code: Option<String>,
896 /// Error message from the provider, if any.
897 pub error_message: Option<String>,
898 /// Provider-specific metadata (e.g., response IDs, routing info).
899 ///
900 /// `LlmAgent` recognizes two optional boolean fields: `content_complete`
901 /// on a non-partial response replaces accumulated deltas with authoritative
902 /// content; `continue_turn` requests another bounded model iteration for
903 /// a provider-native tool pause without a client function call.
904 #[serde(skip_serializing_if = "Option::is_none", default)]
905 pub provider_metadata: Option<serde_json::Value>,
906 /// Interactions API: the server-assigned interaction id for this turn, used
907 /// to continue the conversation via `previous_interaction_id`. `None` for
908 /// the generateContent transport and non-Gemini providers.
909 #[serde(skip_serializing_if = "Option::is_none", default)]
910 pub interaction_id: Option<String>,
911 /// Model that produced this response: the version the provider reports when
912 /// it reports one, otherwise the identifier the request was sent to.
913 ///
914 /// Set by every `adk-model` provider. Budgets and pricing read it to
915 /// attribute usage and cost; `None` means the producer did not attribute it.
916 #[serde(skip_serializing_if = "Option::is_none", default)]
917 pub model: Option<String>,
918 /// Provider that served this response, such as `"gemini"`, `"openai"`,
919 /// `"anthropic"` or `"bedrock"`.
920 ///
921 /// Set by every `adk-model` provider; `None` means the producer did not
922 /// attribute it.
923 #[serde(skip_serializing_if = "Option::is_none", default)]
924 pub provider: Option<String>,
925}
926
927/// Trait for LLM providers that support prompt caching.
928///
929/// Providers implementing this trait can create and delete cached content
930/// resources, enabling automatic prompt caching lifecycle management by the
931/// runner. The runner stores an `Option<Arc<dyn CacheCapable>>` alongside the
932/// primary `Arc<dyn Llm>` and calls these methods when [`ContextCacheConfig`]
933/// is active.
934///
935/// # Example
936///
937/// ```rust,ignore
938/// use adk_core::CacheCapable;
939///
940/// let cache_name = model
941/// .create_cache("You are a helpful assistant.", &tools, 600)
942/// .await?;
943/// // ... use cache_name in generation requests ...
944/// model.delete_cache(&cache_name).await?;
945/// ```
946#[async_trait]
947pub trait CacheCapable: Send + Sync {
948 /// Create a cached content resource from the given system instruction,
949 /// tool definitions, and TTL.
950 ///
951 /// Returns the provider-specific cache name (e.g. `"cachedContents/abc123"`
952 /// for Gemini) that can be attached to subsequent generation requests via
953 /// [`GenerateContentConfig::cached_content`].
954 async fn create_cache(
955 &self,
956 system_instruction: &str,
957 tools: &ToolDeclarations,
958 ttl_seconds: u32,
959 ) -> Result<String>;
960
961 /// Delete a previously created cached content resource by name.
962 async fn delete_cache(&self, name: &str) -> Result<()>;
963}
964
965/// Configuration for automatic prompt caching lifecycle management.
966///
967/// When set on runner configuration, the runner will automatically create and manage
968/// cached content resources for supported providers (currently Gemini).
969///
970/// # Example
971///
972/// ```rust
973/// use adk_core::ContextCacheConfig;
974///
975/// let config = ContextCacheConfig {
976/// min_tokens: 4096,
977/// ttl_seconds: 600,
978/// cache_intervals: 3,
979/// };
980/// assert_eq!(config.min_tokens, 4096);
981/// ```
982#[derive(Debug, Clone, Serialize, Deserialize)]
983pub struct ContextCacheConfig {
984 /// Minimum system instruction + tool token count to trigger caching.
985 /// Set to 0 to disable caching.
986 pub min_tokens: u32,
987
988 /// Cache time-to-live in seconds.
989 /// Set to 0 to disable caching.
990 pub ttl_seconds: u32,
991
992 /// Maximum number of LLM invocations before cache refresh.
993 /// After this many invocations, the runner creates a new cache
994 /// and deletes the old one.
995 pub cache_intervals: u32,
996}
997
998impl Default for ContextCacheConfig {
999 fn default() -> Self {
1000 Self { min_tokens: 4096, ttl_seconds: 600, cache_intervals: 3 }
1001 }
1002}
1003
1004/// Token usage statistics from an LLM response.
1005#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1006pub struct UsageMetadata {
1007 /// Number of tokens in the prompt.
1008 pub prompt_token_count: i32,
1009 /// Number of tokens in the generated response.
1010 pub candidates_token_count: i32,
1011 /// Total tokens (prompt + response).
1012 pub total_token_count: i32,
1013
1014 /// Tokens read from cache (Gemini/Anthropic).
1015 #[serde(skip_serializing_if = "Option::is_none", default)]
1016 pub cache_read_input_token_count: Option<i32>,
1017
1018 /// Tokens written to cache during this request.
1019 #[serde(skip_serializing_if = "Option::is_none", default)]
1020 pub cache_creation_input_token_count: Option<i32>,
1021
1022 /// Tokens used for thinking/reasoning (thinking models).
1023 #[serde(skip_serializing_if = "Option::is_none", default)]
1024 pub thinking_token_count: Option<i32>,
1025
1026 /// Audio input tokens (multimodal models).
1027 #[serde(skip_serializing_if = "Option::is_none", default)]
1028 pub audio_input_token_count: Option<i32>,
1029
1030 /// Audio output tokens (multimodal models).
1031 #[serde(skip_serializing_if = "Option::is_none", default)]
1032 pub audio_output_token_count: Option<i32>,
1033
1034 /// Estimated cost in USD for this request.
1035 ///
1036 /// `adk-model` providers fill this from the provider's own report when it
1037 /// sends one (OpenRouter), otherwise from `adk_model::pricing::PricingCatalog`.
1038 /// `None` means the cost is unknown, never that the request was free.
1039 #[serde(skip_serializing_if = "Option::is_none", default)]
1040 pub cost: Option<f64>,
1041
1042 /// Whether this request used a bring-your-own-key provider.
1043 #[serde(skip_serializing_if = "Option::is_none", default)]
1044 pub is_byok: Option<bool>,
1045
1046 /// Provider-native usage data retained when available, including fields
1047 /// that are not yet projected into the normalized counters above.
1048 #[serde(skip_serializing_if = "Option::is_none", default)]
1049 pub provider_usage: Option<serde_json::Value>,
1050
1051 /// Provider-executed built-in tool uses the provider reported for this request.
1052 ///
1053 /// Each use counts as one tool call against a
1054 /// [`RunBudget`](crate::RunBudget), and priced kinds add their per-use fee to
1055 /// [`cost`](Self::cost). See [`BuiltinToolUse`] for the kinds providers report.
1056 #[serde(skip_serializing_if = "Vec::is_empty", default)]
1057 pub builtin_tool_uses: Vec<BuiltinToolUse>,
1058}
1059
1060impl UsageMetadata {
1061 /// Total number of provider-executed built-in tool uses across all kinds.
1062 ///
1063 /// # Example
1064 ///
1065 /// ```
1066 /// use adk_core::{BuiltinToolUse, UsageMetadata};
1067 ///
1068 /// let usage = UsageMetadata {
1069 /// builtin_tool_uses: vec![BuiltinToolUse::new("web_search", 2), BuiltinToolUse::new("web_fetch", 1)],
1070 /// ..Default::default()
1071 /// };
1072 /// assert_eq!(usage.builtin_tool_use_count(), 3);
1073 /// ```
1074 pub fn builtin_tool_use_count(&self) -> u64 {
1075 self.builtin_tool_uses.iter().map(|used| u64::from(used.count)).sum()
1076 }
1077}
1078
1079/// Deserializes a token count that a provider may report as `null`, reading `null` as zero.
1080///
1081/// Pair it with `#[serde(default)]` so that a missing count is zero too. Compatible endpoints
1082/// report a count they did not compute as `null` or leave it out, and that must not fail the
1083/// model turn the usage belongs to. Fields typed `Option<_>` need no helper: serde already
1084/// reads `null` there as `None`.
1085///
1086/// # Example
1087///
1088/// ```
1089/// use serde::Deserialize;
1090///
1091/// #[derive(Deserialize)]
1092/// struct Usage {
1093/// #[serde(default, deserialize_with = "adk_core::nullable_count")]
1094/// input_tokens: u32,
1095/// }
1096///
1097/// let usage: Usage = serde_json::from_str(r#"{"input_tokens": null}"#).unwrap();
1098/// assert_eq!(usage.input_tokens, 0);
1099/// let usage: Usage = serde_json::from_str("{}").unwrap();
1100/// assert_eq!(usage.input_tokens, 0);
1101/// let usage: Usage = serde_json::from_str(r#"{"input_tokens": 12}"#).unwrap();
1102/// assert_eq!(usage.input_tokens, 12);
1103/// ```
1104///
1105/// # Errors
1106///
1107/// Returns the deserializer's error when the value is neither `null` nor a `T`.
1108pub fn nullable_count<'de, D, T>(deserializer: D) -> std::result::Result<T, D::Error>
1109where
1110 D: serde::Deserializer<'de>,
1111 T: Deserialize<'de> + Default,
1112{
1113 Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
1114}
1115
1116/// How many times the provider ran one kind of built-in tool for a request.
1117///
1118/// Kinds are provider-neutral names:
1119///
1120/// | Kind | Reported by |
1121/// |------|-------------|
1122/// | `web_search` | Anthropic `usage.server_tool_use.web_search_requests`, OpenAI `web_search_call` items |
1123/// | `web_fetch` | Anthropic `usage.server_tool_use.web_fetch_requests` |
1124/// | `code_execution` | Anthropic `usage.server_tool_use.code_execution_requests`, OpenAI `code_interpreter_call` items, Gemini `executableCode` parts |
1125/// | `file_search` | OpenAI `file_search_call` items |
1126/// | `image_generation` | OpenAI `image_generation_call` items |
1127/// | `mcp` | OpenAI `mcp_call` items |
1128/// | `google_search` | Gemini `groundingMetadata.webSearchQueries` (one per query) |
1129/// | `google_maps` | Gemini grounding chunks with a `maps` source (one per grounded response) |
1130///
1131/// # Example
1132///
1133/// ```
1134/// use adk_core::BuiltinToolUse;
1135///
1136/// let used = BuiltinToolUse::new("web_search", 3);
1137/// assert_eq!(used.kind, "web_search");
1138/// assert_eq!(used.count, 3);
1139/// ```
1140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1141pub struct BuiltinToolUse {
1142 /// Provider-neutral tool kind, such as `web_search`.
1143 pub kind: String,
1144 /// Number of uses the provider reported.
1145 pub count: u32,
1146}
1147
1148impl BuiltinToolUse {
1149 /// Creates a record of `count` uses of `kind`.
1150 pub fn new(kind: impl Into<String>, count: u32) -> Self {
1151 Self { kind: kind.into(), count }
1152 }
1153}
1154
1155/// The wire form of a provider-executed web search tool (spec 3.1 §7.20).
1156///
1157/// Each variant names the `adk-tool` built-in that declares it.
1158///
1159/// | Variant | Built-in | Request entry |
1160/// |---------|----------|---------------|
1161/// | `GoogleSearch` | `GoogleSearchTool` | Gemini `tools[].google_search` |
1162/// | `AnthropicWebSearch` | `WebSearchTool` | Messages `web_search_20250305` server tool |
1163/// | `OpenAiWebSearch` | `OpenAIWebSearchTool` | Responses `{"type": "web_search"}` |
1164/// | `DeepSeekWebSearch` | `DeepSeekWebSearchTool` | DeepSeek Responses `{"type": "web_search"}` |
1165#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
1166#[serde(rename_all = "snake_case")]
1167#[non_exhaustive]
1168pub enum NativeWebSearchTool {
1169 /// Gemini `google_search` grounding.
1170 GoogleSearch,
1171 /// The Anthropic Messages `web_search` server tool.
1172 AnthropicWebSearch,
1173 /// The OpenAI Responses `web_search` tool.
1174 OpenAiWebSearch,
1175 /// The `web_search` tool of DeepSeek's Responses endpoint.
1176 DeepSeekWebSearch,
1177}
1178
1179/// The provider-executed web search a model's transport serves (spec 3.1 §7.20), as
1180/// [`Llm::native_web_search`] reports it.
1181///
1182/// # Example
1183///
1184/// ```rust
1185/// use adk_core::{NativeWebSearch, NativeWebSearchTool};
1186///
1187/// let search = NativeWebSearch::new("gemini", NativeWebSearchTool::GoogleSearch, false);
1188/// assert_eq!(search.provider, "gemini");
1189/// assert!(!search.allowed_domains, "google_search takes no domain allowlist");
1190/// ```
1191#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
1192#[non_exhaustive]
1193pub struct NativeWebSearch {
1194 /// Provider that runs the search, such as `"gemini"`, `"anthropic"`, `"openai"` or
1195 /// `"deepseek"`.
1196 pub provider: &'static str,
1197 /// The tool the request declares.
1198 pub tool: NativeWebSearchTool,
1199 /// Whether the provider honours a domain allowlist on the tool.
1200 pub allowed_domains: bool,
1201}
1202
1203impl NativeWebSearch {
1204 /// Describes the search `provider` runs through `tool`, with or without a domain
1205 /// allowlist.
1206 pub fn new(provider: &'static str, tool: NativeWebSearchTool, allowed_domains: bool) -> Self {
1207 Self { provider, tool, allowed_domains }
1208 }
1209}
1210
1211/// The conversation compaction a model's provider performs itself, as
1212/// [`Llm::native_compaction`] reports it.
1213///
1214/// # Example
1215///
1216/// ```rust
1217/// use adk_core::NativeCompaction;
1218///
1219/// let compaction = NativeCompaction::new("anthropic").keeping_thinking();
1220/// assert_eq!(compaction.provider, "anthropic");
1221/// assert!(compaction.keeps_thinking);
1222/// ```
1223#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
1224#[non_exhaustive]
1225pub struct NativeCompaction {
1226 /// Provider that writes the summary, such as `"anthropic"`.
1227 pub provider: &'static str,
1228 /// Whether the turns kept after the summary keep their thinking: the provider accepts
1229 /// thinking that was produced before the summary replaced the turns it followed.
1230 pub keeps_thinking: bool,
1231}
1232
1233impl NativeCompaction {
1234 /// The compaction `provider` performs; the kept turns lose their thinking.
1235 pub fn new(provider: &'static str) -> Self {
1236 Self { provider, keeps_thinking: false }
1237 }
1238
1239 /// The kept turns keep their thinking after the summary.
1240 pub fn keeping_thinking(mut self) -> Self {
1241 self.keeps_thinking = true;
1242 self
1243 }
1244}
1245
1246/// Citation metadata emitted by model providers for source attribution.
1247#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1248#[serde(rename_all = "camelCase")]
1249pub struct CitationMetadata {
1250 /// The list of citation sources in this response.
1251 #[serde(default)]
1252 pub citation_sources: Vec<CitationSource>,
1253}
1254
1255/// One citation source with optional offsets.
1256#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1257#[serde(rename_all = "camelCase")]
1258pub struct CitationSource {
1259 /// URI of the cited source.
1260 pub uri: Option<String>,
1261 /// Title of the cited source.
1262 pub title: Option<String>,
1263 /// Start character index in the response text.
1264 pub start_index: Option<i32>,
1265 /// End character index in the response text.
1266 pub end_index: Option<i32>,
1267 /// License of the cited source.
1268 pub license: Option<String>,
1269 /// Publication date of the cited source.
1270 pub publication_date: Option<String>,
1271}
1272
1273/// Reason the model stopped generating content.
1274///
1275/// The enum is `#[non_exhaustive]`: providers add stop reasons, so a `match` outside
1276/// `adk-core` needs a wildcard arm. Each variant serializes as its name (`"Stop"`,
1277/// `"Refusal"`, ...), and a name this version does not know deserializes as
1278/// [`Other`](Self::Other), so an event written by a newer release still loads.
1279///
1280/// `LlmAgent` and `CodeActAgent` end the run with an error on [`Refusal`](Self::Refusal)
1281/// (`model.refusal`) and [`MalformedToolCall`](Self::MalformedToolCall)
1282/// (`model.malformed_tool_call`); the other reasons leave the outcome to the content.
1283///
1284/// # Example
1285///
1286/// ```
1287/// use adk_core::FinishReason;
1288///
1289/// fn succeeded(reason: Option<FinishReason>) -> bool {
1290/// match reason {
1291/// Some(FinishReason::Stop) | None => true,
1292/// Some(FinishReason::Refusal | FinishReason::MalformedToolCall) => false,
1293/// Some(_) => false,
1294/// }
1295/// }
1296///
1297/// assert!(!succeeded(Some(FinishReason::Refusal)));
1298/// assert_eq!(serde_json::to_string(&FinishReason::Refusal).unwrap(), "\"Refusal\"");
1299/// assert_eq!(
1300/// serde_json::from_str::<FinishReason>("\"SomeLaterReason\"").unwrap(),
1301/// FinishReason::Other
1302/// );
1303/// ```
1304#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1305#[non_exhaustive]
1306pub enum FinishReason {
1307 /// Natural stop (end of response).
1308 Stop,
1309 /// Hit the maximum token limit.
1310 MaxTokens,
1311 /// A content filter blocked or cut the response, such as Gemini `SAFETY`, OpenAI
1312 /// `content_filter`, or a Bedrock guardrail.
1313 Safety,
1314 /// Content blocked due to recitation/copyright.
1315 Recitation,
1316 /// The model declined the request: Anthropic `stop_reason: "refusal"`, an OpenAI Chat
1317 /// Completions `refusal`, or a Responses `refusal` content part. The response's text, when
1318 /// present, is the refusal, not an answer.
1319 Refusal,
1320 /// The provider reports a tool call the model generated as invalid: Gemini
1321 /// `MALFORMED_FUNCTION_CALL` or `UNEXPECTED_TOOL_CALL`, Bedrock `malformed_tool_use`.
1322 MalformedToolCall,
1323 /// Other/unknown reason, including a name a newer release wrote.
1324 #[serde(other)]
1325 Other,
1326}
1327
1328impl LlmRequest {
1329 /// Creates a new request with the given model and contents.
1330 pub fn new(model: impl Into<String>, contents: Vec<Content>) -> Self {
1331 Self {
1332 model: model.into(),
1333 contents,
1334 config: None,
1335 tools: ToolDeclarations::new(),
1336 previous_response_id: None,
1337 }
1338 }
1339
1340 /// Set the response schema for structured output.
1341 pub fn with_response_schema(mut self, schema: serde_json::Value) -> Self {
1342 let config = self.config.get_or_insert(GenerateContentConfig::default());
1343 config.response_schema = Some(schema);
1344 self
1345 }
1346
1347 /// Set the generation config.
1348 pub fn with_config(mut self, config: GenerateContentConfig) -> Self {
1349 self.config = Some(config);
1350 self
1351 }
1352}
1353
1354impl LlmResponse {
1355 /// Creates a complete (non-streaming) response with the given content.
1356 pub fn new(content: Content) -> Self {
1357 Self {
1358 content: Some(content),
1359 usage_metadata: None,
1360 finish_reason: Some(FinishReason::Stop),
1361 citation_metadata: None,
1362 partial: false,
1363 turn_complete: true,
1364 interrupted: false,
1365 error_code: None,
1366 error_message: None,
1367 provider_metadata: None,
1368 interaction_id: None,
1369 model: None,
1370 provider: None,
1371 }
1372 }
1373}
1374
1375#[cfg(test)]
1376mod tests {
1377 use super::*;
1378
1379 #[test]
1380 fn a_loopback_host_is_loopback_and_every_other_host_remote() {
1381 for url in [
1382 "http://localhost:11434",
1383 "http://LOCALHOST.:8000/v1",
1384 "http://vllm.localhost/v1",
1385 "http://127.0.0.1:1234/v1",
1386 "http://127.8.9.10",
1387 "http://[::1]:8080",
1388 "http://[::ffff:127.0.0.1]:8080",
1389 " https://localhost/v1/ ",
1390 ] {
1391 assert_eq!(DataLocality::of_url(url), DataLocality::Loopback, "{url}");
1392 }
1393 for url in [
1394 "https://api.openai.com/v1",
1395 "http://localhost.example.com",
1396 "http://0.0.0.0:11434",
1397 "http://10.0.0.5:11434",
1398 "http://[::2]",
1399 "localhost:11434",
1400 "not a url",
1401 "",
1402 ] {
1403 assert_eq!(DataLocality::of_url(url), DataLocality::Remote, "{url}");
1404 }
1405 }
1406
1407 #[test]
1408 fn the_least_local_of_several_localities_wins() {
1409 use DataLocality::{InProcess, Loopback, Remote};
1410 assert_eq!(DataLocality::least_local([InProcess, InProcess]), InProcess);
1411 assert_eq!(DataLocality::least_local([InProcess, Loopback]), Loopback);
1412 assert_eq!(DataLocality::least_local([Loopback, Remote, InProcess]), Remote);
1413 assert_eq!(DataLocality::least_local([]), Remote);
1414 assert_eq!(DataLocality::default(), Remote);
1415 assert!(Remote.leaves_machine() && Remote.leaves_process());
1416 assert!(!Loopback.leaves_machine() && Loopback.leaves_process());
1417 assert!(!InProcess.leaves_machine() && !InProcess.leaves_process());
1418 for locality in [InProcess, Loopback, Remote] {
1419 let wire = serde_json::to_value(locality).unwrap();
1420 assert_eq!(serde_json::from_value::<DataLocality>(wire).unwrap(), locality);
1421 }
1422 }
1423
1424 #[test]
1425 fn a_metered_model_reports_the_wrapped_models_locality() {
1426 struct Local;
1427
1428 #[async_trait]
1429 impl Llm for Local {
1430 fn name(&self) -> &str {
1431 "local"
1432 }
1433 async fn generate_content(&self, _: LlmRequest, _: bool) -> Result<LlmResponseStream> {
1434 Ok(Box::pin(futures::stream::empty()))
1435 }
1436 fn data_locality(&self) -> DataLocality {
1437 DataLocality::InProcess
1438 }
1439 fn data_destinations(&self) -> Vec<DataDestination> {
1440 vec![DataDestination::new("local", ["127.0.0.1:8080"])]
1441 }
1442 }
1443
1444 let metered = crate::MeteredLlm::new(std::sync::Arc::new(Local));
1445 assert_eq!(metered.data_locality(), DataLocality::InProcess);
1446 assert_eq!(
1447 metered.data_destinations(),
1448 vec![DataDestination::new("local", ["127.0.0.1:8080"])]
1449 );
1450 }
1451
1452 #[test]
1453 fn a_destination_names_the_endpoint_host_and_any_port_but_443() {
1454 for (url, host) in [
1455 ("https://api.anthropic.com", "api.anthropic.com"),
1456 ("https://API.OpenAI.com./v1", "api.openai.com"),
1457 (
1458 "https://bedrock-runtime.eu-west-1.amazonaws.com:443/x",
1459 "bedrock-runtime.eu-west-1.amazonaws.com",
1460 ),
1461 ("http://localhost:11434", "localhost:11434"),
1462 ("http://gpu-box/v1", "gpu-box:80"),
1463 ("https://nim.internal:8443/v1", "nim.internal:8443"),
1464 ("http://[::1]:8000/v1", "[::1]:8000"),
1465 ] {
1466 assert_eq!(
1467 DataDestination::of_url("p", url),
1468 DataDestination::new("p", [host]),
1469 "{url}"
1470 );
1471 }
1472 for url in ["not a url", "", "data:text/plain,x"] {
1473 assert!(DataDestination::of_url("p", url).hosts.is_empty(), "{url}");
1474 }
1475 }
1476
1477 #[test]
1478 fn a_model_that_does_not_say_has_no_destination() {
1479 struct Silent;
1480
1481 #[async_trait]
1482 impl Llm for Silent {
1483 fn name(&self) -> &str {
1484 "silent"
1485 }
1486 async fn generate_content(&self, _: LlmRequest, _: bool) -> Result<LlmResponseStream> {
1487 Ok(Box::pin(futures::stream::empty()))
1488 }
1489 }
1490
1491 assert!(Silent.data_destinations().is_empty());
1492 }
1493
1494 #[test]
1495 fn tool_names_and_declarations_print_as_lists() {
1496 let tools: ToolDeclarations = [
1497 ("search", serde_json::json!({"name": "search"})),
1498 ("add", serde_json::json!({"name": "add"})),
1499 ]
1500 .into_iter()
1501 .collect();
1502 assert_eq!(format!("{:?}", tools.keys()), r#"["search", "add"]"#);
1503 assert_eq!(
1504 format!("{:?}", tools.values()),
1505 r#"[Object {"name": String("search")}, Object {"name": String("add")}]"#
1506 );
1507 assert_eq!(tools.keys().len(), 2);
1508 assert_eq!(tools.keys().next_back().map(String::as_str), Some("add"));
1509 }
1510
1511 #[test]
1512 fn test_llm_request_creation() {
1513 let req = LlmRequest::new("test-model", vec![]);
1514 assert_eq!(req.model, "test-model");
1515 assert!(req.contents.is_empty());
1516 }
1517
1518 #[test]
1519 fn test_llm_request_with_response_schema() {
1520 let schema = serde_json::json!({
1521 "type": "object",
1522 "properties": {
1523 "name": { "type": "string" }
1524 }
1525 });
1526 let req = LlmRequest::new("test-model", vec![]).with_response_schema(schema.clone());
1527
1528 assert!(req.config.is_some());
1529 let config = req.config.unwrap();
1530 assert!(config.response_schema.is_some());
1531 assert_eq!(config.response_schema.unwrap(), schema);
1532 }
1533
1534 #[test]
1535 fn test_llm_request_with_config() {
1536 let config = GenerateContentConfig {
1537 temperature: Some(0.7),
1538 top_p: Some(0.9),
1539 top_k: Some(40),
1540 frequency_penalty: Some(0.2),
1541 presence_penalty: Some(-0.3),
1542 max_output_tokens: Some(1024),
1543 seed: Some(42),
1544 top_logprobs: Some(5),
1545 stop_sequences: vec!["END".to_string()],
1546 ..Default::default()
1547 };
1548 let req = LlmRequest::new("test-model", vec![]).with_config(config);
1549
1550 assert!(req.config.is_some());
1551 let config = req.config.unwrap();
1552 assert_eq!(config.temperature, Some(0.7));
1553 assert_eq!(config.max_output_tokens, Some(1024));
1554 assert_eq!(config.frequency_penalty, Some(0.2));
1555 assert_eq!(config.presence_penalty, Some(-0.3));
1556 assert_eq!(config.seed, Some(42));
1557 assert_eq!(config.top_logprobs, Some(5));
1558 assert_eq!(config.stop_sequences, vec!["END"]);
1559 }
1560
1561 #[test]
1562 fn test_llm_response_creation() {
1563 let content = Content::new("assistant");
1564 let resp = LlmResponse::new(content);
1565 assert!(resp.content.is_some());
1566 assert!(resp.turn_complete);
1567 assert!(!resp.partial);
1568 assert_eq!(resp.finish_reason, Some(FinishReason::Stop));
1569 assert!(resp.citation_metadata.is_none());
1570 assert!(resp.provider_metadata.is_none());
1571 }
1572
1573 #[test]
1574 fn test_llm_response_deserialize_without_citations() {
1575 let json = serde_json::json!({
1576 "content": {
1577 "role": "model",
1578 "parts": [{"text": "hello"}]
1579 },
1580 "partial": false,
1581 "turn_complete": true,
1582 "interrupted": false
1583 });
1584
1585 let response: LlmResponse = serde_json::from_value(json).expect("should deserialize");
1586 assert!(response.citation_metadata.is_none());
1587 }
1588
1589 #[test]
1590 fn test_llm_response_roundtrip_with_citations() {
1591 let response = LlmResponse {
1592 content: Some(Content::new("model").with_text("hello")),
1593 usage_metadata: None,
1594 finish_reason: Some(FinishReason::Stop),
1595 citation_metadata: Some(CitationMetadata {
1596 citation_sources: vec![CitationSource {
1597 uri: Some("https://example.com".to_string()),
1598 title: Some("Example".to_string()),
1599 start_index: Some(0),
1600 end_index: Some(5),
1601 license: None,
1602 publication_date: Some("2026-01-01T00:00:00Z".to_string()),
1603 }],
1604 }),
1605 partial: false,
1606 turn_complete: true,
1607 interrupted: false,
1608 error_code: None,
1609 error_message: None,
1610 provider_metadata: None,
1611 interaction_id: None,
1612 model: None,
1613 provider: None,
1614 };
1615
1616 let encoded = serde_json::to_string(&response).expect("serialize");
1617 let decoded: LlmResponse = serde_json::from_str(&encoded).expect("deserialize");
1618 assert_eq!(decoded.citation_metadata, response.citation_metadata);
1619 }
1620
1621 #[test]
1622 fn test_generate_content_config_roundtrip_with_extensions() {
1623 let mut extensions = serde_json::Map::new();
1624 extensions.insert(
1625 "openrouter".to_string(),
1626 serde_json::json!({
1627 "provider": {
1628 "zdr": true,
1629 "order": ["openai", "anthropic"]
1630 },
1631 "plugins": [
1632 { "id": "web", "enabled": true }
1633 ]
1634 }),
1635 );
1636
1637 let config = GenerateContentConfig {
1638 temperature: Some(0.4),
1639 top_p: Some(0.8),
1640 top_k: Some(12),
1641 frequency_penalty: Some(0.1),
1642 presence_penalty: Some(0.2),
1643 max_output_tokens: Some(512),
1644 seed: Some(7),
1645 top_logprobs: Some(3),
1646 stop_sequences: vec!["STOP".to_string(), "DONE".to_string()],
1647 response_schema: Some(serde_json::json!({
1648 "type": "object",
1649 "properties": { "answer": { "type": "string" } },
1650 "required": ["answer"]
1651 })),
1652 response_modalities: Some(vec!["TEXT".to_string(), "IMAGE".to_string()]),
1653 cached_content: Some("cachedContents/abc123".to_string()),
1654 effort: Some(Effort::Medium),
1655 extensions,
1656 };
1657
1658 let encoded = serde_json::to_string(&config).expect("serialize");
1659 let decoded: GenerateContentConfig = serde_json::from_str(&encoded).expect("deserialize");
1660
1661 assert_eq!(decoded.temperature, config.temperature);
1662 assert_eq!(decoded.top_p, config.top_p);
1663 assert_eq!(decoded.top_k, config.top_k);
1664 assert_eq!(decoded.frequency_penalty, config.frequency_penalty);
1665 assert_eq!(decoded.presence_penalty, config.presence_penalty);
1666 assert_eq!(decoded.max_output_tokens, config.max_output_tokens);
1667 assert_eq!(decoded.seed, config.seed);
1668 assert_eq!(decoded.top_logprobs, config.top_logprobs);
1669 assert_eq!(decoded.stop_sequences, config.stop_sequences);
1670 assert_eq!(decoded.response_schema, config.response_schema);
1671 assert_eq!(decoded.cached_content, config.cached_content);
1672 assert_eq!(decoded.extensions, config.extensions);
1673 assert_eq!(decoded.response_modalities, config.response_modalities);
1674 assert_eq!(decoded.effort, config.effort);
1675 }
1676
1677 #[test]
1678 fn a_config_without_effort_reads_and_writes_as_before() {
1679 let legacy: GenerateContentConfig =
1680 serde_json::from_value(serde_json::json!({ "temperature": 0.2 })).unwrap();
1681 assert_eq!(legacy.effort, None);
1682 assert_eq!(serde_json::to_value(&legacy).unwrap().get("effort"), None);
1683 let set: GenerateContentConfig =
1684 serde_json::from_value(serde_json::json!({ "effort": "low" })).unwrap();
1685 assert_eq!(set.effort, Some(Effort::Low));
1686 }
1687
1688 #[test]
1689 fn test_llm_response_and_usage_roundtrip_with_provider_metadata() {
1690 let response = LlmResponse {
1691 content: Some(Content::new("model").with_text("hello")),
1692 usage_metadata: Some(UsageMetadata {
1693 prompt_token_count: 10,
1694 candidates_token_count: 20,
1695 total_token_count: 30,
1696 cache_read_input_token_count: Some(5),
1697 cache_creation_input_token_count: Some(2),
1698 thinking_token_count: Some(3),
1699 audio_input_token_count: Some(4),
1700 audio_output_token_count: Some(6),
1701 cost: Some(0.0125),
1702 is_byok: Some(true),
1703 provider_usage: Some(serde_json::json!({
1704 "server_tool_use": {
1705 "web_search_requests": 1
1706 },
1707 "prompt_tokens_details": {
1708 "video_tokens": 8
1709 }
1710 })),
1711 builtin_tool_uses: vec![BuiltinToolUse::new("web_search", 1)],
1712 }),
1713 finish_reason: Some(FinishReason::Stop),
1714 citation_metadata: None,
1715 partial: false,
1716 turn_complete: true,
1717 interrupted: false,
1718 error_code: None,
1719 error_message: None,
1720 provider_metadata: Some(serde_json::json!({
1721 "openrouter": {
1722 "responseId": "resp_123",
1723 "outputItems": 2
1724 }
1725 })),
1726 interaction_id: None,
1727 model: None,
1728 provider: None,
1729 };
1730
1731 let encoded = serde_json::to_string(&response).expect("serialize");
1732 let decoded: LlmResponse = serde_json::from_str(&encoded).expect("deserialize");
1733
1734 assert_eq!(decoded.provider_metadata, response.provider_metadata);
1735 assert_eq!(
1736 decoded.usage_metadata.as_ref().and_then(|u| u.cost),
1737 response.usage_metadata.as_ref().and_then(|u| u.cost),
1738 );
1739 assert_eq!(
1740 decoded.usage_metadata.as_ref().and_then(|u| u.is_byok),
1741 response.usage_metadata.as_ref().and_then(|u| u.is_byok),
1742 );
1743 assert_eq!(
1744 decoded.usage_metadata.as_ref().map(|u| u.builtin_tool_uses.clone()),
1745 Some(vec![BuiltinToolUse::new("web_search", 1)]),
1746 );
1747 assert_eq!(
1748 decoded.usage_metadata.as_ref().and_then(|u| u.provider_usage.clone()),
1749 response.usage_metadata.as_ref().and_then(|u| u.provider_usage.clone()),
1750 );
1751 }
1752
1753 #[test]
1754 fn test_finish_reason() {
1755 assert_eq!(FinishReason::Stop, FinishReason::Stop);
1756 assert_ne!(FinishReason::Stop, FinishReason::MaxTokens);
1757 }
1758
1759 /// Events and sessions store the finish reason by name, so the names are a wire format.
1760 #[test]
1761 fn finish_reason_wire_names_are_stable() {
1762 let names = [
1763 (FinishReason::Stop, "Stop"),
1764 (FinishReason::MaxTokens, "MaxTokens"),
1765 (FinishReason::Safety, "Safety"),
1766 (FinishReason::Recitation, "Recitation"),
1767 (FinishReason::Refusal, "Refusal"),
1768 (FinishReason::MalformedToolCall, "MalformedToolCall"),
1769 (FinishReason::Other, "Other"),
1770 ];
1771 for (reason, name) in names {
1772 assert_eq!(serde_json::to_value(reason).unwrap(), serde_json::json!(name));
1773 assert_eq!(
1774 serde_json::from_value::<FinishReason>(serde_json::json!(name)).unwrap(),
1775 reason
1776 );
1777 }
1778 assert_eq!(
1779 serde_json::from_value::<FinishReason>(serde_json::json!("ReasonFromALaterRelease"))
1780 .unwrap(),
1781 FinishReason::Other
1782 );
1783 }
1784
1785 /// A response persisted before 3.0 still loads.
1786 #[test]
1787 fn a_persisted_response_still_loads() {
1788 let stored = serde_json::json!({
1789 "content": null,
1790 "usage_metadata": null,
1791 "finish_reason": "Safety",
1792 "partial": false,
1793 "turn_complete": true,
1794 "interrupted": false,
1795 "error_code": null,
1796 "error_message": null
1797 });
1798 let response: LlmResponse = serde_json::from_value(stored).unwrap();
1799 assert_eq!(response.finish_reason, Some(FinishReason::Safety));
1800 }
1801}