lm15 1.0.0-rc.7

One request and response model for every LLM provider (OpenAI, Anthropic, Gemini, xAI, Groq, Bedrock, Azure, Vertex, local servers), with visible adaptations. Implements the lm15 contract.
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! Configuration (types.md ยง Configuration; INV-004, INV-026..028, INV-050).

use serde_json::Value;

use super::json::{opt_non_empty, positive, JsonObject, VResult, ValidationError};
use super::tools::Tool;
use super::vocab::{
    CacheMode, CachePrefix, CacheRetention, ProbabilityPolicy, ReasoningEffort, ReasoningSummary,
    ToolChoiceMode,
};

/// How the model should use tools.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolChoice {
    pub mode: ToolChoiceMode,
    pub allowed: Vec<String>,
    pub parallel: Option<bool>,
}

impl Default for ToolChoice {
    fn default() -> Self {
        ToolChoice {
            mode: ToolChoiceMode::Auto,
            allowed: Vec::new(),
            parallel: None,
        }
    }
}

impl ToolChoice {
    /// `ToolChoice::from_tools(&tools, mode, parallel)`: names taken from Tool objects.
    pub fn from_tools(
        allowed: &[Tool],
        mode: ToolChoiceMode,
        parallel: Option<bool>,
    ) -> VResult<Self> {
        let choice = ToolChoice {
            mode,
            allowed: allowed.iter().map(|t| t.name().to_string()).collect(),
            parallel,
        };
        choice.validate()?;
        Ok(choice)
    }

    pub fn validate(&self) -> VResult<()> {
        if self.allowed.iter().any(String::is_empty) {
            return Err(ValidationError::value(
                "ToolChoice.allowed must contain non-empty tool names",
            ));
        }
        if self.mode == ToolChoiceMode::None
            && (!self.allowed.is_empty() || self.parallel.is_some())
        {
            return Err(ValidationError::value(
                "ToolChoice(mode='none') cannot specify allowed or parallel",
            ));
        }
        Ok(())
    }
}

/// The one grading table for budget-only classes (MAP-7 rule 3). `off` has
/// no row: it never reaches a budget.
pub const EFFORT_THINKING_BUDGETS: &[(ReasoningEffort, u64)] = &[
    (ReasoningEffort::Minimal, 1024),
    (ReasoningEffort::Low, 2048),
    (ReasoningEffort::Medium, 8192),
    (ReasoningEffort::High, 16384),
    (ReasoningEffort::Xhigh, 24576),
    (ReasoningEffort::Max, 32768),
];

/// The highest effort whose MAP-7 rule 3 budget is at or below `budget`
/// (`Minimal` below 1024): the grading table read the other way.
pub fn effort_for_budget(budget: u64) -> ReasoningEffort {
    EFFORT_THINKING_BUDGETS
        .iter()
        .rev()
        .find(|(_, tokens)| *tokens <= budget)
        .map(|(effort, _)| *effort)
        .unwrap_or(ReasoningEffort::Minimal)
}

/// How much hidden thinking the model does (MAP-7). `effort` is the dial.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reasoning {
    pub effort: ReasoningEffort,
    pub thinking_budget: Option<u64>,
    pub summary: Option<ReasoningSummary>,
}

impl Reasoning {
    pub fn new(effort: ReasoningEffort) -> Self {
        Reasoning {
            effort,
            thinking_budget: None,
            summary: None,
        }
    }

    /// A budget alone: `effort` is filled from MAP-7 rule 3's table read
    /// the other way, the highest level at or below `thinking_budget`
    /// (`Minimal` below 1024; amended 2026-10-10).
    pub fn with_budget(thinking_budget: u64) -> Self {
        Reasoning {
            effort: effort_for_budget(thinking_budget),
            thinking_budget: Some(thinking_budget),
            summary: None,
        }
    }

    pub fn is_off(&self) -> bool {
        self.effort == ReasoningEffort::Off
    }

    pub fn validate(&self) -> VResult<()> {
        positive(self.thinking_budget, "thinking_budget")?;
        if self.is_off() && (self.thinking_budget.is_some() || self.summary.is_some()) {
            return Err(ValidationError::value(
                "Reasoning(effort='off') cannot specify thinking_budget or summary",
            ));
        }
        Ok(())
    }
}

/// Prompt-cache intents (MAP-6).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CacheConfig {
    pub mode: CacheMode,
    pub retention: Option<CacheRetention>,
    pub key: Option<String>,
    pub prefix_until_index: Option<u64>,
    pub prefix: Option<CachePrefix>,
    pub resource: Option<String>,
}

impl Default for CacheConfig {
    fn default() -> Self {
        CacheConfig {
            mode: CacheMode::Auto,
            retention: None,
            key: None,
            prefix_until_index: None,
            prefix: None,
            resource: None,
        }
    }
}

impl CacheConfig {
    pub fn validate(&self) -> VResult<()> {
        opt_non_empty(self.key.as_ref(), "CacheConfig.key")?;
        opt_non_empty(self.resource.as_ref(), "CacheConfig.resource")?;
        if self.mode == CacheMode::Off
            && (self.retention.is_some()
                || self.key.is_some()
                || self.prefix.is_some()
                || self.prefix_until_index.is_some()
                || self.resource.is_some())
        {
            return Err(ValidationError::value(
                "CacheConfig(mode='off') cannot specify retention, key, prefix, prefix_until_index, or resource",
            ));
        }
        if self.prefix.is_some() && self.prefix_until_index.is_some() {
            return Err(ValidationError::value(
                "CacheConfig cannot specify both prefix and prefix_until_index",
            ));
        }
        Ok(())
    }
}

/// Generation parameters. Provider-specific settings go in `extensions`.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Config {
    pub max_tokens: Option<u64>,
    pub temperature: Option<f64>,
    pub top_p: Option<f64>,
    pub top_k: Option<u64>,
    pub stop: Vec<String>,
    pub response_format: Option<JsonObject>,
    pub tool_choice: Option<ToolChoice>,
    pub reasoning: Option<Reasoning>,
    pub cache: Option<CacheConfig>,
    pub service_tier: Option<String>,
    pub user_id: Option<String>,
    pub store: Option<bool>,
    pub logprobs: Option<u64>,
    pub seed: Option<i64>,
    pub frequency_penalty: Option<f64>,
    pub presence_penalty: Option<f64>,
    pub probabilities: Option<ProbabilityPolicy>,
    pub extensions: Option<JsonObject>,
}

impl Config {
    /// Apply INV-004: an empty `extensions` object is stored as absent.
    pub fn normalized(mut self) -> Config {
        if self.extensions.as_ref().is_some_and(JsonObject::is_empty) {
            self.extensions = None;
        }
        self
    }

    /// An all-default Config serializes to `{}` and is omitted from Request.
    pub fn is_default(&self) -> bool {
        *self == Config::default()
    }

    pub fn validate(&self) -> VResult<()> {
        positive(self.max_tokens, "max_tokens")?;
        positive(self.top_k, "top_k")?;
        if let Some(t) = self.temperature {
            if !t.is_finite() || !(0.0..=2.0).contains(&t) {
                return Err(ValidationError::value("temperature must be in [0, 2]"));
            }
        }
        if let Some(p) = self.top_p {
            if !(0.0..=1.0).contains(&p) {
                return Err(ValidationError::value("top_p must be in [0, 1]"));
            }
        }
        for (name, value) in [
            ("frequency_penalty", self.frequency_penalty),
            ("presence_penalty", self.presence_penalty),
        ] {
            if value.is_some_and(|v| !v.is_finite() || !(-2.0..=2.0).contains(&v)) {
                return Err(ValidationError::value(format!("{name} must be in [-2, 2]")));
            }
        }
        if self.stop.iter().any(String::is_empty) {
            return Err(ValidationError::value(
                "stop must contain non-empty strings",
            ));
        }
        if let Some(tc) = &self.tool_choice {
            tc.validate()?;
        }
        if let Some(r) = &self.reasoning {
            r.validate()?;
        }
        if let Some(c) = &self.cache {
            c.validate()?;
        }
        opt_non_empty(self.service_tier.as_ref(), "Config.service_tier")?;
        opt_non_empty(self.user_id.as_ref(), "Config.user_id")?;
        validate_response_format_shape(self.response_format.as_ref())
    }
}

/// INV-050: `response_format` has exactly two shapes.
fn validate_response_format_shape(value: Option<&JsonObject>) -> VResult<()> {
    let Some(value) = value else {
        return Ok(());
    };
    let fmt = value.get("type").and_then(Value::as_str);
    let allowed: &[&str] = match fmt {
        Some("json_object") => &["type"],
        Some("json_schema") => &["type", "schema", "name", "strict"],
        _ => {
            let mut keys: Vec<&String> = value.keys().collect();
            keys.sort();
            return Err(ValidationError::value(format!(
                "response_format must be {{'type': 'json_object'}} or {{'type': 'json_schema', 'schema': {{...}}, 'name'?: str, 'strict'?: bool}}; provider-native shapes go in Config.extensions (got keys {keys:?})"
            )));
        }
    };
    let mut extra: Vec<&String> = value
        .keys()
        .filter(|k| !allowed.contains(&k.as_str()))
        .collect();
    if !extra.is_empty() {
        extra.sort();
        return Err(ValidationError::value(format!(
            "response_format {:?} does not take keys {extra:?}; provider-native shapes go in Config.extensions",
            fmt.unwrap_or_default()
        )));
    }
    if fmt == Some("json_schema") {
        if !value.get("schema").is_some_and(Value::is_object) {
            return Err(ValidationError::value(
                "response_format json_schema requires a 'schema' object",
            ));
        }
        if let Some(name) = value.get("name") {
            if !name.as_str().is_some_and(|n| !n.is_empty()) {
                return Err(ValidationError::value(
                    "response_format name must be a non-empty string",
                ));
            }
        }
        if let Some(strict) = value.get("strict") {
            if !strict.is_boolean() {
                return Err(ValidationError::type_error(
                    "response_format strict must be a bool",
                ));
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn obj(v: Value) -> JsonObject {
        match v {
            Value::Object(m) => m,
            _ => unreachable!(),
        }
    }

    #[test]
    fn inv_004_empty_extensions_normalize_to_absent() {
        let c = Config {
            extensions: Some(JsonObject::new()),
            ..Default::default()
        }
        .normalized();
        assert_eq!(c.extensions, None);
        assert!(c.is_default());
    }

    #[test]
    fn inv_026_reasoning_off_forbids_budget_and_summary() {
        let mut r = Reasoning::new(ReasoningEffort::Off);
        assert!(r.validate().is_ok());
        r.thinking_budget = Some(1024);
        assert!(r.validate().is_err());
        let with_summary = Reasoning {
            effort: ReasoningEffort::Off,
            thinking_budget: None,
            summary: Some(ReasoningSummary::Auto),
        };
        assert!(with_summary.validate().is_err());
        let zero = Reasoning {
            effort: ReasoningEffort::Low,
            thinking_budget: Some(0),
            summary: None,
        };
        assert!(zero.validate().is_err());
    }

    #[test]
    fn inv_027_cache_off_forbids_other_intents() {
        let off = CacheConfig {
            mode: CacheMode::Off,
            key: Some("k".into()),
            ..Default::default()
        };
        assert!(off.validate().is_err());
        let both = CacheConfig {
            prefix: Some(CachePrefix::Stable),
            prefix_until_index: Some(1),
            ..Default::default()
        };
        assert!(both.validate().is_err());
        assert!(CacheConfig {
            mode: CacheMode::Off,
            ..Default::default()
        }
        .validate()
        .is_ok());
    }

    #[test]
    fn inv_028_tool_choice_none_forbids_allowed_and_parallel() {
        let none = ToolChoice {
            mode: ToolChoiceMode::None,
            allowed: vec!["lookup".into()],
            parallel: None,
        };
        assert!(none.validate().is_err());
        let none_parallel = ToolChoice {
            mode: ToolChoiceMode::None,
            allowed: vec![],
            parallel: Some(false),
        };
        assert!(none_parallel.validate().is_err());
        assert!(ToolChoice::default().validate().is_ok());
    }

    #[test]
    fn inv_050_response_format_two_shapes() {
        let ok = Config {
            response_format: Some(obj(json!({"type": "json_object"}))),
            ..Default::default()
        };
        assert!(ok.validate().is_ok());
        let schema = Config {
            response_format: Some(obj(
                json!({"type": "json_schema", "schema": {}, "name": "r", "strict": true}),
            )),
            ..Default::default()
        };
        assert!(schema.validate().is_ok());
        for bad in [
            json!({"format": "json"}),
            json!({"type": "json_object", "schema": {}}),
            json!({"type": "json_schema"}),
            json!({"type": "json_schema", "schema": {}, "strict": 1}),
        ] {
            let c = Config {
                response_format: Some(obj(bad)),
                ..Default::default()
            };
            assert!(c.validate().is_err());
        }
    }

    #[test]
    fn config_ranges() {
        assert!(Config {
            max_tokens: Some(0),
            ..Default::default()
        }
        .validate()
        .is_err());
        assert!(Config {
            temperature: Some(-0.1),
            ..Default::default()
        }
        .validate()
        .is_err());
        assert!(Config {
            top_p: Some(1.5),
            ..Default::default()
        }
        .validate()
        .is_err());
        assert!(Config {
            stop: vec![String::new()],
            ..Default::default()
        }
        .validate()
        .is_err());
        assert!(Config {
            logprobs: Some(0),
            ..Default::default()
        }
        .validate()
        .is_ok());
    }
}