Skip to main content

adk_tool/example_store/
provider.rs

1//! Few-shot retrieval provider that injects Example Store hits into requests.
2
3use super::client::{
4    ExampleStoreClient, ExamplesArrayFilter, SearchExampleResult, SearchExamplesRequest,
5};
6use adk_core::{BeforeModelCallback, BeforeModelResult, Content, Part, Result};
7use std::sync::Arc;
8
9const DEFAULT_TOP_K: i64 = 5;
10
11/// Retrieves top-k similar examples for the incoming user message and injects
12/// them into the request preamble as dynamic few-shot instructions.
13///
14/// Package the provider as a
15/// [`BeforeModelCallback`](adk_core::BeforeModelCallback) via
16/// [`into_before_model_callback`](Self::into_before_model_callback) and
17/// register it on an agent builder. On every model call the callback takes the
18/// text of the most recent `user` content as the search query, calls
19/// [`ExampleStoreClient::search_examples`], and prepends the formatted results
20/// as a leading `user` content — the same position `LlmAgentBuilder`
21/// instructions occupy, so the examples land alongside the system instruction.
22///
23/// # Example
24///
25/// ```no_run
26/// use adk_tool::example_store::{
27///     ExampleStoreClient, ExampleStoreConfig, ExampleStoreProvider,
28/// };
29/// use std::sync::Arc;
30///
31/// # fn demo() -> adk_core::Result<()> {
32/// let client = Arc::new(ExampleStoreClient::new_with_adc(
33///     ExampleStoreConfig::new("my-project", "us-central1", "my-store"),
34/// )?);
35/// let provider = ExampleStoreProvider::new(client).with_top_k(3);
36///
37/// // Register on any agent builder that accepts a BeforeModelCallback:
38/// // LlmAgentBuilder::new("assistant")
39/// //     .model(model)
40/// //     .instruction("You are a helpful assistant.")
41/// //     .before_model_callback(provider.into_before_model_callback())
42/// //     .build()?;
43/// # let _callback = provider.into_before_model_callback();
44/// # Ok(())
45/// # }
46/// ```
47pub struct ExampleStoreProvider {
48    client: Arc<ExampleStoreClient>,
49    top_k: i64,
50    function_names: Option<ExamplesArrayFilter>,
51    fail_open: bool,
52}
53
54impl ExampleStoreProvider {
55    /// Creates a provider retrieving the default top-5 examples per request.
56    pub fn new(client: Arc<ExampleStoreClient>) -> Self {
57        Self { client, top_k: DEFAULT_TOP_K, function_names: None, fail_open: false }
58    }
59
60    /// Sets how many examples are retrieved per request.
61    #[must_use]
62    pub fn with_top_k(mut self, top_k: i64) -> Self {
63        self.top_k = top_k;
64        self
65    }
66
67    /// Restricts retrieval to examples matching the function-name filter.
68    #[must_use]
69    pub fn with_function_names(mut self, function_names: ExamplesArrayFilter) -> Self {
70        self.function_names = Some(function_names);
71        self
72    }
73
74    /// Controls failure behavior inside the callback.
75    ///
76    /// When `true`, a failed retrieval logs a warning and the model call
77    /// proceeds without examples. When `false` (the default), the retrieval
78    /// error propagates and fails the model call.
79    #[must_use]
80    pub fn fail_open(mut self, fail_open: bool) -> Self {
81        self.fail_open = fail_open;
82        self
83    }
84
85    /// Retrieves the top-k examples most similar to `query`.
86    ///
87    /// # Errors
88    ///
89    /// Returns an error when the underlying
90    /// [`ExampleStoreClient::search_examples`] call fails.
91    pub async fn retrieve(&self, query: &str) -> Result<Vec<SearchExampleResult>> {
92        let mut request = SearchExamplesRequest::by_search_key(query, self.top_k);
93        if let Some(function_names) = &self.function_names {
94            request = request.with_function_names(function_names.clone());
95        }
96        Ok(self.client.search_examples(request).await?.results)
97    }
98
99    /// Formats search results as a few-shot instruction block.
100    ///
101    /// Each example renders its conversation and expected responses as
102    /// `role: text` lines. Non-text parts are skipped.
103    pub fn format_examples(results: &[SearchExampleResult]) -> String {
104        let mut block = String::from(
105            "The following retrieved examples show how to respond to similar requests:\n",
106        );
107        for (index, result) in results.iter().enumerate() {
108            block.push_str(&format!("\nExample {}:\n", index + 1));
109            let contents_example = &result.example.stored_contents_example.contents_example;
110            for content in &contents_example.contents {
111                append_content_lines(&mut block, content);
112            }
113            for expected in &contents_example.expected_contents {
114                append_content_lines(&mut block, &expected.content);
115            }
116        }
117        block
118    }
119
120    /// Packages this provider as a [`BeforeModelCallback`].
121    ///
122    /// The callback searches with the text of the most recent `user` content
123    /// and prepends the formatted results as a leading `user` content. When the
124    /// request has no user text or retrieval returns no results, the request
125    /// passes through unmodified.
126    pub fn into_before_model_callback(self) -> BeforeModelCallback {
127        let provider = Arc::new(self);
128        Box::new(move |_ctx, mut request| {
129            let provider = provider.clone();
130            Box::pin(async move {
131                let Some(query) = last_user_text(&request.contents) else {
132                    return Ok(BeforeModelResult::Continue(request));
133                };
134                match provider.retrieve(&query).await {
135                    Ok(results) => {
136                        if !results.is_empty() {
137                            let block = Self::format_examples(&results);
138                            request.contents.insert(0, Content::new("user").with_text(block));
139                        }
140                        Ok(BeforeModelResult::Continue(request))
141                    }
142                    Err(error) if provider.fail_open => {
143                        // The search key is the user's last message, which an error can echo.
144                        tracing::warn!(
145                            error = %error.diagnostics(),
146                            "example store retrieval failed — continuing without examples"
147                        );
148                        Ok(BeforeModelResult::Continue(request))
149                    }
150                    Err(error) => Err(error),
151                }
152            })
153        })
154    }
155}
156
157fn append_content_lines(block: &mut String, content: &Content) {
158    for part in &content.parts {
159        if let Part::Text { text } = part {
160            block.push_str(&format!("  {}: {text}\n", content.role));
161        }
162    }
163}
164
165fn last_user_text(contents: &[Content]) -> Option<String> {
166    contents.iter().rev().find(|content| content.role == "user").and_then(|content| {
167        content
168            .parts
169            .iter()
170            .find_map(|part| if let Part::Text { text } = part { Some(text.clone()) } else { None })
171    })
172}
173
174#[cfg(test)]
175mod tests {
176    use super::super::client::{ContentsExample, Example, StoredContentsExample};
177    use super::*;
178
179    fn result_with_turns(user: &str, model: &str) -> SearchExampleResult {
180        SearchExampleResult {
181            example: Example::new(StoredContentsExample::new(ContentsExample::new(
182                vec![Content::new("user").with_text(user)],
183                vec![Content::new("model").with_text(model)],
184            ))),
185            similarity_score: Some(0.9),
186        }
187    }
188
189    #[test]
190    fn test_format_examples_renders_role_prefixed_turns() {
191        let results =
192            vec![result_with_turns("What is 2+2?", "4"), result_with_turns("Capital?", "Paris")];
193        let block = ExampleStoreProvider::format_examples(&results);
194        assert_eq!(
195            block,
196            "The following retrieved examples show how to respond to similar requests:\n\
197             \nExample 1:\n  user: What is 2+2?\n  model: 4\n\
198             \nExample 2:\n  user: Capital?\n  model: Paris\n",
199        );
200    }
201
202    #[test]
203    fn test_last_user_text_picks_the_most_recent_user_content() {
204        let contents = vec![
205            Content::new("user").with_text("instruction preamble"),
206            Content::new("model").with_text("hello"),
207            Content::new("user").with_text("actual question"),
208        ];
209        assert_eq!(last_user_text(&contents), Some("actual question".to_string()));
210        assert_eq!(last_user_text(&[]), None);
211    }
212}