1use serde::{Deserialize, Serialize};
11
12use crate::model::CitationSource;
13use crate::tool::ToolContext;
14
15#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "camelCase")]
30#[non_exhaustive]
31pub struct GroundingSource {
32 pub uri: String,
34 #[serde(default, skip_serializing_if = "Option::is_none")]
36 pub title: Option<String>,
37 pub tool: String,
39 #[serde(default, skip_serializing_if = "Option::is_none")]
41 pub document_id: Option<String>,
42 #[serde(default, skip_serializing_if = "Option::is_none")]
44 pub chunk_id: Option<String>,
45}
46
47impl GroundingSource {
48 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 #[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 #[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 #[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
75pub 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
103pub 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 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}