Skip to main content

zai_rs/model/moderation/
data.rs

1//! # Content Moderation API
2//!
3//! This module provides the content moderation client for analyzing text,
4//! image, audio, and video content for safety risks.
5
6use std::sync::Arc;
7
8use super::models::*;
9use crate::client::{
10    endpoints::{ApiBase, EndpointConfig, paths},
11    http::{HttpClient, HttpClientConfig, parse_typed_response},
12};
13
14/// Content moderation client.
15///
16/// This client provides functionality to moderate content for safety risks,
17/// supporting text, image, audio, and video formats.
18///
19/// ## Examples
20///
21/// ```rust,ignore
22/// let api_key = "your-api-key".to_string();
23/// let moderation = Moderation::new_text("审核内容安全样例字符串。", api_key);
24/// let result = moderation.send().await?;
25/// ```
26pub struct Moderation {
27    /// API key for authentication
28    pub key: String,
29    url: String,
30    endpoint_config: EndpointConfig,
31    api_base: ApiBase,
32    http_config: Arc<HttpClientConfig>,
33    /// Moderation request body
34    body: ModerationRequest,
35}
36
37impl Moderation {
38    /// Creates a new moderation request with text content.
39    ///
40    /// ## Arguments
41    ///
42    /// * `text` - The text content to moderate (max 2000 characters)
43    /// * `key` - API key for authentication
44    ///
45    /// ## Returns
46    ///
47    /// A new `Moderation` instance configured for text moderation.
48    pub fn new_text(text: impl Into<String>, key: String) -> Self {
49        let endpoint_config = EndpointConfig::default();
50        let api_base = ApiBase::PaasV4;
51        let url = endpoint_config.url(&api_base, paths::MODERATIONS);
52        let body = ModerationRequest::new_text(text);
53        Self {
54            body,
55            key,
56            url,
57            endpoint_config,
58            api_base,
59            http_config: Arc::new(HttpClientConfig::default()),
60        }
61    }
62
63    /// Creates a new moderation request with multimedia content.
64    ///
65    /// ## Arguments
66    ///
67    /// * `content_type` - The type of multimedia content (image, audio, video)
68    /// * `url` - URL to the multimedia content
69    /// * `key` - API key for authentication
70    ///
71    /// ## Returns
72    ///
73    /// A new `Moderation` instance configured for multimedia moderation.
74    pub fn new_multimedia(content_type: MediaType, url: impl Into<String>, key: String) -> Self {
75        let endpoint_config = EndpointConfig::default();
76        let api_base = ApiBase::PaasV4;
77        let endpoint_url = endpoint_config.url(&api_base, paths::MODERATIONS);
78        let body = ModerationRequest::new_multimedia(content_type, url);
79        Self {
80            body,
81            key,
82            url: endpoint_url,
83            endpoint_config,
84            api_base,
85            http_config: Arc::new(HttpClientConfig::default()),
86        }
87    }
88
89    fn rebuild_url(&mut self) {
90        self.url = self.endpoint_config.url(&self.api_base, paths::MODERATIONS);
91    }
92
93    pub fn with_base_url(mut self, base: impl Into<String>) -> Self {
94        self.api_base = ApiBase::Custom(base.into());
95        self.rebuild_url();
96        self
97    }
98
99    pub fn with_endpoint_config(mut self, endpoint_config: EndpointConfig) -> Self {
100        self.endpoint_config = endpoint_config;
101        self.rebuild_url();
102        self
103    }
104
105    pub fn with_http_config(mut self, config: HttpClientConfig) -> Self {
106        self.http_config = Arc::new(config);
107        self
108    }
109
110    /// Gets mutable access to the request body for further customization.
111    pub fn body_mut(&mut self) -> &mut ModerationRequest {
112        &mut self.body
113    }
114
115    pub fn validate(&self) -> crate::ZaiResult<()> {
116        self.body
117            .validate()
118            .map_err(crate::client::error::ZaiError::from)?;
119        Ok(())
120    }
121
122    /// Sends the moderation request and returns the structured response.
123    ///
124    /// This method automatically validates the request before sending.
125    ///
126    /// ## Returns
127    ///
128    /// A `ModerationResponse` containing the moderation results and usage
129    /// statistics.
130    pub async fn send(&self) -> crate::ZaiResult<ModerationResponse> {
131        self.validate()?;
132
133        let resp: reqwest::Response = self.post().await?;
134
135        let parsed = parse_typed_response::<ModerationResponse>(resp).await?;
136
137        Ok(parsed)
138    }
139}
140
141impl HttpClient for Moderation {
142    type Body = ModerationRequest;
143    type ApiUrl = String;
144    type ApiKey = String;
145
146    /// Returns the Zhipu AI moderation API endpoint URL.
147    fn api_url(&self) -> &Self::ApiUrl {
148        &self.url
149    }
150
151    fn api_key(&self) -> &Self::ApiKey {
152        &self.key
153    }
154
155    fn body(&self) -> &Self::Body {
156        &self.body
157    }
158
159    fn http_config(&self) -> Arc<HttpClientConfig> {
160        Arc::clone(&self.http_config)
161    }
162}