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
450
451
452
453
454
455
//! `generationConfig`, `toolConfig` and the cache plan (MAP-5..8 on the
//! Gemini wire). Every refusal here is raised before any wire.

use serde_json::{Map, Number, Value};

use crate::errors::Lm15Error;
use crate::types::{
    CacheMode, CacheRetention, JsonObject, ReasoningEffort, ReasoningSummary, Request, Tool,
    ToolChoiceMode,
};
use crate::wire::BuildContext;

use super::{gemini_level_class, invalid, unsupported};

/// The shared effort → budget grading table (MAP-7 rule 3;
/// `lm15/providers/common.py:386-393` `EFFORT_THINKING_BUDGETS`). The
/// design's one invented mapping, stated and receipted on Gemini 2.5.
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),
];

fn effort_budget(effort: ReasoningEffort) -> Option<u64> {
    EFFORT_THINKING_BUDGETS
        .iter()
        .find(|(e, _)| *e == effort)
        .map(|(_, budget)| *budget)
}

/// Gemini's proto3-JSON form for an integral double is the integer digits
/// (`lm15/providers/gemini.py:208-219` `_gemini_number`; live capture
/// `cases/gemini/temperature.json` sends `"temperature": 1`). A wire
/// dialect fact, not a canonical one: the canonical field stays a float.
pub fn gemini_number(value: f64) -> Value {
    if value.is_finite() && value.fract() == 0.0 && value.abs() < 9.0e15 {
        return Value::from(value as i64);
    }
    Number::from_f64(value)
        .map(Value::Number)
        .unwrap_or(Value::Null)
}

/// The keys of Gemini's Schema object (generate-content#v1beta.Schema):
/// what its OpenAPI fields (`responseSchema`, `parameters`) parse.
const GEMINI_SCHEMA_FIELDS: [&str; 22] = [
    "type",
    "format",
    "title",
    "description",
    "nullable",
    "enum",
    "maxItems",
    "minItems",
    "properties",
    "required",
    "minProperties",
    "maxProperties",
    "minLength",
    "maxLength",
    "pattern",
    "example",
    "anyOf",
    "propertyOrdering",
    "default",
    "items",
    "minimum",
    "maximum",
];

/// MAP-16: can Gemini's OpenAPI field carry `schema`? No, when a schema
/// node — the root, a value of `properties`, `items`, an element of
/// `anyOf` (or `anyOf` itself when it is one object) — is a boolean, has a
/// key that is not a Schema field, has a list `type`, or has an `enum`
/// list with an element that is not a string: the OpenAPI field answers
/// 400 there and the JSON Schema field accepts it (live 2026-09-26,
/// lm15-contract `mapping/gemini-schema-field.json`). Anything else stays
/// on the OpenAPI field; `example` and `default` are values, never walked.
pub fn openapi_schema(schema: &Value) -> bool {
    let mut stack = vec![schema];
    while let Some(node) = stack.pop() {
        let map = match node {
            Value::Bool(_) => return false,
            Value::Object(map) => map,
            _ => continue,
        };
        for (key, value) in map {
            if !GEMINI_SCHEMA_FIELDS.contains(&key.as_str()) {
                return false;
            }
            match (key.as_str(), value) {
                ("type", Value::Array(_)) => return false,
                ("enum", Value::Array(items)) if items.iter().any(|v| !v.is_string()) => {
                    return false
                }
                ("properties", Value::Object(props)) => stack.extend(props.values()),
                ("items", v) => stack.push(v),
                ("anyOf", Value::Array(items)) => stack.extend(items.iter()),
                ("anyOf", v) => stack.push(v),
                _ => {}
            }
        }
    }
    true
}

/// MAP-16 for a response format: `responseSchema` or `responseJsonSchema`.
pub fn schema_field(schema: &Value) -> &'static str {
    if openapi_schema(schema) {
        "responseSchema"
    } else {
        "responseJsonSchema"
    }
}

/// MAP-16 for a function declaration: `parameters` or
/// `parametersJsonSchema`. The schema is verbatim either way (INV-002).
pub fn parameters_field(schema: &Value) -> &'static str {
    if openapi_schema(schema) {
        "parameters"
    } else {
        "parametersJsonSchema"
    }
}

/// `thinkingConfig` (MAP-7 on Gemini; `lm15/providers/gemini.py:706-743`).
fn thinking_config(request: &Request, cx: &BuildContext<'_>) -> Result<Option<Value>, Lm15Error> {
    let Some(reasoning) = &request.config.reasoning else {
        return Ok(None);
    };
    let level_class = gemini_level_class(cx.model);
    let mut thinking = Map::new();
    if reasoning.is_off() {
        if level_class {
            // MAP-7 rule 4 / MAP-5: the Gemini 3 class has no full off
            // switch; 3.7 Flash accepted `thinkingBudget: 0` and still spent
            // 58 tokens (live 2026-09-02) — a silent paid no-op.
            crate::adaptation::adapt("config.reasoning.effort",crate::adaptation::AdaptationAction::Substituted,Some(Value::from("off")),Some(Value::from("minimal")),"the Gemini 3 class has no off switch; the lowest level was sent and thinking spend remains visible in usage")?;
            thinking.insert("thinkingLevel".into(), Value::from("minimal"));
            return Ok(Some(Value::Object(thinking)));
        }
        thinking.insert("thinkingBudget".into(), Value::from(0));
        return Ok(Some(Value::Object(thinking)));
    }
    match reasoning.summary {
        Some(ReasoningSummary::Concise) | Some(ReasoningSummary::Detailed) => {
            crate::adaptation::adapt(
                "config.reasoning.summary",
                crate::adaptation::AdaptationAction::Substituted,
                reasoning.summary.map(|s| Value::from(s.as_str())),
                Some(Value::from("auto")),
                "GenerateContent has includeThoughts only, not summary detail levels",
            )?;
            thinking.insert("includeThoughts".into(), Value::Bool(true));
        }
        // MAP-7 rule 7: `includeThoughts` only when asked.
        Some(ReasoningSummary::Auto) => {
            thinking.insert("includeThoughts".into(), Value::Bool(true));
        }
        None => {}
    }
    if let Some(budget) = reasoning.thinking_budget {
        // MAP-7 rule 5: the budget is the spelling on both classes (3.x
        // accepts it; the docs warn).
        thinking.insert("thinkingBudget".into(), Value::from(budget));
    } else if level_class {
        match reasoning.effort {
            ReasoningEffort::Xhigh | ReasoningEffort::Max => {
                crate::adaptation::adapt("config.reasoning.effort",crate::adaptation::AdaptationAction::Clamped,Some(Value::from(reasoning.effort.as_str())),Some(Value::from("high")),"the Gemini 3 class has thinkingLevel minimal|low|medium|high; high is the ceiling")?;
                thinking.insert("thinkingLevel".into(), Value::from("high"));
            }
            effort => {
                thinking.insert(
                    "thinkingLevel".into(),
                    Value::String(effort.as_str().to_string()),
                );
            }
        }
    } else {
        let budget = effort_budget(reasoning.effort).ok_or_else(|| {
            invalid(
                cx,
                format!(
                    "no thinking budget for effort {:?}",
                    reasoning.effort.as_str()
                ),
            )
        })?;
        thinking.insert("thinkingBudget".into(), Value::from(budget));
    }
    Ok(Some(Value::Object(thinking)))
}

/// `generationConfig` in the reference's insertion order
/// (`lm15/providers/gemini.py:685-745`): `temperature`, `maxOutputTokens`,
/// `topP`, `topK`, `stopSequences`, `responseLogprobs`, `logprobs`,
/// `responseMimeType`, `responseJsonSchema`/`responseSchema`,
/// `thinkingConfig`. Empty when nothing applies (the caller omits it).
pub fn generation_config(
    request: &Request,
    cx: &BuildContext<'_>,
) -> Result<JsonObject, Lm15Error> {
    crate::judgments::note_unmeasurable_probabilities(request, cx.provider)?;
    let config = &request.config;
    let mut out = Map::new();
    if let Some(temperature) = config.temperature {
        out.insert("temperature".into(), gemini_number(temperature));
    }
    if let Some(max_tokens) = config.max_tokens {
        out.insert("maxOutputTokens".into(), Value::from(max_tokens));
    }
    if let Some(top_p) = config.top_p {
        out.insert("topP".into(), gemini_number(top_p));
    }
    if let Some(top_k) = config.top_k {
        out.insert("topK".into(), Value::from(top_k));
    }
    if let Some(v) = config.seed {
        out.insert("seed".into(), Value::from(v));
    }
    if let Some(v) = config.frequency_penalty {
        out.insert("frequencyPenalty".into(), gemini_number(v));
    }
    if let Some(v) = config.presence_penalty {
        out.insert("presencePenalty".into(), gemini_number(v));
    }
    if !config.stop.is_empty() {
        out.insert(
            "stopSequences".into(),
            Value::Array(config.stop.iter().cloned().map(Value::String).collect()),
        );
    }
    if let Some(logprobs) = config.logprobs {
        // Documented wire knobs (doc-based; every currently served model
        // rejects them live with "Logprobs is not enabled" — the server's
        // 400 is the contract, spec/types.md § Config).
        out.insert("responseLogprobs".into(), Value::Bool(true));
        if logprobs > 0 {
            out.insert("logprobs".into(), Value::from(logprobs));
        }
    }
    if let Some(format) = &config.response_format {
        // INV-050 / MAP-8.5: `responseMimeType` plus the schema field by
        // the `additionalProperties` rule; `strict` is satisfied (always
        // constrained), `name` is a label with no slot.
        out.insert(
            "responseMimeType".into(),
            Value::String("application/json".into()),
        );
        if format.get("type").and_then(Value::as_str) == Some("json_schema") {
            let mut schema = format.get("schema").cloned().unwrap_or(Value::Null);
            let found = crate::judgments::judgments_in_schema(&schema);
            if let Some(obj) = schema.as_object() {
                schema = Value::Object(crate::judgments::gemini_schema(obj, &found));
            }
            out.insert(schema_field(&schema).into(), schema);
        }
    }
    if let Some(thinking) = thinking_config(request, cx)? {
        out.insert("thinkingConfig".into(), thinking);
    }
    Ok(out)
}

/// `toolConfig.functionCallingConfig` (MAP-8;
/// `lm15/providers/gemini.py:610-644`), or `None` without a tool choice.
pub fn tool_config(request: &Request, cx: &BuildContext<'_>) -> Result<Option<Value>, Lm15Error> {
    let Some(choice) = &request.config.tool_choice else {
        return Ok(None);
    };
    if choice.parallel == Some(false) {
        // MAP-8 rule 2 (live 2026-09-02): no wire knob; two calls came back
        // on 2.5 and 3.7 with the preference set. The outcome is not
        // observable from usage, so the MAP-6 fallback exception does not
        // apply — raise.
        crate::adaptation::adapt(
            "config.tool_choice.parallel",
            crate::adaptation::AdaptationAction::Dropped,
            Some(Value::Bool(false)),
            None,
            "GenerateContent has no parallel-tool-calls knob and may return several calls",
        )?;
    }
    let mut mode = match choice.mode {
        ToolChoiceMode::None => "NONE",
        ToolChoiceMode::Required => "ANY",
        ToolChoiceMode::Auto => "AUTO",
    };
    let mut allowed: Option<Vec<Value>> = None;
    if !choice.allowed.is_empty() {
        let builtins: Vec<&str> = choice
            .allowed
            .iter()
            .filter(|name| {
                request
                    .tools
                    .iter()
                    .any(|tool| matches!(tool, Tool::Builtin(b) if b.name == **name))
            })
            .map(String::as_str)
            .collect();
        if !builtins.is_empty() {
            return Err(unsupported(
                cx,
                format!(
                    "cannot force builtin tools {builtins:?} — functionCallingConfig addresses function declarations only; googleSearch/codeExecution have no tool_choice form (OpenAI Responses and Anthropic carry builtin forcing)"
                ),
            ));
        }
        allowed = Some(choice.allowed.iter().cloned().map(Value::String).collect());
        if choice.mode == ToolChoiceMode::Auto {
            // `allowedFunctionNames` is only legal with ANY or VALIDATED.
            // VALIDATED = "function call or text, restricted to the
            // allowlist" — exactly canonical mode=auto + allowed.
            mode = "VALIDATED";
        }
    }
    let mut cfg = Map::new();
    cfg.insert("mode".into(), Value::String(mode.into()));
    if let Some(allowed) = allowed {
        cfg.insert("allowedFunctionNames".into(), Value::Array(allowed));
    }
    let mut out = Map::new();
    out.insert("functionCallingConfig".into(), Value::Object(cfg));
    Ok(Some(Value::Object(out)))
}

/// What MAP-6 makes of `config.cache` on this wire.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct CachePlan {
    /// The `cachedContent` resource name to reference, if any.
    pub resource: Option<String>,
    /// The index of the first message the wire carries.
    pub suffix_from: usize,
}

/// `cachedContents/<id>` (`lm15/providers/gemini.py:1537-1538`). A full
/// resource name (Vertex: `projects/…/locations/…/cachedContents/…`) is
/// kept verbatim; the reference would prefix it a second time.
fn cache_resource(id: &str) -> String {
    if id.starts_with("cachedContents/") || id.contains("/cachedContents/") {
        id.to_string()
    } else {
        format!("cachedContents/{id}")
    }
}

/// MAP-6 on Gemini (`lm15/providers/gemini.py:651-680`).
pub fn cache_plan(request: &Request, _cx: &BuildContext<'_>) -> Result<CachePlan, Lm15Error> {
    let mut plan = CachePlan::default();
    let Some(cache) = &request.config.cache else {
        return Ok(plan);
    };
    if cache.mode == CacheMode::Off {
        // MAP-6.2: nothing to send; the wire has no write switch.
        return Ok(plan);
    }
    if cache.key.is_some() {
        crate::adaptation::adapt(
            "config.cache.key",
            crate::adaptation::AdaptationAction::Dropped,
            cache.key.clone().map(Value::String),
            None,
            "GenerateContent has no cache affinity key; implicit caching applies",
        )?;
    }
    if cache.retention.is_some_and(|r| r != CacheRetention::Short) {
        crate::adaptation::adapt(
            "config.cache.retention",
            crate::adaptation::AdaptationAction::Dropped,
            Some(Value::from("long")),
            None,
            "cache lifetime belongs to the stored cache, not this request",
        )?;
    }
    if let Some(resource) = &cache.resource {
        plan.resource = Some(cache_resource(resource));
        if let Some(index) = cache.prefix_until_index {
            let last = request.messages.len().saturating_sub(1) as u64;
            plan.suffix_from = (index.min(last) + 1) as usize;
        }
    }
    Ok(plan)
}

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

    #[test]
    fn integral_floats_take_the_integer_form() {
        assert_eq!(gemini_number(1.0), json!(1));
        assert_eq!(gemini_number(0.8), json!(0.8));
        assert_eq!(gemini_number(0.0), json!(0));
        assert_eq!(gemini_number(-2.0), json!(-2));
    }

    #[test]
    fn schema_field_follows_map_16() {
        assert_eq!(schema_field(&json!({"type": "object"})), "responseSchema");
        assert_eq!(
            schema_field(&json!({"type": "array", "items": {"additionalProperties": false}})),
            "responseJsonSchema"
        );
        assert_eq!(
            parameters_field(&json!({"properties": {"v": {"$ref": "#/$defs/S"}}})),
            "parametersJsonSchema"
        );
        assert_eq!(
            parameters_field(&json!({"properties": {"$ref": {"type": "string"}}})),
            "parameters"
        );
    }

    /// The contract's vectors (skipped when the sibling checkout is absent;
    /// the harness's mapping direction grades them through the vet shim).
    #[test]
    fn map_16_contract_vectors() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../lm15-contract/mapping/gemini-schema-field.json");
        let Ok(raw) = std::fs::read(&path) else {
            return;
        };
        let doc: Value = serde_json::from_slice(&raw).unwrap();
        for case in doc["cases"].as_array().unwrap() {
            assert_eq!(
                openapi_schema(&case["schema"]),
                case["openapi"].as_bool().unwrap(),
                "{}",
                case["id"]
            );
        }
    }

    #[test]
    fn cache_resource_keeps_full_names() {
        assert_eq!(cache_resource("abc"), "cachedContents/abc");
        assert_eq!(cache_resource("cachedContents/abc"), "cachedContents/abc");
        assert_eq!(
            cache_resource("projects/p/locations/l/cachedContents/abc"),
            "projects/p/locations/l/cachedContents/abc"
        );
    }

    #[test]
    fn the_grading_table_is_the_shared_one() {
        assert_eq!(effort_budget(ReasoningEffort::Minimal), Some(1024));
        assert_eq!(effort_budget(ReasoningEffort::Max), Some(32768));
        assert_eq!(effort_budget(ReasoningEffort::Off), None);
    }
}