1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use core::{fmt, str::FromStr};
5use std::error::Error;
6
7pub mod prelude {
8 pub use crate::{
9 AiCapabilityError, AiCapabilityKind, AiCapabilityName, AiCapabilityStatus,
10 AiMemoryCapability, AiModalitySupport, AiReasoningCapability, AiSafetyCapability,
11 AiStreamingSupport, AiStructuredOutputSupport, AiToolUseSupport,
12 };
13}
14
15#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
16pub struct AiCapabilityName(String);
17
18impl AiCapabilityName {
19 pub fn new(value: impl AsRef<str>) -> Result<Self, AiCapabilityError> {
20 non_empty_text(value).map(Self)
21 }
22
23 pub fn as_str(&self) -> &str {
24 &self.0
25 }
26
27 pub fn value(&self) -> &str {
28 self.as_str()
29 }
30
31 pub fn into_string(self) -> String {
32 self.0
33 }
34}
35
36impl AsRef<str> for AiCapabilityName {
37 fn as_ref(&self) -> &str {
38 self.as_str()
39 }
40}
41
42impl fmt::Display for AiCapabilityName {
43 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
44 formatter.write_str(self.as_str())
45 }
46}
47
48impl FromStr for AiCapabilityName {
49 type Err = AiCapabilityError;
50
51 fn from_str(value: &str) -> Result<Self, Self::Err> {
52 Self::new(value)
53 }
54}
55
56impl TryFrom<&str> for AiCapabilityName {
57 type Error = AiCapabilityError;
58
59 fn try_from(value: &str) -> Result<Self, Self::Error> {
60 Self::new(value)
61 }
62}
63
64macro_rules! capability_enum {
65 ($name:ident { $($variant:ident => $label:literal),+ $(,)? }) => {
66 #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
67 pub enum $name {
68 $($variant),+
69 }
70
71 impl $name {
72 pub const ALL: &'static [Self] = &[$(Self::$variant),+];
73
74 pub const fn as_str(self) -> &'static str {
75 match self {
76 $(Self::$variant => $label),+
77 }
78 }
79 }
80
81 impl fmt::Display for $name {
82 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
83 formatter.write_str(self.as_str())
84 }
85 }
86
87 impl FromStr for $name {
88 type Err = AiCapabilityError;
89
90 fn from_str(value: &str) -> Result<Self, Self::Err> {
91 match normalized_label(value)?.as_str() {
92 $($label => Ok(Self::$variant),)+
93 _ => Err(AiCapabilityError::UnknownLabel),
94 }
95 }
96 }
97 };
98}
99
100capability_enum!(AiCapabilityKind {
101 TextGeneration => "text-generation",
102 Chat => "chat",
103 ToolUse => "tool-use",
104 StructuredOutput => "structured-output",
105 JsonMode => "json-mode",
106 Vision => "vision",
107 AudioInput => "audio-input",
108 AudioOutput => "audio-output",
109 ImageGeneration => "image-generation",
110 ImageEditing => "image-editing",
111 Embedding => "embedding",
112 Reranking => "reranking",
113 Reasoning => "reasoning",
114 Realtime => "realtime",
115 Batch => "batch",
116 Moderation => "moderation",
117 Custom => "custom",
118});
119
120capability_enum!(AiCapabilityStatus {
121 Supported => "supported",
122 Unsupported => "unsupported",
123 Preview => "preview",
124 Deprecated => "deprecated",
125 Unknown => "unknown",
126});
127
128capability_enum!(AiModalitySupport {
129 None => "none",
130 Input => "input",
131 Output => "output",
132 InputOutput => "input-output",
133 Unknown => "unknown",
134});
135
136capability_enum!(AiToolUseSupport {
137 None => "none",
138 SingleToolCall => "single-tool-call",
139 ParallelToolCalls => "parallel-tool-calls",
140 RequiredToolChoice => "required-tool-choice",
141 ToolChoice => "tool-choice",
142 Unknown => "unknown",
143});
144
145capability_enum!(AiStreamingSupport {
146 None => "none",
147 Text => "text",
148 Events => "events",
149 Audio => "audio",
150 Multimodal => "multimodal",
151 Unknown => "unknown",
152});
153
154capability_enum!(AiStructuredOutputSupport {
155 None => "none",
156 Json => "json",
157 JsonSchema => "json-schema",
158 Grammar => "grammar",
159 Custom => "custom",
160});
161
162capability_enum!(AiSafetyCapability {
163 Moderation => "moderation",
164 Refusal => "refusal",
165 PolicyFilter => "policy-filter",
166 Citation => "citation",
167 Grounding => "grounding",
168 PiiRedaction => "pii-redaction",
169 Unknown => "unknown",
170});
171
172capability_enum!(AiReasoningCapability {
173 None => "none",
174 Hidden => "hidden",
175 Summary => "summary",
176 Stepwise => "stepwise",
177 ToolAugmented => "tool-augmented",
178 Unknown => "unknown",
179});
180
181capability_enum!(AiMemoryCapability {
182 None => "none",
183 Session => "session",
184 LongTerm => "long-term",
185 External => "external",
186 Unknown => "unknown",
187});
188
189#[derive(Clone, Copy, Debug, Eq, PartialEq)]
190pub enum AiCapabilityError {
191 Empty,
192 UnknownLabel,
193}
194
195impl fmt::Display for AiCapabilityError {
196 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
197 match self {
198 Self::Empty => formatter.write_str("AI capability metadata text cannot be empty"),
199 Self::UnknownLabel => formatter.write_str("unknown AI capability metadata label"),
200 }
201 }
202}
203
204impl Error for AiCapabilityError {}
205
206fn non_empty_text(value: impl AsRef<str>) -> Result<String, AiCapabilityError> {
207 let trimmed = value.as_ref().trim();
208 if trimmed.is_empty() {
209 Err(AiCapabilityError::Empty)
210 } else {
211 Ok(trimmed.to_string())
212 }
213}
214
215fn normalized_label(value: &str) -> Result<String, AiCapabilityError> {
216 let trimmed = value.trim();
217 if trimmed.is_empty() {
218 Err(AiCapabilityError::Empty)
219 } else {
220 Ok(trimmed.to_ascii_lowercase().replace(['_', ' '], "-"))
221 }
222}
223
224#[cfg(test)]
225mod tests {
226 use super::{
227 AiCapabilityError, AiCapabilityKind, AiCapabilityName, AiCapabilityStatus,
228 AiMemoryCapability, AiModalitySupport, AiReasoningCapability, AiSafetyCapability,
229 AiStreamingSupport, AiStructuredOutputSupport, AiToolUseSupport,
230 };
231 use core::{fmt, str::FromStr};
232
233 fn assert_enum_family<T>(variants: &[T]) -> Result<(), AiCapabilityError>
234 where
235 T: Copy + Eq + fmt::Debug + fmt::Display + FromStr<Err = AiCapabilityError>,
236 {
237 for variant in variants {
238 let label = variant.to_string();
239 assert_eq!(label.parse::<T>()?, *variant);
240 assert_eq!(label.replace('-', "_").parse::<T>()?, *variant);
241 assert_eq!(label.replace('-', " ").parse::<T>()?, *variant);
242 }
243 Ok(())
244 }
245
246 #[test]
247 fn validates_capability_names() -> Result<(), AiCapabilityError> {
248 let name = AiCapabilityName::new(" tool-use ")?;
249
250 assert_eq!(name.as_str(), "tool-use");
251 assert_eq!(name.value(), "tool-use");
252 assert_eq!(name.as_ref(), "tool-use");
253 assert_eq!(name.to_string(), "tool-use");
254 assert_eq!(AiCapabilityName::try_from("tool-use")?, name);
255 assert_eq!(name.into_string(), "tool-use".to_string());
256 assert_eq!(AiCapabilityName::new(" "), Err(AiCapabilityError::Empty));
257 Ok(())
258 }
259
260 #[test]
261 fn displays_and_parses_capability_enums() -> Result<(), AiCapabilityError> {
262 assert_enum_family(AiCapabilityKind::ALL)?;
263 assert_enum_family(AiCapabilityStatus::ALL)?;
264 assert_enum_family(AiModalitySupport::ALL)?;
265 assert_enum_family(AiToolUseSupport::ALL)?;
266 assert_enum_family(AiStreamingSupport::ALL)?;
267 assert_enum_family(AiStructuredOutputSupport::ALL)?;
268 assert_enum_family(AiSafetyCapability::ALL)?;
269 assert_enum_family(AiReasoningCapability::ALL)?;
270 assert_enum_family(AiMemoryCapability::ALL)?;
271 assert_eq!(
272 "structured output".parse::<AiCapabilityKind>()?,
273 AiCapabilityKind::StructuredOutput
274 );
275 Ok(())
276 }
277}