Skip to main content

zai_rs/model/
traits.rs

1//! # Core Traits for AI Model Abstractions
2//!
3//! Defines the fundamental traits enabling type-safe interactions with
4//! different AI models and capabilities in the Zhipu AI ecosystem.
5//!
6//! # Trait Categories
7//!
8//! ## Model Identification
9//!
10//! - `ModelName` — Converts model types to string identifiers used in API
11//!   requests
12//!
13//! ## Capability Markers
14//!
15//! These marker traits carry no runtime data but encode model capabilities at
16//! compile time:
17//!
18//! - `Chat` — Synchronous chat completion
19//! - `AsyncChat` — Asynchronous (queued) chat completion
20//! - `ThinkEnable` — Thinking / reasoning mode
21//! - `ReasoningEffortEnable` — `reasoning_effort` depth control (GLM-5.2+)
22//! - `ToolStreamEnable` — Streaming tool-call output
23//! - `VideoGen` — Video generation
24//! - `ImageGen` — Image generation
25//! - `AudioToText` — Speech recognition
26//! - `TextToAudio` — Text-to-speech synthesis
27//! - `VoiceClone` — Voice cloning
28//! - `Ocr` — Optical character recognition
29//!
30//! ## Type-Safety Traits
31//!
32//! - `Bounded` — Compile-time model ↔ message compatibility check
33//! - `StreamState` — Type-state pattern for streaming control
34//!
35//! # Type-State Pattern
36//!
37//! `StreamState` and its implementations (`StreamOn`, `StreamOff`)
38//! enforce streaming vs. non-streaming semantics at the type level, preventing
39//! invalid API usage without any runtime cost.
40//!
41//! # Helper Macros
42//!
43//! - `define_model_type!` — Generates a model struct with `Debug`, `Clone`,
44//!   `Into<String>`, `Serialize`, and `ModelName` impls
45//! - `impl_message_binding!` — Binds one or more message types to a model
46//!   (implements `Bounded`)
47//! - `impl_model_markers!` — Implements multiple capability marker traits on
48//!   one or more models
49
50/// Trait for AI models that can be identified by name.
51///
52/// This trait enables conversion of model types to their string identifiers
53/// used in API requests. All AI model types must implement this trait.
54pub trait ModelName: Into<String> {}
55
56/// Marker trait for compile-time model-message compatibility checking.
57///
58/// This trait is used in conjunction with the type system to ensure that
59/// specific model types are only used with compatible message types,
60/// preventing invalid API calls at compile time.
61pub trait Bounded {}
62
63/// Indicates that a model supports synchronous chat completion.
64///
65/// Models implementing this trait can be used with the chat-completion API for
66/// real-time conversational interactions.
67pub trait Chat {}
68
69/// Indicates that a model supports asynchronous chat completion.
70///
71/// Models implementing this trait can be used with the asynchronous
72/// chat-completion API for queued conversational requests.
73pub trait AsyncChat {}
74
75/// Indicates that a model supports thinking/reasoning capabilities.
76///
77/// Models implementing this trait can enable the provider's extended reasoning
78/// mode. Whether reasoning text is returned is model- and endpoint-dependent.
79pub trait ThinkEnable {}
80
81/// Indicates that a model supports the `reasoning_effort` parameter, which
82/// controls the depth of reasoning when thinking mode is enabled.
83///
84/// Currently supported only by GLM-5.2 and above. See
85/// [`ReasoningEffort`](super::tools::ReasoningEffort) for the available levels.
86pub trait ReasoningEffortEnable {}
87
88/// Indicates that a model supports streaming tool calls (tool_stream
89/// parameter). Only models implementing this marker can enable tool_stream in
90/// requests.
91pub trait ToolStreamEnable {}
92
93/// Indicates that a model supports video generation.
94///
95/// Models implementing this trait can be used to generate videos from
96/// text descriptions or other inputs.
97pub trait VideoGen {}
98
99/// Indicates that a model supports image generation.
100///
101/// Models implementing this trait can be used to generate images from
102/// text descriptions or other inputs.
103pub trait ImageGen {}
104
105/// Indicates that a model supports speech recognition.
106///
107/// Models implementing this trait can convert audio input to text,
108/// supporting various audio formats and languages.
109pub trait AudioToText {}
110
111/// Indicates that a model supports text-to-speech synthesis.
112///
113/// Models implementing this trait can convert text input to audio output,
114/// supporting various voices and audio formats.
115pub trait TextToAudio {}
116
117/// Indicates that a model supports voice cloning.
118///
119/// Models implementing this trait can create synthetic voices that
120/// mimic specific speakers based on audio samples.
121pub trait VoiceClone {}
122
123/// Indicates that a model supports OCR (Optical Character Recognition).
124///
125/// Models implementing this trait can recognize and extract text content
126/// from images, supporting handwritten and printed text in multiple languages.
127pub trait Ocr {}
128
129/// Type-state trait for compile-time streaming capability control.
130///
131/// This trait enables the type system to enforce whether a request
132/// supports streaming (`StreamOn`) or non-streaming (`StreamOff`) responses,
133/// preventing invalid API usage patterns.
134pub trait StreamState {}
135
136/// Type-state indicating that streaming is enabled.
137///
138/// Types parameterized with this marker support Server-Sent Events (SSE)
139/// streaming for real-time response processing.
140pub struct StreamOn;
141
142/// Type-state indicating that streaming is disabled.
143///
144/// Types parameterized with this marker receive complete responses
145/// rather than streaming chunks.
146pub struct StreamOff;
147
148impl StreamState for StreamOn {}
149impl StreamState for StreamOff {}
150
151/// Legacy SSE marker retained for source compatibility.
152///
153/// It has no methods, and no type in this crate currently implements it.
154pub trait SseStreamable {}
155
156/// Macro for defining AI model types with standard implementations.
157///
158/// This macro generates a model type with the following implementations:
159/// - `Debug` and `Clone` traits
160/// - `Into<String>` for API identifier conversion
161/// - `Serialize` for JSON serialization
162/// - `ModelName` trait marker
163///
164/// ## Usage Examples
165///
166/// ```text
167/// // Basic model definition
168/// define_model_type!(GLM4_5, "glm-4.5");
169/// // Model with attributes
170/// define_model_type!(
171///     #[allow(non_camel_case_types)]
172///     GLM4_5_flash,
173///     "glm-4.5-flash"
174/// );
175/// ```
176#[macro_export]
177macro_rules! define_model_type {
178    ($(#[$meta:meta])* $name:ident, $s:expr) => {
179        #[doc = concat!(" AI model type backed by the upstream id `", $s, "`.")]
180        #[derive(Debug, Clone)]
181        $(#[$meta])*
182        pub struct $name {}
183
184        impl ::core::convert::From<$name> for String {
185            fn from(_val: $name) -> Self { $s.to_string() }
186        }
187
188        impl ::serde::Serialize for $name {
189            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
190            where S: ::serde::Serializer {
191                let model_name: String = self.clone().into();
192                serializer.serialize_str(&model_name)
193            }
194        }
195
196        impl $crate::model::traits::ModelName for $name {}
197    };
198}
199
200/// Macro for binding message types to AI models.
201///
202/// This macro creates compile-time associations between model types and
203/// message types, ensuring type safety in chat completion requests.
204///
205/// ## Usage Examples
206///
207/// ```text
208/// // Single message type binding
209/// impl_message_binding!(GLM4_5, TextMessage);
210/// // Multiple message type bindings
211/// impl_message_binding!(GLM4_5, TextMessage, VisionMessage);
212/// ```
213#[macro_export]
214macro_rules! impl_message_binding {
215    // Single message type
216    ($name:ident, $message_type:ty) => {
217        impl $crate::model::traits::Bounded for ($name, $message_type) {}
218    };
219    // Multiple message types
220    ($name:ident, $message_type:ty, $($message_types:ty),+) => {
221        impl $crate::model::traits::Bounded for ($name, $message_type) {}
222        $(
223            impl $crate::model::traits::Bounded for ($name, $message_types) {}
224        )+
225    };
226}
227
228/// Macro for implementing multiple capability traits on model types.
229///
230/// This macro provides a convenient way to mark models with multiple
231/// capabilities in a single declaration.
232///
233/// ## Usage Examples
234///
235/// ```text
236/// // Single model, multiple traits
237/// impl_model_markers!(GLM4_5_flash: AsyncChat, Chat);
238///
239/// // Multiple models, same traits
240/// impl_model_markers!([GLM4_5, GLM4_5_air]: Chat);
241/// ```
242#[macro_export]
243macro_rules! impl_model_markers {
244    // Single model, multiple markers
245    ($model:ident : $($marker:path),+ $(,)?) => {
246        $( impl $marker for $model {} )+
247    };
248    // Multiple models, multiple markers
249    ([$($model:ident),+ ] : $($marker:path),+ $(,)?) => {
250        $( $( impl $marker for $model {} )+ )+
251    };
252}