zai_rs/model/text_embedded/
data.rs1use std::sync::Arc;
2
3use super::{
4 request::{EmbeddingBody, EmbeddingDimensions, EmbeddingInput, EmbeddingModel},
5 response::EmbeddingResponse,
6};
7use crate::client::{
8 endpoints::{ApiBase, EndpointConfig, paths},
9 http::{HttpClient, HttpClientConfig, parse_typed_response},
10};
11
12pub struct EmbeddingRequest {
14 pub key: String,
15 url: String,
16 endpoint_config: EndpointConfig,
17 api_base: ApiBase,
18 http_config: Arc<HttpClientConfig>,
19 body: EmbeddingBody,
20}
21
22impl EmbeddingRequest {
23 pub fn new(key: String, model: EmbeddingModel, input: EmbeddingInput) -> Self {
24 let endpoint_config = EndpointConfig::default();
25 let api_base = ApiBase::PaasV4;
26 let url = endpoint_config.url(&api_base, paths::EMBEDDINGS);
27 let body = EmbeddingBody::new(model, input);
28 Self {
29 key,
30 url,
31 endpoint_config,
32 api_base,
33 http_config: Arc::new(HttpClientConfig::default()),
34 body,
35 }
36 }
37
38 fn rebuild_url(&mut self) {
39 self.url = self.endpoint_config.url(&self.api_base, paths::EMBEDDINGS);
40 }
41
42 pub fn with_base_url(mut self, base: impl Into<String>) -> Self {
43 self.api_base = ApiBase::Custom(base.into());
44 self.rebuild_url();
45 self
46 }
47
48 pub fn with_endpoint_config(mut self, endpoint_config: EndpointConfig) -> Self {
49 self.endpoint_config = endpoint_config;
50 self.rebuild_url();
51 self
52 }
53
54 pub fn with_http_config(mut self, config: HttpClientConfig) -> Self {
55 self.http_config = Arc::new(config);
56 self
57 }
58
59 pub fn with_dimensions(mut self, dims: EmbeddingDimensions) -> Self {
60 self.body = self.body.with_dimensions(dims);
61 self
62 }
63
64 pub fn validate(&self) -> crate::ZaiResult<()> {
66 self.body.validate_model_constraints().map_err(|e| {
67 crate::client::error::ZaiError::ApiError {
68 code: 1200,
69 message: format!("Validation error: {:?}", e),
70 }
71 })
72 }
73
74 pub async fn send(&self) -> crate::ZaiResult<EmbeddingResponse> {
77 if let Err(e) = self.validate() {
78 return Err(crate::client::error::ZaiError::ApiError {
79 code: 1200,
80 message: format!("validation failed: {}", e),
81 });
82 }
83 let resp: reqwest::Response = self.post().await?;
84 let parsed = parse_typed_response::<EmbeddingResponse>(resp).await?;
85 Ok(parsed)
86 }
87
88 #[deprecated(note = "Use send() instead")]
89 pub async fn execute(&self) -> crate::ZaiResult<EmbeddingResponse> {
91 self.send().await
92 }
93}
94
95impl HttpClient for EmbeddingRequest {
96 type Body = EmbeddingBody;
97 type ApiUrl = String;
98 type ApiKey = String;
99
100 fn api_url(&self) -> &Self::ApiUrl {
101 &self.url
102 }
103 fn api_key(&self) -> &Self::ApiKey {
104 &self.key
105 }
106 fn body(&self) -> &Self::Body {
107 &self.body
108 }
109 fn http_config(&self) -> Arc<HttpClientConfig> {
110 Arc::clone(&self.http_config)
111 }
112}