Skip to main content

zai_rs/model/text_tokenizer/
data.rs

1use super::{
2    request::{TokenizerBody, TokenizerMessage, TokenizerModel},
3    response::TokenizerResponse,
4};
5use crate::client::http::HttpClient;
6
7/// Text Tokenizer request client (JSON POST)
8pub struct TokenizerRequest {
9    pub key: String,
10    body: TokenizerBody,
11}
12
13impl TokenizerRequest {
14    pub fn new(key: String, model: TokenizerModel, messages: Vec<TokenizerMessage>) -> Self {
15        let body = TokenizerBody::new(model, messages);
16        Self { key, body }
17    }
18
19    pub fn with_request_id(mut self, v: impl Into<String>) -> Self {
20        self.body = self.body.with_request_id(v);
21        self
22    }
23    pub fn with_user_id(mut self, v: impl Into<String>) -> Self {
24        self.body = self.body.with_user_id(v);
25        self
26    }
27
28    /// Optional: validate constraints before sending
29    pub fn validate(&self) -> crate::ZaiResult<()> {
30        if self.body.messages.is_empty() {
31            return Err(crate::client::error::ZaiError::ApiError {
32                code: 1200,
33                message: "messages must not be empty".to_string(),
34            });
35        }
36        Ok(())
37    }
38
39    /// Send the request and parse typed response.
40    /// Automatically runs `validate()` before sending.
41    pub async fn send(&self) -> crate::ZaiResult<TokenizerResponse> {
42        self.validate()?;
43        let resp: reqwest::Response = self.post().await?;
44        let parsed = resp.json::<TokenizerResponse>().await?;
45        Ok(parsed)
46    }
47
48    #[deprecated(note = "Use send() instead")]
49    /// Deprecated: use `send()`.
50    pub async fn execute(&self) -> crate::ZaiResult<TokenizerResponse> {
51        self.send().await
52    }
53}
54
55impl HttpClient for TokenizerRequest {
56    type Body = TokenizerBody;
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/tokenizer"
62    }
63    fn api_key(&self) -> &Self::ApiKey {
64        &self.key
65    }
66    fn body(&self) -> &Self::Body {
67        &self.body
68    }
69}