Skip to main content

adk_tool/example_store/
client.rs

1//! REST client for the Vertex AI Example Store v1beta1 data plane.
2
3use 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/// Configuration for the Vertex AI Example Store client.
19///
20/// The `exampleStores` resource itself is assumed pre-provisioned; this client
21/// only performs data-plane operations against it.
22///
23/// > **Note:** the Example Store API is **v1beta1 (Preview)** and is currently
24/// > served from the `us-central1` region only.
25#[derive(Debug, Clone)]
26pub struct ExampleStoreConfig {
27    /// Google Cloud project ID.
28    pub project_id: String,
29    /// GCP region. Example Store is currently `us-central1` only.
30    pub location: String,
31    /// Example Store ID (the last resource-name segment) or a full
32    /// `projects/*/locations/*/exampleStores/*` resource name.
33    pub example_store: String,
34    /// Optional custom API origin.
35    ///
36    /// The origin receives Google authorization headers plus example data. It
37    /// must not contain userinfo, a path, a query, or a fragment.
38    pub endpoint: Option<String>,
39}
40
41impl ExampleStoreConfig {
42    /// Creates a new config with the given project ID, location, and store.
43    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    /// Builds a config from environment variables.
57    ///
58    /// Reads `GOOGLE_CLOUD_PROJECT`, `GOOGLE_CLOUD_LOCATION`, and
59    /// `EXAMPLE_STORE_ID`. Values are trimmed; blank values count as missing.
60    ///
61    /// # Example
62    ///
63    /// ```no_run
64    /// use adk_tool::example_store::{ExampleStoreClient, ExampleStoreConfig};
65    ///
66    /// # fn main() -> adk_core::Result<()> {
67    /// let config = ExampleStoreConfig::from_env()?;
68    /// let client = ExampleStoreClient::new_with_adc(config)?;
69    /// # Ok(())
70    /// # }
71    /// ```
72    ///
73    /// # Errors
74    ///
75    /// Returns an invalid-input error naming every missing or blank variable.
76    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    /// Sets a custom API origin.
115    ///
116    /// Use only a trusted HTTPS origin, or loopback HTTP for local tests.
117    /// Userinfo, paths, queries, and fragments are rejected before transport.
118    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// ===== Wire types (v1beta1, camelCase JSON) =====
144
145/// A single stored example (`google.cloud.aiplatform.v1beta1.Example`).
146#[derive(Debug, Clone, Serialize, Deserialize)]
147#[serde(rename_all = "camelCase")]
148pub struct Example {
149    /// Optional human-readable display name.
150    #[serde(skip_serializing_if = "Option::is_none")]
151    pub display_name: Option<String>,
152    /// Immutable unique example ID. Generated by the service when absent.
153    #[serde(skip_serializing_if = "Option::is_none")]
154    pub example_id: Option<String>,
155    /// Output only. RFC 3339 creation timestamp.
156    #[serde(skip_serializing_if = "Option::is_none")]
157    pub create_time: Option<String>,
158    /// The example payload: contents plus expected model responses.
159    pub stored_contents_example: StoredContentsExample,
160}
161
162impl Example {
163    /// Creates a new example from a stored-contents payload.
164    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    /// Sets the human-readable display name.
169    #[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    /// Sets the immutable example ID (used for overwrite-by-ID upserts).
176    #[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/// Contents-based example payload
184/// (`google.cloud.aiplatform.v1beta1.StoredContentsExample`).
185#[derive(Debug, Clone, Serialize, Deserialize)]
186#[serde(rename_all = "camelCase")]
187pub struct StoredContentsExample {
188    /// Explicit search key. When absent, the service derives one via
189    /// `search_key_generation_method`.
190    #[serde(skip_serializing_if = "Option::is_none")]
191    pub search_key: Option<String>,
192    /// The conversation contents and expected model responses.
193    pub contents_example: ContentsExample,
194    /// How the service derives a search key when `search_key` is absent.
195    #[serde(skip_serializing_if = "Option::is_none")]
196    pub search_key_generation_method: Option<SearchKeyGenerationMethod>,
197}
198
199impl StoredContentsExample {
200    /// Creates a new stored-contents example.
201    pub fn new(contents_example: ContentsExample) -> Self {
202        Self { search_key: None, contents_example, search_key_generation_method: None }
203    }
204
205    /// Sets an explicit search key.
206    #[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    /// Derives the search key from the last conversation entry (`lastEntry`).
213    #[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/// A conversation plus the expected model responses
221/// (`google.cloud.aiplatform.v1beta1.StoredContentsExample.ContentsExample`).
222#[derive(Debug, Clone, Serialize, Deserialize)]
223#[serde(rename_all = "camelCase")]
224pub struct ContentsExample {
225    /// The conversation contents leading up to the expected response.
226    pub contents: Vec<Content>,
227    /// The expected model responses for `contents`.
228    pub expected_contents: Vec<ExpectedContent>,
229}
230
231impl ContentsExample {
232    /// Creates a contents example, wrapping each expected response content.
233    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/// One expected model response wrapper.
245#[derive(Debug, Clone, Serialize, Deserialize)]
246#[serde(rename_all = "camelCase")]
247pub struct ExpectedContent {
248    /// The expected response content.
249    pub content: Content,
250}
251
252/// How the service derives a search key from example contents.
253#[derive(Debug, Clone, Serialize, Deserialize)]
254#[serde(rename_all = "camelCase")]
255pub struct SearchKeyGenerationMethod {
256    /// Derive the search key from the last conversation entry.
257    #[serde(skip_serializing_if = "Option::is_none")]
258    pub last_entry: Option<LastEntry>,
259}
260
261impl SearchKeyGenerationMethod {
262    /// The `{"lastEntry": {}}` generation method.
263    pub fn last_entry() -> Self {
264        Self { last_entry: Some(LastEntry {}) }
265    }
266}
267
268/// Marker for last-entry search-key generation. Serializes as `{}`.
269#[derive(Debug, Clone, Serialize, Deserialize, Default)]
270pub struct LastEntry {}
271
272/// Request body for `exampleStores.upsertExamples`.
273#[derive(Debug, Clone, Serialize, Deserialize)]
274#[serde(rename_all = "camelCase")]
275pub struct UpsertExamplesRequest {
276    /// The examples to insert or update.
277    pub examples: Vec<Example>,
278    /// When `true`, examples with matching IDs are overwritten.
279    #[serde(skip_serializing_if = "Option::is_none")]
280    pub overwrite: Option<bool>,
281}
282
283impl UpsertExamplesRequest {
284    /// Creates an upsert request for the given examples.
285    pub fn new(examples: Vec<Example>) -> Self {
286        Self { examples, overwrite: None }
287    }
288
289    /// Sets the overwrite flag.
290    #[must_use]
291    pub fn with_overwrite(mut self, overwrite: bool) -> Self {
292        self.overwrite = Some(overwrite);
293        self
294    }
295}
296
297/// Response body for `exampleStores.upsertExamples`.
298#[derive(Debug, Clone, Serialize, Deserialize, Default)]
299#[serde(rename_all = "camelCase")]
300pub struct UpsertExamplesResponse {
301    /// Per-example outcomes, in request order.
302    #[serde(default)]
303    pub results: Vec<UpsertResult>,
304}
305
306/// Per-example upsert outcome: the stored example on success, a
307/// `google.rpc.Status` on failure.
308#[derive(Debug, Clone, Serialize, Deserialize, Default)]
309#[serde(rename_all = "camelCase")]
310pub struct UpsertResult {
311    /// The stored example, present on success.
312    #[serde(skip_serializing_if = "Option::is_none")]
313    pub example: Option<Example>,
314    /// The failure status, present on error.
315    #[serde(skip_serializing_if = "Option::is_none")]
316    pub status: Option<RpcStatus>,
317}
318
319/// A `google.rpc.Status` error payload.
320#[derive(Debug, Clone, Serialize, Deserialize, Default)]
321#[serde(rename_all = "camelCase")]
322pub struct RpcStatus {
323    /// Canonical `google.rpc.Code` value.
324    #[serde(default)]
325    pub code: i32,
326    /// Developer-facing error message.
327    #[serde(default)]
328    pub message: String,
329    /// Detail messages, if any.
330    #[serde(default, skip_serializing_if = "Vec::is_empty")]
331    pub details: Vec<serde_json::Value>,
332}
333
334/// Request body for `exampleStores.searchExamples`.
335#[derive(Debug, Clone, Serialize, Deserialize)]
336#[serde(rename_all = "camelCase")]
337pub struct SearchExamplesRequest {
338    /// Maximum number of results to return.
339    ///
340    /// This is a proto JSON `int64`, which serializes as a **string** on the
341    /// wire (`"topK": "5"`).
342    #[serde(with = "int64_string")]
343    pub top_k: i64,
344    /// The search parameters.
345    pub parameters: SearchExamplesParameters,
346}
347
348impl SearchExamplesRequest {
349    /// Searches by an explicit search-key string.
350    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    /// Searches by conversation contents, deriving the key from the last entry.
364    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    /// Restricts results to examples matching the function-name filter.
381    #[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/// Search parameters wrapper. Currently only stored-contents search exists.
389#[derive(Debug, Clone, Serialize, Deserialize)]
390#[serde(rename_all = "camelCase")]
391pub struct SearchExamplesParameters {
392    /// Parameters for searching `StoredContentsExample` data.
393    pub stored_contents_example_parameters: StoredContentsExampleParameters,
394}
395
396/// Search parameters for stored-contents examples.
397#[derive(Debug, Clone, Serialize, Deserialize)]
398#[serde(rename_all = "camelCase")]
399pub struct StoredContentsExampleParameters {
400    /// Restricts results by the function names present in an example.
401    #[serde(skip_serializing_if = "Option::is_none")]
402    pub function_names: Option<ExamplesArrayFilter>,
403    /// Explicit search-key query. Mutually exclusive with `content_search_key`.
404    #[serde(skip_serializing_if = "Option::is_none")]
405    pub search_key: Option<String>,
406    /// Contents-derived query. Mutually exclusive with `search_key`.
407    #[serde(skip_serializing_if = "Option::is_none")]
408    pub content_search_key: Option<ContentSearchKey>,
409}
410
411/// A search query expressed as conversation contents.
412#[derive(Debug, Clone, Serialize, Deserialize)]
413#[serde(rename_all = "camelCase")]
414pub struct ContentSearchKey {
415    /// The conversation contents to derive the search key from.
416    pub contents: Vec<Content>,
417    /// How the search key is derived from `contents`.
418    pub search_key_generation_method: SearchKeyGenerationMethod,
419}
420
421/// Array filter over string values
422/// (`google.cloud.aiplatform.v1beta1.ExamplesArrayFilter`).
423#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
424#[serde(rename_all = "camelCase")]
425pub struct ExamplesArrayFilter {
426    /// The values to match.
427    pub values: Vec<String>,
428    /// How `values` are combined.
429    pub array_operator: ArrayOperator,
430}
431
432impl ExamplesArrayFilter {
433    /// Matches examples containing any of the given values.
434    pub fn contains_any(values: Vec<String>) -> Self {
435        Self { values, array_operator: ArrayOperator::ContainsAny }
436    }
437
438    /// Matches examples containing all of the given values.
439    pub fn contains_all(values: Vec<String>) -> Self {
440        Self { values, array_operator: ArrayOperator::ContainsAll }
441    }
442}
443
444/// Logical operator for [`ExamplesArrayFilter`].
445#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
446#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
447pub enum ArrayOperator {
448    /// Unspecified operator.
449    ArrayOperatorUnspecified,
450    /// Matches when any value is present.
451    ContainsAny,
452    /// Matches when all values are present.
453    ContainsAll,
454}
455
456/// Response body for `exampleStores.searchExamples`.
457#[derive(Debug, Clone, Serialize, Deserialize, Default)]
458#[serde(rename_all = "camelCase")]
459pub struct SearchExamplesResponse {
460    /// Matching examples ordered by decreasing similarity.
461    #[serde(default)]
462    pub results: Vec<SearchExampleResult>,
463}
464
465/// One search hit: an example plus its similarity score.
466#[derive(Debug, Clone, Serialize, Deserialize)]
467#[serde(rename_all = "camelCase")]
468pub struct SearchExampleResult {
469    /// The matching example.
470    pub example: Example,
471    /// Similarity between the query and the example's search key.
472    #[serde(skip_serializing_if = "Option::is_none")]
473    pub similarity_score: Option<f64>,
474}
475
476/// Request body for `exampleStores.fetchExamples`.
477#[derive(Debug, Clone, Serialize, Deserialize, Default)]
478#[serde(rename_all = "camelCase")]
479pub struct FetchExamplesRequest {
480    /// Maximum number of examples per page.
481    #[serde(skip_serializing_if = "Option::is_none")]
482    pub page_size: Option<i32>,
483    /// Continuation token from a previous response.
484    #[serde(skip_serializing_if = "Option::is_none")]
485    pub page_token: Option<String>,
486    /// Restricts the fetch to these example IDs.
487    #[serde(default, skip_serializing_if = "Vec::is_empty")]
488    pub example_ids: Vec<String>,
489    /// Restricts the fetch by stored-contents attributes.
490    #[serde(skip_serializing_if = "Option::is_none")]
491    pub stored_contents_example_filter: Option<StoredContentsExampleFilter>,
492}
493
494impl FetchExamplesRequest {
495    /// Creates an empty fetch request (first page, no filters).
496    pub fn new() -> Self {
497        Self::default()
498    }
499
500    /// Sets the page size.
501    #[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    /// Sets the continuation token.
508    #[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    /// Restricts the fetch to the given example IDs.
515    #[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    /// Restricts the fetch by stored-contents attributes.
522    #[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/// Fetch filter over stored-contents attributes.
530#[derive(Debug, Clone, Serialize, Deserialize, Default)]
531#[serde(rename_all = "camelCase")]
532pub struct StoredContentsExampleFilter {
533    /// Restricts results to examples with these search keys.
534    #[serde(default, skip_serializing_if = "Vec::is_empty")]
535    pub search_keys: Vec<String>,
536    /// Restricts results by the function names present in an example.
537    #[serde(skip_serializing_if = "Option::is_none")]
538    pub function_names: Option<ExamplesArrayFilter>,
539}
540
541/// Response body for `exampleStores.fetchExamples`.
542#[derive(Debug, Clone, Serialize, Deserialize, Default)]
543#[serde(rename_all = "camelCase")]
544pub struct FetchExamplesResponse {
545    /// The fetched examples.
546    #[serde(default)]
547    pub examples: Vec<Example>,
548    /// Continuation token; absent or empty on the last page.
549    #[serde(default, skip_serializing_if = "Option::is_none")]
550    pub next_page_token: Option<String>,
551}
552
553/// Proto JSON `int64` codec: serializes as a decimal string, accepts either a
554/// string or a bare number on input (both are valid per the proto3 JSON spec).
555mod 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
591// ===== Client =====
592
593// Slots are named by failure class, not by literal: the pre-migration
594// internal-error code `tool.example_store.internal` rides in the
595// `invalid_response` slot, so every error code this client ever stamped
596// survives the adk-gcp migration exactly.
597const 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    // The synchronous data plane has no long-running operations; required by
610    // the table but never stamped.
611    operation_failed: "tool.example_store.operation_failed",
612};
613
614/// ADC-authenticated REST client for the Example Store v1beta1 data plane.
615///
616/// Performs [`upsert_examples`](Self::upsert_examples),
617/// [`search_examples`](Self::search_examples), and
618/// [`fetch_examples`](Self::fetch_examples) against a pre-provisioned
619/// `projects/*/locations/*/exampleStores/*` resource. Store creation and
620/// deletion are control-plane provisioning concerns and are out of scope.
621///
622/// > **Note:** the Example Store API is **v1beta1 (Preview)** and is currently
623/// > served from the `us-central1` region only.
624pub 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        // The transport carries credentials; expose only the resource name.
632        f.debug_struct("ExampleStoreClient")
633            .field("store_path", &self.store_path)
634            .finish_non_exhaustive()
635    }
636}
637
638impl ExampleStoreClient {
639    /// Creates a new client using Application Default Credentials (ADC).
640    ///
641    /// # Example
642    ///
643    /// ```no_run
644    /// use adk_tool::example_store::{ExampleStoreClient, ExampleStoreConfig};
645    ///
646    /// # fn main() -> adk_core::Result<()> {
647    /// let config = ExampleStoreConfig::new("my-project", "us-central1", "my-store");
648    /// let client = ExampleStoreClient::new_with_adc(config)?;
649    /// # Ok(())
650    /// # }
651    /// ```
652    ///
653    /// # Errors
654    ///
655    /// Returns an error when ADC cannot be constructed, the endpoint is not a
656    /// valid secure origin, or the redirect-disabled HTTP client cannot be
657    /// constructed.
658    pub fn new_with_adc(config: ExampleStoreConfig) -> Result<Self> {
659        Self::build(config, None)
660    }
661
662    /// Creates a new client with explicit credentials.
663    ///
664    /// # Errors
665    ///
666    /// Returns an error when the endpoint is not a valid secure origin or the
667    /// redirect-disabled HTTP client cannot be constructed.
668    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    /// The full `projects/*/locations/*/exampleStores/*` resource name this
686    /// client operates on.
687    pub fn store_resource_name(&self) -> &str {
688        &self.store_path
689    }
690
691    /// Inserts or updates examples in the store.
692    ///
693    /// `POST {store}:upsertExamples` with `{"examples": [...], "overwrite": ...}`.
694    /// The response carries one result per input example: the stored example on
695    /// success, or a `google.rpc.Status` on per-example failure. Per-example
696    /// failures do **not** fail the request; inspect
697    /// [`UpsertResult::status`] to detect them.
698    ///
699    /// # Errors
700    ///
701    /// Returns an error on transport failure, timeout, a non-success HTTP
702    /// status, or an unparseable response body.
703    pub async fn upsert_examples(
704        &self,
705        request: UpsertExamplesRequest,
706    ) -> Result<UpsertExamplesResponse> {
707        self.post_verb("upsertExamples", &request).await
708    }
709
710    /// Retrieves the top-k examples most similar to a query.
711    ///
712    /// `POST {store}:searchExamples`. The `topK` field is a proto JSON `int64`
713    /// and serializes as a string. Results are ordered by decreasing
714    /// [`SearchExampleResult::similarity_score`].
715    ///
716    /// # Errors
717    ///
718    /// Returns an error on transport failure, timeout, a non-success HTTP
719    /// status, or an unparseable response body.
720    pub async fn search_examples(
721        &self,
722        request: SearchExamplesRequest,
723    ) -> Result<SearchExamplesResponse> {
724        self.post_verb("searchExamples", &request).await
725    }
726
727    /// Fetches examples by ID or filter, with pagination.
728    ///
729    /// `POST {store}:fetchExamples`. Pass
730    /// [`FetchExamplesResponse::next_page_token`] back via
731    /// [`FetchExamplesRequest::with_page_token`] to continue.
732    ///
733    /// # Errors
734    ///
735    /// Returns an error on transport failure, timeout, a non-success HTTP
736    /// status, or an unparseable response body.
737    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    // async: the credentials builder requires an ambient tokio runtime.
811    #[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}