Skip to main content

zai_rs/model/text_embedded/
data.rs

1use super::{
2    request::{EmbeddingBody, EmbeddingDimensions, EmbeddingInput, EmbeddingModel},
3    response::EmbeddingResponse,
4};
5use crate::client::ZaiClient;
6
7/// Builder for generating text embeddings through a [`ZaiClient`].
8///
9/// Credentials and transport live on the `ZaiClient`, passed to
10/// [`send_via`](Self::send_via).
11pub struct EmbeddingRequest {
12    body: EmbeddingBody,
13}
14
15impl EmbeddingRequest {
16    /// Create a new embedding request for the given model and input.
17    pub fn new(model: EmbeddingModel, input: EmbeddingInput) -> Self {
18        Self {
19            body: EmbeddingBody::new(model, input),
20        }
21    }
22
23    /// Set the embedding vector dimensionality.
24    pub fn with_dimensions(mut self, dims: EmbeddingDimensions) -> Self {
25        self.body = self.body.with_dimensions(dims);
26        self
27    }
28
29    /// Validate input and model/dimension constraints before sending.
30    pub fn validate(&self) -> crate::ZaiResult<()> {
31        self.body.validate_model_constraints().map_err(|error| {
32            crate::client::error::ZaiError::ApiError {
33                code: crate::client::error::codes::SDK_VALIDATION,
34                message: format!("embedding request validation failed: {}", error.code),
35            }
36        })
37    }
38
39    /// Send via a [`ZaiClient`] and parse the typed response.
40    pub async fn send_via(&self, client: &ZaiClient) -> crate::ZaiResult<EmbeddingResponse> {
41        self.validate()?;
42        let route = crate::client::routes::EMBEDDINGS_CREATE;
43        let url = client.endpoints().resolve_route(route, &[])?;
44        client
45            .send_json::<_, EmbeddingResponse>(route.method(), url, &self.body)
46            .await
47    }
48}