Skip to main content

adk_core/
grounding.rs

1//! Sources a run retrieved, and the citations an answer makes to them.
2//!
3//! A retrieval tool records each source it returned to the model as a [`GroundingSource`] on
4//! its event's [`EventActions::grounding_sources`](crate::EventActions::grounding_sources),
5//! with [`record_grounding_sources`]. An agent collects the sources its run recorded and binds
6//! the markdown links of its final answer that point at one of them into the answer's
7//! [`CitationMetadata`](crate::CitationMetadata), with [`bind_markdown_citations`], so a
8//! citation is checkable: it names a source the run actually retrieved.
9
10use serde::{Deserialize, Serialize};
11
12use crate::model::CitationSource;
13use crate::tool::ToolContext;
14
15/// A source a tool retrieved and gave the model during a run.
16///
17/// # Example
18///
19/// ```rust
20/// use adk_core::GroundingSource;
21///
22/// let source = GroundingSource::new("rag_search", "https://example.com/refunds")
23///     .with_title("Refund policy")
24///     .with_document_id("refunds")
25///     .with_chunk_id("refunds_0");
26/// assert_eq!(source.uri, "https://example.com/refunds");
27/// ```
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "camelCase")]
30#[non_exhaustive]
31pub struct GroundingSource {
32    /// URI of the source, which a citation names.
33    pub uri: String,
34    /// Human-readable title of the source.
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub title: Option<String>,
37    /// Name of the tool that retrieved it.
38    pub tool: String,
39    /// ID of the document the passage came from.
40    #[serde(default, skip_serializing_if = "Option::is_none")]
41    pub document_id: Option<String>,
42    /// ID of the retrieved passage.
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    pub chunk_id: Option<String>,
45}
46
47impl GroundingSource {
48    /// A source at `uri` that `tool` retrieved.
49    pub fn new(tool: impl Into<String>, uri: impl Into<String>) -> Self {
50        Self { uri: uri.into(), title: None, tool: tool.into(), document_id: None, chunk_id: None }
51    }
52
53    /// Sets the source's title.
54    #[must_use]
55    pub fn with_title(mut self, title: impl Into<String>) -> Self {
56        self.title = Some(title.into());
57        self
58    }
59
60    /// Sets the ID of the document the passage came from.
61    #[must_use]
62    pub fn with_document_id(mut self, document_id: impl Into<String>) -> Self {
63        self.document_id = Some(document_id.into());
64        self
65    }
66
67    /// Sets the ID of the retrieved passage.
68    #[must_use]
69    pub fn with_chunk_id(mut self, chunk_id: impl Into<String>) -> Self {
70        self.chunk_id = Some(chunk_id.into());
71        self
72    }
73}
74
75/// Records `sources` on the actions of the tool call `ctx` belongs to.
76///
77/// The agent puts them on the call's event, where they stay in the session, and counts them
78/// as retrieved by the run when it binds the final answer's citations.
79///
80/// # Example
81///
82/// ```rust,ignore
83/// use adk_core::{GroundingSource, record_grounding_sources};
84///
85/// record_grounding_sources(
86///     ctx.as_ref(),
87///     [GroundingSource::new("rag_search", "https://example.com/refunds")],
88/// );
89/// ```
90pub fn record_grounding_sources(
91    ctx: &dyn ToolContext,
92    sources: impl IntoIterator<Item = GroundingSource>,
93) {
94    let mut actions = ctx.actions();
95    for source in sources {
96        if !actions.grounding_sources.contains(&source) {
97            actions.grounding_sources.push(source);
98        }
99    }
100    ctx.set_actions(actions);
101}
102
103/// The markdown links in `text` whose target is the URI of one of `sources`, as citations.
104///
105/// A link is `[label](uri)` or `[label](uri "title")`. Each citation carries the source's
106/// title and the link's character offsets in `text`, the convention of
107/// [`CitationSource::start_index`]. A link to any other URI is not a citation of a retrieved
108/// source and is left out, as is a link whose URI only resembles a source's: URIs match
109/// exactly.
110///
111/// # Example
112///
113/// ```rust
114/// use adk_core::{GroundingSource, bind_markdown_citations};
115///
116/// let sources = [GroundingSource::new("rag_search", "https://example.com/refunds")
117///     .with_title("Refund policy")];
118/// let answer = "Refunds take 30 days ([policy](https://example.com/refunds)). \
119///               See [elsewhere](https://other.example.com).";
120///
121/// let citations = bind_markdown_citations(answer, &sources);
122/// assert_eq!(citations.len(), 1);
123/// assert_eq!(citations[0].uri.as_deref(), Some("https://example.com/refunds"));
124/// assert_eq!(citations[0].title.as_deref(), Some("Refund policy"));
125/// ```
126pub fn bind_markdown_citations(text: &str, sources: &[GroundingSource]) -> Vec<CitationSource> {
127    let mut citations = Vec::new();
128    let mut search_from = 0;
129    while let Some(open) = text[search_from..].find('[').map(|i| search_from + i) {
130        search_from = open + 1;
131        let Some(close) = text[open + 1..].find("](").map(|i| open + 1 + i) else {
132            break;
133        };
134        // A label holds no bracket, so `[a [b](u)` binds the inner link.
135        if text[open + 1..close].contains(['[', ']']) {
136            continue;
137        }
138        let target_start = close + 2;
139        let Some(end) = text[target_start..].find(')').map(|i| target_start + i) else {
140            continue;
141        };
142        let target = text[target_start..end].trim();
143        let uri = target.split_once(char::is_whitespace).map_or(target, |(uri, _title)| uri);
144        let uri = uri.strip_prefix('<').and_then(|uri| uri.strip_suffix('>')).unwrap_or(uri);
145        if let Some(source) = sources.iter().find(|source| source.uri == uri) {
146            citations.push(CitationSource {
147                uri: Some(source.uri.clone()),
148                title: source.title.clone(),
149                start_index: i32::try_from(text[..open].chars().count()).ok(),
150                end_index: i32::try_from(text[..=end].chars().count()).ok(),
151                license: None,
152                publication_date: None,
153            });
154            search_from = end + 1;
155        }
156    }
157    citations
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    fn sources() -> Vec<GroundingSource> {
165        vec![
166            GroundingSource::new("rag_search", "https://example.com/a").with_title("A"),
167            GroundingSource::new("rag_search", "https://example.com/b?x=1&y=2"),
168        ]
169    }
170
171    #[test]
172    fn binds_only_links_to_recorded_sources_with_character_offsets() {
173        let text = "日本 [first](https://example.com/a) and [no](https://example.com/z) \
174                    [second](<https://example.com/a> \"Title\").";
175        let citations = bind_markdown_citations(text, &sources());
176        let offsets: Vec<(Option<i32>, Option<i32>)> =
177            citations.iter().map(|c| (c.start_index, c.end_index)).collect();
178        assert_eq!(citations.len(), 2);
179        let first_start = "日本 ".chars().count() as i32;
180        let first_end = first_start + "[first](https://example.com/a)".chars().count() as i32;
181        assert_eq!(offsets[0], (Some(first_start), Some(first_end)));
182        assert!(citations.iter().all(|c| c.uri.as_deref() == Some("https://example.com/a")));
183        assert!(citations.iter().all(|c| c.title.as_deref() == Some("A")));
184    }
185
186    #[test]
187    fn a_uri_that_only_resembles_a_source_is_not_bound() {
188        for text in [
189            "[x](https://example.com/a/)",
190            "[x](https://example.com/aa)",
191            "[x](HTTPS://example.com/a)",
192            "[x] (https://example.com/a)",
193            "[x](https://example.com/a",
194            "https://example.com/a",
195        ] {
196            assert!(bind_markdown_citations(text, &sources()).is_empty(), "{text}");
197        }
198    }
199
200    #[test]
201    fn a_nested_bracket_binds_the_inner_link() {
202        let citations = bind_markdown_citations("[a [b](https://example.com/a)", &sources());
203        assert_eq!(citations.len(), 1);
204        assert_eq!(citations[0].start_index, Some(3));
205    }
206
207    #[test]
208    fn grounding_sources_serialize_in_camel_case_without_empty_fields() {
209        let source = GroundingSource::new("rag_search", "https://example.com/a")
210            .with_document_id("doc")
211            .with_chunk_id("doc_0");
212        assert_eq!(
213            serde_json::to_value(&source).unwrap(),
214            serde_json::json!({
215                "uri": "https://example.com/a",
216                "tool": "rag_search",
217                "documentId": "doc",
218                "chunkId": "doc_0",
219            })
220        );
221    }
222}