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::http::HttpClient;
6
7/// Text Embedding request client (JSON POST)
8pub struct EmbeddingRequest {
9    pub key: String,
10    body: EmbeddingBody,
11}
12
13impl EmbeddingRequest {
14    pub fn new(key: String, model: EmbeddingModel, input: EmbeddingInput) -> Self {
15        let body = EmbeddingBody::new(model, input);
16        Self { key, body }
17    }
18
19    pub fn with_dimensions(mut self, dims: EmbeddingDimensions) -> Self {
20        self.body = self.body.with_dimensions(dims);
21        self
22    }
23
24    /// Optional: validate constraints before sending
25    pub fn validate(&self) -> crate::ZaiResult<()> {
26        self.body.validate_model_constraints().map_err(|e| {
27            crate::client::error::ZaiError::ApiError {
28                code: 1200,
29                message: format!("Validation error: {:?}", e),
30            }
31        })
32    }
33
34    /// Send the request and parse typed response.
35    /// Automatically runs `validate()` before sending.
36    pub async fn send(&self) -> crate::ZaiResult<EmbeddingResponse> {
37        if let Err(e) = self.validate() {
38            return Err(crate::client::error::ZaiError::ApiError {
39                code: 1200,
40                message: format!("validation failed: {}", e),
41            });
42        }
43        let resp: reqwest::Response = self.post().await?;
44        let parsed = resp.json::<EmbeddingResponse>().await?;
45        Ok(parsed)
46    }
47
48    #[deprecated(note = "Use send() instead")]
49    /// Deprecated: use `send()`.
50    pub async fn execute(&self) -> crate::ZaiResult<EmbeddingResponse> {
51        self.send().await
52    }
53}
54
55impl HttpClient for EmbeddingRequest {
56    type Body = EmbeddingBody;
57    type ApiUrl = &'static str;
58    type ApiKey = String;
59
60    fn api_url(&self) -> &Self::ApiUrl {
61        &"https://open.bigmodel.cn/api/paas/v4/embeddings"
62    }
63    fn api_key(&self) -> &Self::ApiKey {
64        &self.key
65    }
66    fn body(&self) -> &Self::Body {
67        &self.body
68    }
69}