use serde::{Deserialize, Serialize};
use crate::model::CitationSource;
use crate::tool::ToolContext;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct GroundingSource {
pub uri: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
pub tool: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub document_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub chunk_id: Option<String>,
}
impl GroundingSource {
pub fn new(tool: impl Into<String>, uri: impl Into<String>) -> Self {
Self { uri: uri.into(), title: None, tool: tool.into(), document_id: None, chunk_id: None }
}
#[must_use]
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
#[must_use]
pub fn with_document_id(mut self, document_id: impl Into<String>) -> Self {
self.document_id = Some(document_id.into());
self
}
#[must_use]
pub fn with_chunk_id(mut self, chunk_id: impl Into<String>) -> Self {
self.chunk_id = Some(chunk_id.into());
self
}
}
pub fn record_grounding_sources(
ctx: &dyn ToolContext,
sources: impl IntoIterator<Item = GroundingSource>,
) {
let mut actions = ctx.actions();
for source in sources {
if !actions.grounding_sources.contains(&source) {
actions.grounding_sources.push(source);
}
}
ctx.set_actions(actions);
}
pub fn bind_markdown_citations(text: &str, sources: &[GroundingSource]) -> Vec<CitationSource> {
let mut citations = Vec::new();
let mut search_from = 0;
while let Some(open) = text[search_from..].find('[').map(|i| search_from + i) {
search_from = open + 1;
let Some(close) = text[open + 1..].find("](").map(|i| open + 1 + i) else {
break;
};
if text[open + 1..close].contains(['[', ']']) {
continue;
}
let target_start = close + 2;
let Some(end) = text[target_start..].find(')').map(|i| target_start + i) else {
continue;
};
let target = text[target_start..end].trim();
let uri = target.split_once(char::is_whitespace).map_or(target, |(uri, _title)| uri);
let uri = uri.strip_prefix('<').and_then(|uri| uri.strip_suffix('>')).unwrap_or(uri);
if let Some(source) = sources.iter().find(|source| source.uri == uri) {
citations.push(CitationSource {
uri: Some(source.uri.clone()),
title: source.title.clone(),
start_index: i32::try_from(text[..open].chars().count()).ok(),
end_index: i32::try_from(text[..=end].chars().count()).ok(),
license: None,
publication_date: None,
});
search_from = end + 1;
}
}
citations
}
#[cfg(test)]
mod tests {
use super::*;
fn sources() -> Vec<GroundingSource> {
vec![
GroundingSource::new("rag_search", "https://example.com/a").with_title("A"),
GroundingSource::new("rag_search", "https://example.com/b?x=1&y=2"),
]
}
#[test]
fn binds_only_links_to_recorded_sources_with_character_offsets() {
let text = "日本 [first](https://example.com/a) and [no](https://example.com/z) \
[second](<https://example.com/a> \"Title\").";
let citations = bind_markdown_citations(text, &sources());
let offsets: Vec<(Option<i32>, Option<i32>)> =
citations.iter().map(|c| (c.start_index, c.end_index)).collect();
assert_eq!(citations.len(), 2);
let first_start = "日本 ".chars().count() as i32;
let first_end = first_start + "[first](https://example.com/a)".chars().count() as i32;
assert_eq!(offsets[0], (Some(first_start), Some(first_end)));
assert!(citations.iter().all(|c| c.uri.as_deref() == Some("https://example.com/a")));
assert!(citations.iter().all(|c| c.title.as_deref() == Some("A")));
}
#[test]
fn a_uri_that_only_resembles_a_source_is_not_bound() {
for text in [
"[x](https://example.com/a/)",
"[x](https://example.com/aa)",
"[x](HTTPS://example.com/a)",
"[x] (https://example.com/a)",
"[x](https://example.com/a",
"https://example.com/a",
] {
assert!(bind_markdown_citations(text, &sources()).is_empty(), "{text}");
}
}
#[test]
fn a_nested_bracket_binds_the_inner_link() {
let citations = bind_markdown_citations("[a [b](https://example.com/a)", &sources());
assert_eq!(citations.len(), 1);
assert_eq!(citations[0].start_index, Some(3));
}
#[test]
fn grounding_sources_serialize_in_camel_case_without_empty_fields() {
let source = GroundingSource::new("rag_search", "https://example.com/a")
.with_document_id("doc")
.with_chunk_id("doc_0");
assert_eq!(
serde_json::to_value(&source).unwrap(),
serde_json::json!({
"uri": "https://example.com/a",
"tool": "rag_search",
"documentId": "doc",
"chunkId": "doc_0",
})
);
}
}