tea-model 0.1.0

Provider-neutral model port for tea-rs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use std::fmt;
use std::str::FromStr;

use tea_protocol::{ModelId, ModelRef, ProviderId, ReasoningEffort, TokenCount};
use thiserror::Error;

use crate::HostedToolKind;

const MAX_DISPLAY_NAME_BYTES: usize = 256;

/// Human-readable bounded model name.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ModelDisplayName(String);

impl ModelDisplayName {
    /// Returns the model display name.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl FromStr for ModelDisplayName {
    type Err = ModelTextParseError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        if value.is_empty()
            || value.len() > MAX_DISPLAY_NAME_BYTES
            || value.chars().any(char::is_control)
        {
            return Err(ModelTextParseError::InvalidDisplayName);
        }
        Ok(Self(value.to_owned()))
    }
}

impl fmt::Display for ModelDisplayName {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.0)
    }
}

/// Error returned when parsing bounded model text values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum ModelTextParseError {
    /// Display name is empty, oversized, or contains control characters.
    #[error("model display name is invalid")]
    InvalidDisplayName,
}

const CAP_IMAGE_INPUT: u16 = 1 << 0;
const CAP_REASONING: u16 = 1 << 1;
const CAP_TOOLS: u16 = 1 << 2;
const CAP_PARALLEL_TOOLS: u16 = 1 << 3;
const CAP_USAGE: u16 = 1 << 4;
const CAP_HOSTED_WEB_SEARCH: u16 = 1 << 5;

/// Provider-neutral capabilities advertised by one model.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ModelCapabilities(u16);

impl ModelCapabilities {
    /// Creates the minimum supported capability set: text input only.
    #[must_use]
    pub const fn text() -> Self {
        Self(0)
    }

    /// Enables image input.
    #[must_use]
    pub const fn with_image_input(mut self) -> Self {
        self.0 |= CAP_IMAGE_INPUT;
        self
    }

    /// Enables reasoning output and options.
    #[must_use]
    pub const fn with_reasoning(mut self) -> Self {
        self.0 |= CAP_REASONING;
        self
    }

    /// Enables tool calls and optionally parallel tool calls.
    #[must_use]
    pub const fn with_tools(mut self, parallel: bool) -> Self {
        self.0 |= CAP_TOOLS;
        if parallel {
            self.0 |= CAP_PARALLEL_TOOLS;
        } else {
            self.0 &= !CAP_PARALLEL_TOOLS;
        }
        self
    }

    /// Enables normalized usage reporting.
    #[must_use]
    pub const fn with_usage_reporting(mut self) -> Self {
        self.0 |= CAP_USAGE;
        self
    }

    /// Enables one provider-hosted tool kind for this model and endpoint.
    #[must_use]
    pub const fn with_hosted_tool(mut self, kind: HostedToolKind) -> Self {
        match kind {
            HostedToolKind::WebSearch => self.0 |= CAP_HOSTED_WEB_SEARCH,
        }
        self
    }

    /// Returns whether text input is accepted.
    #[must_use]
    pub const fn accepts_text(self) -> bool {
        true
    }

    /// Returns whether image input is accepted.
    #[must_use]
    pub const fn accepts_images(self) -> bool {
        self.0 & CAP_IMAGE_INPUT != 0
    }

    /// Returns whether reasoning is supported.
    #[must_use]
    pub const fn supports_reasoning(self) -> bool {
        self.0 & CAP_REASONING != 0
    }

    /// Returns whether tool calls are supported.
    #[must_use]
    pub const fn supports_tools(self) -> bool {
        self.0 & CAP_TOOLS != 0
    }

    /// Returns whether several tool calls may be requested in one response.
    #[must_use]
    pub const fn supports_parallel_tool_calls(self) -> bool {
        self.0 & CAP_PARALLEL_TOOLS != 0
    }

    /// Returns whether usage is reported.
    #[must_use]
    pub const fn reports_usage(self) -> bool {
        self.0 & CAP_USAGE != 0
    }

    /// Returns whether the model/endpoint supports one provider-hosted tool.
    #[must_use]
    pub const fn supports_hosted_tool(self, kind: HostedToolKind) -> bool {
        match kind {
            HostedToolKind::WebSearch => self.0 & CAP_HOSTED_WEB_SEARCH != 0,
        }
    }
}

impl Default for ModelCapabilities {
    fn default() -> Self {
        Self::text()
    }
}

/// Validated provider-neutral reasoning levels supported by one model.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReasoningProfile {
    default_effort: ReasoningEffort,
    supported_efforts: Vec<ReasoningEffort>,
}

impl ReasoningProfile {
    /// Creates a profile with a supported default and unique effort levels.
    ///
    /// # Errors
    ///
    /// Returns an error when no levels are supplied, a level is duplicated,
    /// or the default level is not supported.
    pub fn new(
        default_effort: ReasoningEffort,
        supported_efforts: impl IntoIterator<Item = ReasoningEffort>,
    ) -> Result<Self, ModelSpecError> {
        let mut supported_efforts = supported_efforts.into_iter().collect::<Vec<_>>();
        if supported_efforts.is_empty() {
            return Err(ModelSpecError::EmptyReasoningEfforts);
        }
        supported_efforts.sort_unstable();
        if supported_efforts
            .windows(2)
            .any(|levels| levels[0] == levels[1])
        {
            return Err(ModelSpecError::DuplicateReasoningEffort);
        }
        if !supported_efforts.contains(&default_effort) {
            return Err(ModelSpecError::ReasoningDefaultUnsupported);
        }
        Ok(Self {
            default_effort,
            supported_efforts,
        })
    }

    pub(crate) fn compatible_default() -> Self {
        Self {
            default_effort: ReasoningEffort::Medium,
            supported_efforts: ReasoningEffort::SHORTCUT_LEVELS.to_vec(),
        }
    }

    /// Returns the model default when a session has no explicit selection.
    #[must_use]
    pub const fn default_effort(&self) -> ReasoningEffort {
        self.default_effort
    }

    /// Returns supported levels in canonical ascending order.
    #[must_use]
    pub fn supported_efforts(&self) -> &[ReasoningEffort] {
        &self.supported_efforts
    }

    /// Resolves one requested level using Pi's upward-first clamp rule.
    #[must_use]
    pub fn resolve(&self, requested: ReasoningEffort) -> ReasoningResolution {
        let effective = if self.supported_efforts.contains(&requested) {
            requested
        } else {
            self.supported_efforts
                .iter()
                .copied()
                .find(|candidate| *candidate > requested)
                .or_else(|| {
                    self.supported_efforts
                        .iter()
                        .rev()
                        .copied()
                        .find(|candidate| *candidate < requested)
                })
                .unwrap_or(self.default_effort)
        };
        ReasoningResolution {
            requested,
            effective,
        }
    }
}

/// Result of resolving a requested reasoning level for one model.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReasoningResolution {
    requested: ReasoningEffort,
    effective: ReasoningEffort,
}

impl ReasoningResolution {
    /// Returns the caller's requested level.
    #[must_use]
    pub const fn requested(self) -> ReasoningEffort {
        self.requested
    }

    /// Returns the supported level selected for the model.
    #[must_use]
    pub const fn effective(self) -> ReasoningEffort {
        self.effective
    }

    /// Returns whether resolution changed the caller's request.
    #[must_use]
    pub fn was_clamped(self) -> bool {
        self.requested != self.effective
    }
}

/// Validated provider-neutral model specification.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelSpec {
    model_ref: ModelRef,
    display_name: ModelDisplayName,
    context_window_tokens: TokenCount,
    max_output_tokens: TokenCount,
    capabilities: ModelCapabilities,
    reasoning_profile: Option<ReasoningProfile>,
}

impl ModelSpec {
    /// Creates a validated model specification.
    ///
    /// # Errors
    ///
    /// Returns an error when context/output limits are zero or output exceeds
    /// the full context window.
    pub fn new(
        model_id: ModelId,
        provider_id: ProviderId,
        display_name: ModelDisplayName,
        context_window_tokens: TokenCount,
        max_output_tokens: TokenCount,
        capabilities: ModelCapabilities,
    ) -> Result<Self, ModelSpecError> {
        if context_window_tokens.get() == 0 {
            return Err(ModelSpecError::EmptyContextWindow);
        }
        if max_output_tokens.get() == 0 {
            return Err(ModelSpecError::EmptyOutputLimit);
        }
        if max_output_tokens > context_window_tokens {
            return Err(ModelSpecError::OutputExceedsContext);
        }
        let reasoning_profile = capabilities
            .supports_reasoning()
            .then(ReasoningProfile::compatible_default);
        Ok(Self {
            model_ref: ModelRef::new(provider_id, model_id),
            display_name,
            context_window_tokens,
            max_output_tokens,
            capabilities,
            reasoning_profile,
        })
    }

    /// Replaces the model's supported/default reasoning metadata.
    #[must_use]
    pub fn with_reasoning_profile(mut self, profile: ReasoningProfile) -> Self {
        self.capabilities = self.capabilities.with_reasoning();
        self.reasoning_profile = Some(profile);
        self
    }

    /// Returns the canonical model selector.
    #[must_use]
    pub const fn model_id(&self) -> &ModelId {
        self.model_ref.model_id()
    }

    /// Returns the owning provider selector.
    #[must_use]
    pub const fn provider_id(&self) -> &ProviderId {
        self.model_ref.provider_id()
    }

    /// Returns the complete provider-qualified model identity.
    #[must_use]
    pub const fn model_ref(&self) -> &ModelRef {
        &self.model_ref
    }

    /// Returns the human-readable model name.
    #[must_use]
    pub const fn display_name(&self) -> &ModelDisplayName {
        &self.display_name
    }

    /// Returns the full context-window limit.
    #[must_use]
    pub const fn context_window_tokens(&self) -> TokenCount {
        self.context_window_tokens
    }

    /// Returns the maximum generated output tokens.
    #[must_use]
    pub const fn max_output_tokens(&self) -> TokenCount {
        self.max_output_tokens
    }

    /// Returns provider-neutral model capabilities.
    #[must_use]
    pub const fn capabilities(&self) -> ModelCapabilities {
        self.capabilities
    }

    /// Returns supported/default reasoning metadata for a reasoning model.
    #[must_use]
    pub const fn reasoning_profile(&self) -> Option<&ReasoningProfile> {
        self.reasoning_profile.as_ref()
    }

    /// Resolves an optional session selection against this model.
    ///
    /// A missing selection inherits a reasoning model's default. A requested
    /// level on a non-reasoning model resolves to explicit `off`.
    #[must_use]
    pub fn resolve_reasoning(
        &self,
        requested: Option<ReasoningEffort>,
    ) -> Option<ReasoningResolution> {
        match (&self.reasoning_profile, requested) {
            (Some(profile), Some(requested)) => Some(profile.resolve(requested)),
            (Some(profile), None) => Some(profile.resolve(profile.default_effort())),
            (None, Some(requested)) => Some(ReasoningResolution {
                requested,
                effective: ReasoningEffort::Off,
            }),
            (None, None) => None,
        }
    }
}

/// Error returned when model limits are inconsistent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum ModelSpecError {
    /// Context window must contain at least one token.
    #[error("model context window must be non-zero")]
    EmptyContextWindow,
    /// Output limit must contain at least one token.
    #[error("model output limit must be non-zero")]
    EmptyOutputLimit,
    /// Output token limit exceeds the full context window.
    #[error("model output limit exceeds context window")]
    OutputExceedsContext,
    /// A reasoning profile must advertise at least one level.
    #[error("model reasoning profile is empty")]
    EmptyReasoningEfforts,
    /// A reasoning profile cannot repeat a canonical level.
    #[error("model reasoning profile contains a duplicate effort")]
    DuplicateReasoningEffort,
    /// The model default must be one of its supported levels.
    #[error("model reasoning default is unsupported")]
    ReasoningDefaultUnsupported,
}