1use adk_core::{AdkError, Content, ErrorCategory, ErrorComponent, Result};
4use adk_gcp::{GcpErrorCodes, GcpErrorContext, GcpHttpClient, truncate_for_error};
5use google_cloud_auth::credentials::Credentials;
6use reqwest::Method;
7use serde::{Deserialize, Serialize};
8use std::time::Duration;
9
10const EXAMPLE_STORE_API_VERSION: &str = "v1beta1";
11const HTTP_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
12const HTTP_REQUEST_TIMEOUT: Duration = Duration::from_secs(120);
13const AUTH_HEADERS_TIMEOUT: Duration = Duration::from_secs(30);
14const ENV_GOOGLE_CLOUD_PROJECT: &str = "GOOGLE_CLOUD_PROJECT";
15const ENV_GOOGLE_CLOUD_LOCATION: &str = "GOOGLE_CLOUD_LOCATION";
16const ENV_EXAMPLE_STORE_ID: &str = "EXAMPLE_STORE_ID";
17
18#[derive(Debug, Clone)]
26pub struct ExampleStoreConfig {
27 pub project_id: String,
29 pub location: String,
31 pub example_store: String,
34 pub endpoint: Option<String>,
39}
40
41impl ExampleStoreConfig {
42 pub fn new(
44 project_id: impl Into<String>,
45 location: impl Into<String>,
46 example_store: impl Into<String>,
47 ) -> Self {
48 Self {
49 project_id: project_id.into(),
50 location: location.into(),
51 example_store: example_store.into(),
52 endpoint: None,
53 }
54 }
55
56 pub fn from_env() -> Result<Self> {
77 let read = |key: &str| {
78 std::env::var(key)
79 .ok()
80 .map(|value| value.trim().to_string())
81 .filter(|value| !value.is_empty())
82 };
83 let project_id = read(ENV_GOOGLE_CLOUD_PROJECT);
84 let location = read(ENV_GOOGLE_CLOUD_LOCATION);
85 let example_store = read(ENV_EXAMPLE_STORE_ID);
86
87 match (project_id, location, example_store) {
88 (Some(project_id), Some(location), Some(example_store)) => {
89 Ok(Self::new(project_id, location, example_store))
90 }
91 (project_id, location, example_store) => {
92 let missing = [
93 (ENV_GOOGLE_CLOUD_PROJECT, project_id.is_none()),
94 (ENV_GOOGLE_CLOUD_LOCATION, location.is_none()),
95 (ENV_EXAMPLE_STORE_ID, example_store.is_none()),
96 ]
97 .into_iter()
98 .filter_map(|(key, is_missing)| is_missing.then_some(key))
99 .collect::<Vec<_>>()
100 .join(", ");
101 Err(AdkError::new(
102 ErrorComponent::Tool,
103 ErrorCategory::InvalidInput,
104 "tool.example_store.missing_env",
105 format!(
106 "missing or blank environment variable(s): {missing}. Set them, or construct the config with ExampleStoreConfig::new",
107 ),
108 )
109 .with_provider("vertex_ai"))
110 }
111 }
112 }
113
114 pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
119 self.endpoint = Some(endpoint.into());
120 self
121 }
122
123 fn endpoint(&self) -> String {
124 let endpoint = self
125 .endpoint
126 .clone()
127 .unwrap_or_else(|| format!("https://{}-aiplatform.googleapis.com", self.location));
128 if endpoint.contains("://") { endpoint } else { format!("https://{endpoint}") }
129 }
130
131 fn store_path(&self) -> String {
132 if self.example_store.contains('/') {
133 self.example_store.clone()
134 } else {
135 format!(
136 "projects/{}/locations/{}/exampleStores/{}",
137 self.project_id, self.location, self.example_store,
138 )
139 }
140 }
141}
142
143#[derive(Debug, Clone, Serialize, Deserialize)]
147#[serde(rename_all = "camelCase")]
148pub struct Example {
149 #[serde(skip_serializing_if = "Option::is_none")]
151 pub display_name: Option<String>,
152 #[serde(skip_serializing_if = "Option::is_none")]
154 pub example_id: Option<String>,
155 #[serde(skip_serializing_if = "Option::is_none")]
157 pub create_time: Option<String>,
158 pub stored_contents_example: StoredContentsExample,
160}
161
162impl Example {
163 pub fn new(stored_contents_example: StoredContentsExample) -> Self {
165 Self { display_name: None, example_id: None, create_time: None, stored_contents_example }
166 }
167
168 #[must_use]
170 pub fn with_display_name(mut self, display_name: impl Into<String>) -> Self {
171 self.display_name = Some(display_name.into());
172 self
173 }
174
175 #[must_use]
177 pub fn with_example_id(mut self, example_id: impl Into<String>) -> Self {
178 self.example_id = Some(example_id.into());
179 self
180 }
181}
182
183#[derive(Debug, Clone, Serialize, Deserialize)]
186#[serde(rename_all = "camelCase")]
187pub struct StoredContentsExample {
188 #[serde(skip_serializing_if = "Option::is_none")]
191 pub search_key: Option<String>,
192 pub contents_example: ContentsExample,
194 #[serde(skip_serializing_if = "Option::is_none")]
196 pub search_key_generation_method: Option<SearchKeyGenerationMethod>,
197}
198
199impl StoredContentsExample {
200 pub fn new(contents_example: ContentsExample) -> Self {
202 Self { search_key: None, contents_example, search_key_generation_method: None }
203 }
204
205 #[must_use]
207 pub fn with_search_key(mut self, search_key: impl Into<String>) -> Self {
208 self.search_key = Some(search_key.into());
209 self
210 }
211
212 #[must_use]
214 pub fn with_last_entry_search_key(mut self) -> Self {
215 self.search_key_generation_method = Some(SearchKeyGenerationMethod::last_entry());
216 self
217 }
218}
219
220#[derive(Debug, Clone, Serialize, Deserialize)]
223#[serde(rename_all = "camelCase")]
224pub struct ContentsExample {
225 pub contents: Vec<Content>,
227 pub expected_contents: Vec<ExpectedContent>,
229}
230
231impl ContentsExample {
232 pub fn new(contents: Vec<Content>, expected: Vec<Content>) -> Self {
234 Self {
235 contents,
236 expected_contents: expected
237 .into_iter()
238 .map(|content| ExpectedContent { content })
239 .collect(),
240 }
241 }
242}
243
244#[derive(Debug, Clone, Serialize, Deserialize)]
246#[serde(rename_all = "camelCase")]
247pub struct ExpectedContent {
248 pub content: Content,
250}
251
252#[derive(Debug, Clone, Serialize, Deserialize)]
254#[serde(rename_all = "camelCase")]
255pub struct SearchKeyGenerationMethod {
256 #[serde(skip_serializing_if = "Option::is_none")]
258 pub last_entry: Option<LastEntry>,
259}
260
261impl SearchKeyGenerationMethod {
262 pub fn last_entry() -> Self {
264 Self { last_entry: Some(LastEntry {}) }
265 }
266}
267
268#[derive(Debug, Clone, Serialize, Deserialize, Default)]
270pub struct LastEntry {}
271
272#[derive(Debug, Clone, Serialize, Deserialize)]
274#[serde(rename_all = "camelCase")]
275pub struct UpsertExamplesRequest {
276 pub examples: Vec<Example>,
278 #[serde(skip_serializing_if = "Option::is_none")]
280 pub overwrite: Option<bool>,
281}
282
283impl UpsertExamplesRequest {
284 pub fn new(examples: Vec<Example>) -> Self {
286 Self { examples, overwrite: None }
287 }
288
289 #[must_use]
291 pub fn with_overwrite(mut self, overwrite: bool) -> Self {
292 self.overwrite = Some(overwrite);
293 self
294 }
295}
296
297#[derive(Debug, Clone, Serialize, Deserialize, Default)]
299#[serde(rename_all = "camelCase")]
300pub struct UpsertExamplesResponse {
301 #[serde(default)]
303 pub results: Vec<UpsertResult>,
304}
305
306#[derive(Debug, Clone, Serialize, Deserialize, Default)]
309#[serde(rename_all = "camelCase")]
310pub struct UpsertResult {
311 #[serde(skip_serializing_if = "Option::is_none")]
313 pub example: Option<Example>,
314 #[serde(skip_serializing_if = "Option::is_none")]
316 pub status: Option<RpcStatus>,
317}
318
319#[derive(Debug, Clone, Serialize, Deserialize, Default)]
321#[serde(rename_all = "camelCase")]
322pub struct RpcStatus {
323 #[serde(default)]
325 pub code: i32,
326 #[serde(default)]
328 pub message: String,
329 #[serde(default, skip_serializing_if = "Vec::is_empty")]
331 pub details: Vec<serde_json::Value>,
332}
333
334#[derive(Debug, Clone, Serialize, Deserialize)]
336#[serde(rename_all = "camelCase")]
337pub struct SearchExamplesRequest {
338 #[serde(with = "int64_string")]
343 pub top_k: i64,
344 pub parameters: SearchExamplesParameters,
346}
347
348impl SearchExamplesRequest {
349 pub fn by_search_key(search_key: impl Into<String>, top_k: i64) -> Self {
351 Self {
352 top_k,
353 parameters: SearchExamplesParameters {
354 stored_contents_example_parameters: StoredContentsExampleParameters {
355 function_names: None,
356 search_key: Some(search_key.into()),
357 content_search_key: None,
358 },
359 },
360 }
361 }
362
363 pub fn by_contents(contents: Vec<Content>, top_k: i64) -> Self {
365 Self {
366 top_k,
367 parameters: SearchExamplesParameters {
368 stored_contents_example_parameters: StoredContentsExampleParameters {
369 function_names: None,
370 search_key: None,
371 content_search_key: Some(ContentSearchKey {
372 contents,
373 search_key_generation_method: SearchKeyGenerationMethod::last_entry(),
374 }),
375 },
376 },
377 }
378 }
379
380 #[must_use]
382 pub fn with_function_names(mut self, function_names: ExamplesArrayFilter) -> Self {
383 self.parameters.stored_contents_example_parameters.function_names = Some(function_names);
384 self
385 }
386}
387
388#[derive(Debug, Clone, Serialize, Deserialize)]
390#[serde(rename_all = "camelCase")]
391pub struct SearchExamplesParameters {
392 pub stored_contents_example_parameters: StoredContentsExampleParameters,
394}
395
396#[derive(Debug, Clone, Serialize, Deserialize)]
398#[serde(rename_all = "camelCase")]
399pub struct StoredContentsExampleParameters {
400 #[serde(skip_serializing_if = "Option::is_none")]
402 pub function_names: Option<ExamplesArrayFilter>,
403 #[serde(skip_serializing_if = "Option::is_none")]
405 pub search_key: Option<String>,
406 #[serde(skip_serializing_if = "Option::is_none")]
408 pub content_search_key: Option<ContentSearchKey>,
409}
410
411#[derive(Debug, Clone, Serialize, Deserialize)]
413#[serde(rename_all = "camelCase")]
414pub struct ContentSearchKey {
415 pub contents: Vec<Content>,
417 pub search_key_generation_method: SearchKeyGenerationMethod,
419}
420
421#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
424#[serde(rename_all = "camelCase")]
425pub struct ExamplesArrayFilter {
426 pub values: Vec<String>,
428 pub array_operator: ArrayOperator,
430}
431
432impl ExamplesArrayFilter {
433 pub fn contains_any(values: Vec<String>) -> Self {
435 Self { values, array_operator: ArrayOperator::ContainsAny }
436 }
437
438 pub fn contains_all(values: Vec<String>) -> Self {
440 Self { values, array_operator: ArrayOperator::ContainsAll }
441 }
442}
443
444#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
446#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
447pub enum ArrayOperator {
448 ArrayOperatorUnspecified,
450 ContainsAny,
452 ContainsAll,
454}
455
456#[derive(Debug, Clone, Serialize, Deserialize, Default)]
458#[serde(rename_all = "camelCase")]
459pub struct SearchExamplesResponse {
460 #[serde(default)]
462 pub results: Vec<SearchExampleResult>,
463}
464
465#[derive(Debug, Clone, Serialize, Deserialize)]
467#[serde(rename_all = "camelCase")]
468pub struct SearchExampleResult {
469 pub example: Example,
471 #[serde(skip_serializing_if = "Option::is_none")]
473 pub similarity_score: Option<f64>,
474}
475
476#[derive(Debug, Clone, Serialize, Deserialize, Default)]
478#[serde(rename_all = "camelCase")]
479pub struct FetchExamplesRequest {
480 #[serde(skip_serializing_if = "Option::is_none")]
482 pub page_size: Option<i32>,
483 #[serde(skip_serializing_if = "Option::is_none")]
485 pub page_token: Option<String>,
486 #[serde(default, skip_serializing_if = "Vec::is_empty")]
488 pub example_ids: Vec<String>,
489 #[serde(skip_serializing_if = "Option::is_none")]
491 pub stored_contents_example_filter: Option<StoredContentsExampleFilter>,
492}
493
494impl FetchExamplesRequest {
495 pub fn new() -> Self {
497 Self::default()
498 }
499
500 #[must_use]
502 pub fn with_page_size(mut self, page_size: i32) -> Self {
503 self.page_size = Some(page_size);
504 self
505 }
506
507 #[must_use]
509 pub fn with_page_token(mut self, page_token: impl Into<String>) -> Self {
510 self.page_token = Some(page_token.into());
511 self
512 }
513
514 #[must_use]
516 pub fn with_example_ids(mut self, example_ids: Vec<String>) -> Self {
517 self.example_ids = example_ids;
518 self
519 }
520
521 #[must_use]
523 pub fn with_filter(mut self, filter: StoredContentsExampleFilter) -> Self {
524 self.stored_contents_example_filter = Some(filter);
525 self
526 }
527}
528
529#[derive(Debug, Clone, Serialize, Deserialize, Default)]
531#[serde(rename_all = "camelCase")]
532pub struct StoredContentsExampleFilter {
533 #[serde(default, skip_serializing_if = "Vec::is_empty")]
535 pub search_keys: Vec<String>,
536 #[serde(skip_serializing_if = "Option::is_none")]
538 pub function_names: Option<ExamplesArrayFilter>,
539}
540
541#[derive(Debug, Clone, Serialize, Deserialize, Default)]
543#[serde(rename_all = "camelCase")]
544pub struct FetchExamplesResponse {
545 #[serde(default)]
547 pub examples: Vec<Example>,
548 #[serde(default, skip_serializing_if = "Option::is_none")]
550 pub next_page_token: Option<String>,
551}
552
553mod int64_string {
556 use serde::de::{Deserializer, Error, Unexpected, Visitor};
557 use serde::ser::Serializer;
558
559 pub fn serialize<S: Serializer>(value: &i64, serializer: S) -> Result<S::Ok, S::Error> {
560 serializer.serialize_str(&value.to_string())
561 }
562
563 pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<i64, D::Error> {
564 struct Int64Visitor;
565
566 impl Visitor<'_> for Int64Visitor {
567 type Value = i64;
568
569 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
570 formatter.write_str("an int64 as a decimal string or number")
571 }
572
573 fn visit_str<E: Error>(self, value: &str) -> Result<i64, E> {
574 value.parse().map_err(|_| Error::invalid_value(Unexpected::Str(value), &self))
575 }
576
577 fn visit_i64<E: Error>(self, value: i64) -> Result<i64, E> {
578 Ok(value)
579 }
580
581 fn visit_u64<E: Error>(self, value: u64) -> Result<i64, E> {
582 i64::try_from(value)
583 .map_err(|_| Error::invalid_value(Unexpected::Unsigned(value), &self))
584 }
585 }
586
587 deserializer.deserialize_any(Int64Visitor)
588 }
589}
590
591const GCP_ERROR_CODES: GcpErrorCodes = GcpErrorCodes {
598 invalid_input: "tool.example_store.invalid_input",
599 unauthorized: "tool.example_store.unauthorized",
600 forbidden: "tool.example_store.forbidden",
601 not_found: "tool.example_store.not_found",
602 rate_limited: "tool.example_store.rate_limited",
603 timeout: "tool.example_store.timeout",
604 unavailable: "tool.example_store.unavailable",
605 credentials_unavailable: "tool.example_store.credentials_unavailable",
606 invalid_response: "tool.example_store.internal",
607 invalid_request: "tool.example_store.invalid_request",
608 upstream_error: "tool.example_store.upstream_error",
609 operation_failed: "tool.example_store.operation_failed",
612};
613
614pub struct ExampleStoreClient {
625 client: GcpHttpClient,
626 store_path: String,
627}
628
629impl std::fmt::Debug for ExampleStoreClient {
630 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
631 f.debug_struct("ExampleStoreClient")
633 .field("store_path", &self.store_path)
634 .finish_non_exhaustive()
635 }
636}
637
638impl ExampleStoreClient {
639 pub fn new_with_adc(config: ExampleStoreConfig) -> Result<Self> {
659 Self::build(config, None)
660 }
661
662 pub fn with_credentials(config: ExampleStoreConfig, credentials: Credentials) -> Result<Self> {
669 Self::build(config, Some(credentials))
670 }
671
672 fn build(config: ExampleStoreConfig, credentials: Option<Credentials>) -> Result<Self> {
673 let errors = GcpErrorContext::new(ErrorComponent::Tool, GCP_ERROR_CODES, "example store");
674 let mut builder = GcpHttpClient::builder(errors, config.endpoint())
675 .api_version(EXAMPLE_STORE_API_VERSION)
676 .connect_timeout(HTTP_CONNECT_TIMEOUT)
677 .request_timeout(HTTP_REQUEST_TIMEOUT)
678 .auth_timeout(AUTH_HEADERS_TIMEOUT);
679 if let Some(credentials) = credentials {
680 builder = builder.credentials(credentials);
681 }
682 Ok(Self { client: builder.build()?, store_path: config.store_path() })
683 }
684
685 pub fn store_resource_name(&self) -> &str {
688 &self.store_path
689 }
690
691 pub async fn upsert_examples(
704 &self,
705 request: UpsertExamplesRequest,
706 ) -> Result<UpsertExamplesResponse> {
707 self.post_verb("upsertExamples", &request).await
708 }
709
710 pub async fn search_examples(
721 &self,
722 request: SearchExamplesRequest,
723 ) -> Result<SearchExamplesResponse> {
724 self.post_verb("searchExamples", &request).await
725 }
726
727 pub async fn fetch_examples(
738 &self,
739 request: FetchExamplesRequest,
740 ) -> Result<FetchExamplesResponse> {
741 self.post_verb("fetchExamples", &request).await
742 }
743
744 async fn post_verb<T: Serialize, R: for<'de> Deserialize<'de>>(
745 &self,
746 verb: &str,
747 body: &T,
748 ) -> Result<R> {
749 tracing::debug!(example_store.verb = verb, "sending example store request");
750 let request = self
751 .client
752 .request(Method::POST, &format!("{}:{verb}", self.store_path))
753 .await?
754 .json(body);
755 let value = self.client.send_value(request).await?;
756 serde_json::from_value(value).map_err(|error| {
757 let error = truncate_for_error(&error.to_string());
758 self.client
759 .errors()
760 .invalid_response(format!("failed to parse example store response JSON: {error}"))
761 })
762 }
763}
764
765#[cfg(test)]
766mod tests {
767 use super::*;
768 use serde_json::json;
769
770 #[test]
771 fn test_top_k_serializes_as_a_string_and_accepts_both_forms() {
772 let request = SearchExamplesRequest::by_search_key("query", 5);
773 let value = serde_json::to_value(&request).unwrap();
774 assert_eq!(value["topK"], json!("5"));
775
776 let from_string: SearchExamplesRequest = serde_json::from_value(json!({
777 "topK": "7",
778 "parameters": { "storedContentsExampleParameters": { "searchKey": "q" } },
779 }))
780 .unwrap();
781 assert_eq!(from_string.top_k, 7);
782
783 let from_number: SearchExamplesRequest = serde_json::from_value(json!({
784 "topK": 7,
785 "parameters": { "storedContentsExampleParameters": { "searchKey": "q" } },
786 }))
787 .unwrap();
788 assert_eq!(from_number.top_k, 7);
789 }
790
791 #[test]
792 fn test_search_key_generation_method_serializes_last_entry_as_empty_object() {
793 let value = serde_json::to_value(SearchKeyGenerationMethod::last_entry()).unwrap();
794 assert_eq!(value, json!({ "lastEntry": {} }));
795 }
796
797 #[test]
798 fn test_config_resolves_bare_ids_and_full_resource_names() {
799 let bare = ExampleStoreConfig::new("p", "us-central1", "store-1");
800 assert_eq!(bare.store_path(), "projects/p/locations/us-central1/exampleStores/store-1");
801
802 let full = ExampleStoreConfig::new(
803 "p",
804 "us-central1",
805 "projects/other/locations/us-central1/exampleStores/store-2",
806 );
807 assert_eq!(full.store_path(), "projects/other/locations/us-central1/exampleStores/store-2");
808 }
809
810 #[tokio::test]
812 async fn test_endpoint_rejects_cleartext_and_decorated_origins() {
813 let credentials =
814 google_cloud_auth::credentials::api_key_credentials::Builder::new("k").build();
815 let config =
816 ExampleStoreConfig::new("p", "us-central1", "s").with_endpoint("http://example.com");
817 let error = ExampleStoreClient::with_credentials(config, credentials.clone()).unwrap_err();
818 assert!(error.message.contains("HTTPS"), "unexpected error: {}", error.message);
819
820 let config = ExampleStoreConfig::new("p", "us-central1", "s")
821 .with_endpoint("https://example.com/path");
822 let error = ExampleStoreClient::with_credentials(config, credentials).unwrap_err();
823 assert!(error.message.contains("origin"), "unexpected error: {}", error.message);
824 }
825}