Skip to main content

openai_compat/types/
moderations.rs

1//! Moderation types, mirroring `openai-python/src/openai/types/moderation*.py`.
2
3use std::collections::HashMap;
4
5use serde::{Deserialize, Serialize};
6
7/// `input` accepts a string or an array of strings.
8/// (Multimodal moderation input is out of scope for v0.1.)
9#[derive(Debug, Clone, Serialize, Deserialize)]
10#[serde(untagged)]
11pub enum ModerationInput {
12    Text(String),
13    Texts(Vec<String>),
14}
15
16impl From<&str> for ModerationInput {
17    fn from(text: &str) -> Self {
18        Self::Text(text.to_string())
19    }
20}
21
22impl From<String> for ModerationInput {
23    fn from(text: String) -> Self {
24        Self::Text(text)
25    }
26}
27
28impl From<Vec<String>> for ModerationInput {
29    fn from(texts: Vec<String>) -> Self {
30        Self::Texts(texts)
31    }
32}
33
34/// Request body for `POST /moderations`.
35#[derive(Debug, Clone, Serialize)]
36pub struct ModerationRequest {
37    pub input: ModerationInput,
38    #[serde(skip_serializing_if = "Option::is_none")]
39    pub model: Option<String>,
40}
41
42impl ModerationRequest {
43    pub fn new(input: impl Into<ModerationInput>) -> Self {
44        Self {
45            input: input.into(),
46            model: None,
47        }
48    }
49
50    pub fn model(mut self, model: impl Into<String>) -> Self {
51        self.model = Some(model.into());
52        self
53    }
54}
55
56/// One moderation verdict. Category names vary by moderation model, so
57/// categories and scores are kept as maps; values may be null for categories
58/// a model does not support.
59#[derive(Debug, Clone, Serialize, Deserialize)]
60#[non_exhaustive]
61pub struct ModerationResult {
62    pub flagged: bool,
63    #[serde(default)]
64    pub categories: HashMap<String, Option<bool>>,
65    #[serde(default)]
66    pub category_scores: HashMap<String, Option<f64>>,
67}
68
69/// Response from `POST /moderations`.
70#[derive(Debug, Clone, Serialize, Deserialize)]
71#[non_exhaustive]
72pub struct ModerationResponse {
73    pub id: String,
74    pub model: String,
75    pub results: Vec<ModerationResult>,
76}