zai_rs/model/text_tokenizer/
data.rs

1use super::request::{TokenizerBody, TokenizerMessage, TokenizerModel};
2use super::response::TokenizerResponse;
3use crate::client::http::HttpClient;
4
5/// Text Tokenizer request client (JSON POST)
6pub struct TokenizerRequest {
7    pub key: String,
8    body: TokenizerBody,
9}
10
11impl TokenizerRequest {
12    pub fn new(key: String, model: TokenizerModel, messages: Vec<TokenizerMessage>) -> Self {
13        let body = TokenizerBody::new(model, messages);
14        Self { key, body }
15    }
16
17    pub fn with_request_id(mut self, v: impl Into<String>) -> Self {
18        self.body = self.body.with_request_id(v);
19        self
20    }
21    pub fn with_user_id(mut self, v: impl Into<String>) -> Self {
22        self.body = self.body.with_user_id(v);
23        self
24    }
25
26    /// Optional: validate constraints before sending
27    pub fn validate(&self) -> anyhow::Result<()> {
28        if self.body.messages.is_empty() {
29            anyhow::bail!("messages must not be empty");
30        }
31        Ok(())
32    }
33
34    /// Send the request and parse typed response.
35    /// Automatically runs `validate()` before sending.
36    pub async fn send(&self) -> anyhow::Result<TokenizerResponse> {
37        self.validate()?;
38        let resp: reqwest::Response = self.post().await?;
39        let parsed = resp.json::<TokenizerResponse>().await?;
40        Ok(parsed)
41    }
42
43    #[deprecated(note = "Use send() instead")]
44    /// Deprecated: use `send()`.
45    pub async fn execute(&self) -> anyhow::Result<TokenizerResponse> {
46        self.send().await
47    }
48}
49
50impl HttpClient for TokenizerRequest {
51    type Body = TokenizerBody;
52    type ApiUrl = &'static str;
53    type ApiKey = String;
54
55    fn api_url(&self) -> &Self::ApiUrl {
56        &"https://open.bigmodel.cn/api/paas/v4/tokenizer"
57    }
58    fn api_key(&self) -> &Self::ApiKey {
59        &self.key
60    }
61    fn body(&self) -> &Self::Body {
62        &self.body
63    }
64}