Skip to main content

rig_core/completion/options/
merge.rs

1//! The one merge of a completion request body: the wire's own encoding of
2//! the request, then the mapped options, then the provider options, then
3//! `additional_params`, then the closed list of [`Rewrite`]s.
4//! [`request_params`] is the only function that builds a [`FinalBody`], and
5//! [`check`] reports every refused option before a wire encodes.
6
7use std::borrow::Cow;
8
9use serde::de::DeserializeOwned;
10use serde::ser::SerializeMap;
11use serde::{Serialize, Serializer};
12use serde_json::{Map, Value};
13
14use super::mapping::{Mapping, OptionName};
15use super::{CacheRetention, OnUnsupported, UnsupportedOption};
16use crate::completion::provider_options::SHARED;
17use crate::completion::{CompletionRequest, ReplayTarget};
18use crate::error::EncodeError;
19use crate::json_utils::{deep_merge, remove_preserving_order};
20use crate::providers::openai::wire::BodyRewrite;
21use crate::wire::Body;
22
23/// The merged request body. Only [`request_params`] builds one.
24/// Serialization writes fields named by [`Rewrite::MoveLast`] after the
25/// other fields, in rewrite order.
26#[derive(Clone, Debug, PartialEq)]
27pub struct FinalBody {
28    fields: Map<String, Value>,
29    last: Vec<&'static str>,
30}
31
32impl Serialize for FinalBody {
33    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
34        let mut map = serializer.serialize_map(Some(self.fields.len()))?;
35        for (key, value) in &self.fields {
36            if !self.last.contains(&key.as_str()) {
37                map.serialize_entry(key, value)?;
38            }
39        }
40        for key in &self.last {
41            if let Some(value) = self.fields.get(*key) {
42                map.serialize_entry(key, value)?;
43            }
44        }
45        map.end()
46    }
47}
48
49impl FinalBody {
50    /// Whether the body has no key.
51    pub fn is_empty(&self) -> bool {
52        self.fields.is_empty()
53    }
54
55    /// The top-level value of `key`.
56    pub fn get(&self, key: &str) -> Option<&Value> {
57        self.fields.get(key)
58    }
59
60    /// The value at the JSON pointer `pointer`.
61    pub fn pointer(&self, pointer: &str) -> Option<&Value> {
62        let path = pointer.strip_prefix('/')?;
63        let (head, rest) = path.split_once('/').unwrap_or((path, ""));
64        let value = self
65            .fields
66            .get(&head.replace("~1", "/").replace("~0", "~"))?;
67        if rest.is_empty() {
68            Some(value)
69        } else {
70            value.pointer(&format!("/{rest}"))
71        }
72    }
73
74    /// The request bytes of an HTTP completion wire: the body as compact
75    /// JSON.
76    pub fn into_body(self) -> Body {
77        let mut bytes = Vec::new();
78        // JSON values and string keys serialize infallibly into a byte vector.
79        let _ = serde_json::to_writer(&mut bytes, &self);
80        Body::Bytes(bytes)
81    }
82
83    /// The body read as `T`: an SDK-backed wire's request type, or a local
84    /// runtime's generation settings.
85    ///
86    /// # Errors
87    ///
88    /// When the body is not a `T`.
89    pub fn deserialize<T: DeserializeOwned>(&self) -> Result<T, serde_json::Error> {
90        // Read in place: a `Value` of the body would copy the whole history.
91        // A body holding an integer beyond u64 or i64 is read as
92        // `json_utils::from_value` reads it.
93        if self
94            .fields
95            .values()
96            .any(crate::json_utils::holds_wide_integer)
97        {
98            return crate::json_utils::from_value(&Value::Object(self.fields.clone()));
99        }
100        let fields = self.fields.iter().map(|(key, value)| (key.as_str(), value));
101        T::deserialize(serde::de::value::MapDeserializer::new(fields))
102    }
103}
104
105/// Where the raw layer, `additional_params`, merges. Data, not code.
106#[derive(Clone, Copy, Debug, PartialEq, Eq)]
107#[non_exhaustive]
108pub enum RawAt {
109    /// At the top level of the body.
110    Top,
111    /// Under the object at this JSON pointer (Bedrock's
112    /// `/additionalModelRequestFields`).
113    Under(&'static str),
114    /// The keys in `top`, and the key `rest` names, at the top level; every
115    /// other key under `rest` (Ollama's native `options`).
116    Split {
117        /// The keys the wire reads at the top level.
118        top: &'static [&'static str],
119        /// The object every other key goes under.
120        rest: &'static str,
121    },
122    /// Not merged: the provider rejects pass-through parameters, so a
123    /// non-empty raw layer is skipped with this warning.
124    ///
125    /// For rig's own crates; not covered by semver.
126    #[doc(hidden)]
127    Ignored(&'static str),
128}
129
130/// The writes [`request_params`] makes after the merge, each one a write a
131/// wire made after merging `additional_params` before. Each reads the merged
132/// body, raw keys included. A third-party wire uses the stream ones; the
133/// provider-specific ones are rig's own and hidden.
134#[derive(Clone, Debug, PartialEq)]
135#[non_exhaustive]
136pub enum Rewrite {
137    /// Chat Completions: `max_tokens` as `max_completion_tokens` for an
138    /// OpenAI reasoning model.
139    ///
140    /// For rig's own crates; not covered by semver.
141    #[doc(hidden)]
142    OutputCapRename,
143    /// Anthropic: ask to drop thinking bound to another context, when the
144    /// body's thinking is adaptive or unset.
145    ///
146    /// For rig's own crates; not covered by semver.
147    #[doc(hidden)]
148    DropUnboundThinking,
149    /// Anthropic on a platform whose URL names the model: `model` removed
150    /// and `anthropic_version` set to this value.
151    ///
152    /// For rig's own crates; not covered by semver.
153    #[doc(hidden)]
154    AnthropicVersionInBody(String),
155    /// Anthropic streams: a default `tool_choice` beside tools, none without
156    /// them.
157    ///
158    /// For rig's own crates; not covered by semver.
159    #[doc(hidden)]
160    ToolChoiceNeedsTools,
161    /// `stream` set to this value.
162    Stream(bool),
163    /// `stream` removed.
164    NoStream,
165    /// OpenAI Responses over a WebSocket session: `background` removed,
166    /// which the session ignores.
167    ///
168    /// For rig's own crates; not covered by semver.
169    #[doc(hidden)]
170    NoBackground,
171    /// Chat Completions streams: `stream_options.include_usage: true`
172    /// unless the body states it.
173    StreamUsage,
174    /// OpenAI Responses: ask for the reasoning ciphertext when the body
175    /// reasons or stores nothing, or always when `true`.
176    ///
177    /// For rig's own crates; not covered by semver.
178    #[doc(hidden)]
179    ReasoningCiphertext(bool),
180    /// OpenAI Responses on ChatGPT: `store: false`.
181    ///
182    /// For rig's own crates; not covered by semver.
183    #[doc(hidden)]
184    CodexStore,
185    /// The Chat Completions dialect's own rewrite.
186    ///
187    /// For rig's own crates; not covered by semver.
188    #[doc(hidden)]
189    ChatDialect(BodyRewrite),
190    /// The Hugging Face router: `model` suffixed with the sub-provider it
191    /// selects.
192    ///
193    /// For rig's own crates; not covered by semver.
194    #[doc(hidden)]
195    RouterProvider(crate::providers::openai::wire::SubRoute),
196    /// Gemini `cachedContent`: each raw `cachedContent`/`cached_content`
197    /// handle, then the wire's own, checked against the body. The
198    /// GenerateContent wires that name it also read a raw
199    /// `generationConfig: null` as absent, as they always have.
200    ///
201    /// For rig's own crates; not covered by semver.
202    #[doc(hidden)]
203    GeminiCachedContent(Option<String>),
204    /// The top-level `key` moved to the end of the body, so a request that
205    /// only appended to it starts with the previous request's bytes.
206    ///
207    /// For rig's own crates; not covered by semver.
208    #[doc(hidden)]
209    MoveLast(&'static str),
210}
211
212/// The base builder's view of the options and the layers above it. It
213/// cannot write them.
214pub struct BaseInput<'a> {
215    target: &'a dyn ReplayTarget,
216    request: &'a CompletionRequest,
217    cache: Option<CacheRetention>,
218    upper: &'a Map<String, Value>,
219    provider: &'a Map<String, Value>,
220    claimed: Vec<&'static str>,
221    raw_tools: Option<Value>,
222}
223
224impl BaseInput<'_> {
225    /// The cache retention the mapping honoured through `Send` or `Place`,
226    /// for markers inside the body's arrays.
227    pub fn cache(&self) -> Option<CacheRetention> {
228        self.cache
229    }
230
231    /// Report a cache marker the base cannot place, under the name `cache`:
232    /// an error under [`OnUnsupported::Error`], a warning under
233    /// [`OnUnsupported::Ignore`].
234    ///
235    /// # Errors
236    ///
237    /// Under [`OnUnsupported::Error`].
238    pub fn refuse_cache(&mut self, reason: impl Into<String>) -> Result<(), EncodeError> {
239        refuse(self.target, self.request, "cache", reason.into())
240    }
241
242    /// The value top-level `key` gets from the layers above the base: the
243    /// mapped options, then the provider options, then `additional_params`,
244    /// merged as the body merges them. Read only, so it cannot rank
245    /// anything.
246    pub fn param(&self, key: &str) -> Option<&Value> {
247        self.upper.get(key)
248    }
249
250    /// The provider options' top-level `key`, which the base places itself.
251    /// The merge then leaves it out of the provider layer, so it does not
252    /// replace that placement; `additional_params` still merges over it.
253    pub fn claim(&mut self, key: &'static str) -> Option<Value> {
254        self.claimed.push(key);
255        self.provider.get(key).cloned()
256    }
257
258    /// `additional_params.tools`, taken out of the raw layer for the base to
259    /// append after the request's own tools, so the merge never replaces
260    /// them. Empty when it is unset.
261    ///
262    /// # Errors
263    ///
264    /// When it is not an array.
265    pub fn raw_tools(&mut self) -> Result<Vec<Value>, EncodeError> {
266        match self.raw_tools.take() {
267            None | Some(Value::Null) => Ok(Vec::new()),
268            Some(Value::Array(tools)) => Ok(tools),
269            Some(other) => Err(EncodeError::request(format!(
270                "`additional_params.tools` must be an array, got {other}"
271            ))),
272        }
273    }
274}
275
276/// The answers of a wire for a request's options, after the policy.
277#[derive(Default)]
278struct Settled {
279    /// Each `Send` object, in option order.
280    sends: Vec<Value>,
281    /// The retention honoured by `Send` or `Place`.
282    cache: Option<CacheRetention>,
283    /// The options skipped under `Ignore`.
284    ignored: Vec<OptionName>,
285}
286
287/// The model the request resolves to on `target`.
288fn model_of<'a>(target: &'a dyn ReplayTarget, request: &'a CompletionRequest) -> &'a str {
289    request
290        .model
291        .as_deref()
292        .filter(|model| !model.is_empty())
293        .unwrap_or_else(|| target.model())
294}
295
296/// Report `option` as unsupported for `reason` under the request's policy.
297fn refuse(
298    target: &dyn ReplayTarget,
299    request: &CompletionRequest,
300    option: impl Into<Cow<'static, str>>,
301    reason: String,
302) -> Result<(), EncodeError> {
303    let option = option.into();
304    let provider = target.provider();
305    let model = model_of(target, request);
306    if collected(|| UnsupportedOption::new(option.clone(), provider, model, reason.clone())) {
307        return Ok(());
308    }
309    match request.options.unsupported_policy() {
310        OnUnsupported::Error => Err(EncodeError::unsupported(UnsupportedOption::new(
311            option, provider, model, reason,
312        ))),
313        OnUnsupported::Ignore => {
314            tracing::warn!(
315                option = option.as_ref(),
316                provider,
317                model,
318                reason = reason.as_str(),
319                "option skipped: the provider cannot honour it"
320            );
321            Ok(())
322        }
323    }
324}
325
326/// `target`'s answer for every option of `request`, with each refusal
327/// reported under the request's policy.
328fn settle(target: &dyn ReplayTarget, request: &CompletionRequest) -> Result<Settled, EncodeError> {
329    let fields = request.options.fields();
330    let map = target.map_options(request, fields);
331    let provider = target.provider();
332    let mut settled = Settled::default();
333    for (option, mapping) in map.into_slots() {
334        let set = fields.is_set(option);
335        let name = option.as_str();
336        let fail = |what: String| Err(EncodeError::request(format!("{provider} {what}")));
337        match (mapping, set) {
338            (Mapping::Nothing, false) => {}
339            (Mapping::Nothing, true) => {
340                return fail(format!(
341                    "answered `Mapping::Nothing` for the option `{name}`, which the request sets"
342                ));
343            }
344            (_, false) => {
345                return fail(format!(
346                    "answered the option `{name}`, which the request does not set; \
347                     an unset option answers `Mapping::Nothing` (see `Mapping::of`)"
348                ));
349            }
350            (Mapping::Send(value), true) => {
351                if !value.is_object() {
352                    return fail(format!(
353                        "sent a value that is not a JSON object for the option `{name}`"
354                    ));
355                }
356                settled.sends.push(value);
357                if option == OptionName::Cache {
358                    settled.cache = request.options.cache;
359                }
360            }
361            (Mapping::Omit(reason), true) => {
362                tracing::debug!(
363                    option = name,
364                    provider,
365                    reason,
366                    "option honoured by sending nothing"
367                );
368            }
369            (Mapping::Place, true) if option == OptionName::Cache => {
370                settled.cache = request.options.cache
371            }
372            (Mapping::Place, true) => {
373                return fail(format!(
374                    "answered `Mapping::Place` for the option `{name}`; only `cache` places markers"
375                ));
376            }
377            (Mapping::Unsupported(reason), true) => {
378                refuse(target, request, name, reason)?;
379                settled.ignored.push(option);
380            }
381        }
382    }
383    Ok(settled)
384}
385
386/// Report each option `target` cannot honour for `request` under its
387/// policy: an error under [`OnUnsupported::Error`]; under
388/// [`OnUnsupported::Ignore`] a warning, and the option is cleared on
389/// `request`, so it is reported once. A set option the wire answers
390/// [`Mapping::Nothing`] is an error. `Completion::prepare` calls it on the
391/// routed target before every completion encode.
392///
393/// # Errors
394///
395/// When an option is refused under [`OnUnsupported::Error`], the wire
396/// answers an option wrongly, or the request carries provider options that
397/// did not serialize.
398pub fn check(
399    target: &dyn ReplayTarget,
400    request: &mut CompletionRequest,
401) -> Result<(), EncodeError> {
402    unserialized(request)?;
403    let settled = settle(target, request)?;
404    for option in settled.ignored {
405        option.clear(request);
406    }
407    model_rules(target, request)?;
408    let layer = provider_layer(target, request);
409    for refusal in &layer.refused {
410        refuse(
411            target,
412            request,
413            refusal.name(target),
414            refusal.reason.clone(),
415        )?;
416    }
417    let api = target.api();
418    for refusal in layer.refused {
419        request.provider_options.remove_field(
420            target.provider(),
421            &[SHARED, api.as_str()],
422            refusal.field,
423        );
424    }
425    Ok(())
426}
427
428/// Report each option of `request` the catalog entry of its model on
429/// `target` refuses by [`ModelSpec::refusals`](crate::catalog::ModelSpec::refusals),
430/// under the request's policy, and clear it under
431/// [`OnUnsupported::Ignore`]. The wire's own answers come first, so an
432/// option it already refused is not reported twice.
433fn model_rules(
434    target: &dyn ReplayTarget,
435    request: &mut CompletionRequest,
436) -> Result<(), EncodeError> {
437    let facts = target
438        .facts()
439        .unwrap_or_else(|| crate::catalog::ModelFacts::builtin());
440    let Some(spec) = facts.for_model(target.provider(), model_of(target, request)) else {
441        return Ok(());
442    };
443    for CatalogRefusal { option, reason } in spec.request_rules(request) {
444        refuse(target, request, option.as_str(), reason)?;
445        option.clear(request);
446    }
447    Ok(())
448}
449
450thread_local! {
451    /// The refusals collected by [`collect_refusals`] on this thread, while
452    /// it runs.
453    static COLLECTED: std::cell::RefCell<Option<Vec<UnsupportedOption>>> =
454        const { std::cell::RefCell::new(None) };
455}
456
457/// Run `encode` with every refusal collected instead of reported: each
458/// refused option is skipped as under [`OnUnsupported::Ignore`], without a
459/// warning, and the refusals come back in the order they were made. Encoding
460/// is synchronous and pure, so a thread-local scope sees every refusal it
461/// makes. `DynModel::check` dry-runs a request under it.
462pub(crate) fn collect_refusals<T>(encode: impl FnOnce() -> T) -> (T, Vec<UnsupportedOption>) {
463    /// Restores the enclosing scope's collection, also on unwind.
464    struct Scope(Option<Vec<UnsupportedOption>>);
465    impl Drop for Scope {
466        fn drop(&mut self) {
467            let outer = self.0.take();
468            COLLECTED.with(|collected| collected.replace(outer));
469        }
470    }
471    let outer = COLLECTED.with(|collected| collected.replace(Some(Vec::new())));
472    let scope = Scope(outer);
473    let value = encode();
474    let refusals = COLLECTED
475        .with(|collected| collected.borrow_mut().take())
476        .unwrap_or_default();
477    drop(scope);
478    (value, refusals)
479}
480
481/// Whether a [`collect_refusals`] scope is open, after adding the refusal
482/// `make` builds to it.
483fn collected(make: impl FnOnce() -> UnsupportedOption) -> bool {
484    COLLECTED.with(|collected| match collected.borrow_mut().as_mut() {
485        Some(refusals) => {
486            refusals.push(make());
487            true
488        }
489        None => false,
490    })
491}
492
493/// An option a model's catalog entry refuses, and why.
494pub(crate) struct CatalogRefusal {
495    pub(crate) option: OptionName,
496    pub(crate) reason: String,
497}
498
499/// A part of a final body that a model's catalog entry says the API
500/// rejects: a top-level body key, or `tools` for the request's tools, and
501/// why. Found on the final body, because `additional_params` can set the
502/// same keys.
503pub(crate) struct BodyRefusal {
504    pub(crate) field: &'static str,
505    pub(crate) reason: String,
506}
507
508/// `body` after the refusals `target`'s catalog entry for the model makes
509/// of it. A request that sets no [`GenerationOptions`] is sent as built,
510/// and the provider decides. Otherwise each refusal goes through the
511/// request's policy under the name of its body key: an error under
512/// [`OnUnsupported::Error`]; under [`OnUnsupported::Ignore`] a warning, and
513/// a field rig wrote from a typed source (a request field such as
514/// `temperature`, a generation option, a provider option) is left out of
515/// the body. A key whose value `additional_params` sets, and the request's
516/// `tools`, are sent as written.
517///
518/// Inside [`collect_refusals`], every refusal is collected and handled as
519/// under [`OnUnsupported::Ignore`], so a dry run lists them all.
520///
521/// # Errors
522///
523/// Under [`OnUnsupported::Error`], for the first refusal.
524///
525/// [`GenerationOptions`]: super::GenerationOptions
526pub(crate) fn catalog_refusals(
527    target: &dyn ReplayTarget,
528    request: &CompletionRequest,
529    body: FinalBody,
530    refusals: Vec<BodyRefusal>,
531) -> Result<FinalBody, EncodeError> {
532    let provider = target.provider();
533    let model = model_of(target, request);
534    if request.options.is_default() {
535        for refusal in &refusals {
536            tracing::debug!(
537                option = refusal.field,
538                provider,
539                model,
540                reason = refusal.reason.as_str(),
541                "catalog refusal not applied: the request sets no generation options"
542            );
543        }
544        return Ok(body);
545    }
546    let mut body = body;
547    for BodyRefusal { field, reason } in refusals {
548        let collecting =
549            collected(|| UnsupportedOption::new(field, provider, model, reason.clone()));
550        if !collecting && request.options.unsupported_policy() == OnUnsupported::Error {
551            return Err(EncodeError::unsupported(UnsupportedOption::new(
552                field, provider, model, reason,
553            )));
554        }
555        let raw = request
556            .additional_params
557            .as_ref()
558            .and_then(|params| params.get(field));
559        let typed = field != "tools" && raw.is_none_or(|raw| body.get(field) != Some(raw));
560        if typed {
561            remove_preserving_order(&mut body.fields, field);
562        }
563        if collecting {
564            continue;
565        }
566        tracing::warn!(
567            option = field,
568            provider,
569            model,
570            reason = reason.as_str(),
571            "{}",
572            match typed {
573                true => "option skipped: the model's catalog entry refuses it",
574                false => "catalog refusal ignored: sent as written",
575            }
576        );
577    }
578    Ok(body)
579}
580
581/// A provider field the target cannot send: its body key, the section it
582/// came from and why.
583struct Refused {
584    field: &'static str,
585    section: String,
586    reason: String,
587}
588
589impl Refused {
590    /// The field's name, `"<provider>.<section>.<field>"`.
591    fn name(&self, target: &dyn ReplayTarget) -> String {
592        format!("{}.{}.{}", target.provider(), self.section, self.field)
593    }
594}
595
596/// The provider options `target` reads from `request`, with the fields it
597/// cannot send taken out.
598struct ProviderLayer {
599    fields: Map<String, Value>,
600    refused: Vec<Refused>,
601}
602
603/// The entry of `request`'s provider options named by `target`'s provider:
604/// its [`SHARED`] section, then the section named by `target`'s API, merged.
605/// A section for another route is skipped. Each set field the entry's
606/// typed options refuse for `target` is taken out and listed.
607fn provider_layer(target: &dyn ReplayTarget, request: &CompletionRequest) -> ProviderLayer {
608    let provider = target.provider();
609    let api = target.api();
610    let mut layer = ProviderLayer {
611        fields: Map::new(),
612        refused: Vec::new(),
613    };
614    let Some(sections) = request.provider_options.sections(provider) else {
615        return layer;
616    };
617    let mut route = None;
618    for (name, section) in sections {
619        let Value::Object(section) = section else {
620            continue;
621        };
622        if name == SHARED {
623            deep_merge(&mut layer.fields, section.clone());
624        } else if name == api.as_str() {
625            route = Some(section);
626        } else {
627            tracing::debug!(
628                provider,
629                section = name.as_str(),
630                api = api.as_str(),
631                "provider options section skipped: the request takes another route"
632            );
633        }
634    }
635    if let Some(route) = route {
636        deep_merge(&mut layer.fields, route.clone());
637    }
638    for (field, reason) in request.provider_options.refusals(provider, target, request) {
639        layer.refuse(target, request, field, reason);
640    }
641    layer
642}
643
644impl ProviderLayer {
645    /// Take `field` out and list it as refused for `reason`, when the layer
646    /// sets it. It is named by the section it came from: the route's when
647    /// that section sets it, [`SHARED`] otherwise.
648    fn refuse(
649        &mut self,
650        target: &dyn ReplayTarget,
651        request: &CompletionRequest,
652        field: &'static str,
653        reason: String,
654    ) {
655        if remove_preserving_order(&mut self.fields, field).is_none() {
656            return;
657        }
658        let api = target.api();
659        let in_route = request
660            .provider_options
661            .sections(target.provider())
662            .and_then(|sections| sections.get(api.as_str()))
663            .and_then(Value::as_object)
664            .is_some_and(|route| route.contains_key(field));
665        let section = if in_route { api.as_str() } else { SHARED };
666        self.refused.push(Refused {
667            field,
668            section: section.to_owned(),
669            reason,
670        });
671    }
672}
673
674/// The error of provider options [`ProviderOptions::set`] stored without
675/// sections, as an encode error.
676///
677/// [`ProviderOptions::set`]: crate::completion::ProviderOptions::set
678fn unserialized(request: &CompletionRequest) -> Result<(), EncodeError> {
679    match request.provider_options.failure() {
680        Some(error) => Err(EncodeError::request(error.clone())),
681        None => Ok(()),
682    }
683}
684
685/// `additional_params` as an object, or empty.
686fn raw_layer(request: &CompletionRequest) -> Result<Map<String, Value>, EncodeError> {
687    match &request.additional_params {
688        None | Some(Value::Null) => Ok(Map::new()),
689        Some(Value::Object(params)) => Ok(params.clone()),
690        Some(_) => Err(EncodeError::request(
691            "`additional_params` must be a JSON object",
692        )),
693    }
694}
695
696/// `raw` placed in the body as `raw_at` says.
697fn placed(raw: Map<String, Value>, raw_at: RawAt) -> Map<String, Value> {
698    match raw_at {
699        RawAt::Top => raw,
700        RawAt::Under(_) if raw.is_empty() => Map::new(),
701        RawAt::Under(pointer) => {
702            let mut value = Value::Object(raw);
703            for key in pointer.rsplit('/').filter(|key| !key.is_empty()) {
704                value = Value::Object(Map::from_iter([(key.to_owned(), value)]));
705            }
706            match value {
707                Value::Object(map) => map,
708                _ => Map::new(),
709            }
710        }
711        RawAt::Split { top, rest } => {
712            let mut body = Map::new();
713            let mut under = Map::new();
714            for (key, value) in raw {
715                if key == rest || top.contains(&key.as_str()) {
716                    deep_merge(&mut body, Map::from_iter([(key, value)]));
717                } else {
718                    under.insert(key, value);
719                }
720            }
721            if !under.is_empty() {
722                deep_merge(
723                    &mut body,
724                    Map::from_iter([(rest.to_owned(), Value::Object(under))]),
725                );
726            }
727            body
728        }
729        RawAt::Ignored(warning) => {
730            if !raw.is_empty() {
731                tracing::warn!("{warning}");
732            }
733            Map::new()
734        }
735    }
736}
737
738/// The layers above the base, merged: the mapped options, then the
739/// provider options, then the raw layer as placed.
740fn upper_layers(
741    sends: &[Value],
742    provider: &Map<String, Value>,
743    raw: &Map<String, Value>,
744) -> Map<String, Value> {
745    let mut upper = Map::new();
746    for send in sends {
747        if let Value::Object(send) = send {
748            deep_merge(&mut upper, send.clone());
749        }
750    }
751    deep_merge(&mut upper, provider.clone());
752    deep_merge(&mut upper, raw.clone());
753    upper
754}
755
756/// The value top-level `key` gets from the mapped options, the provider
757/// options and `additional_params`, merged as [`request_params`] merges
758/// them, with no base. For a reader that runs before encoding and must
759/// agree with the body. Read only, so it cannot rank anything, and it
760/// reports nothing: a refused option adds nothing here. The one sanctioned
761/// reader of these layers on the completion path outside the merge. A
762/// wire's `map_options` must not call it, since it calls `map_options`.
763pub fn param(target: &dyn ReplayTarget, request: &CompletionRequest, key: &str) -> Option<Value> {
764    let map = target.map_options(request, request.options.fields());
765    let mut upper = Map::new();
766    for (_, mapping) in map.into_slots() {
767        if let Mapping::Send(Value::Object(send)) = mapping {
768            deep_merge(&mut upper, send);
769        }
770    }
771    deep_merge(&mut upper, provider_layer(target, request).fields);
772    if let Some(Value::Object(raw)) = &request.additional_params {
773        deep_merge(&mut upper, raw.clone());
774    }
775    remove_preserving_order(&mut upper, key)
776}
777
778/// The body `target` sends for `request`. Reports each refused option
779/// (after `Completion::prepare` none is left), then calls `base` for the
780/// wire's own encoding of the request, merges the mapped options, then the
781/// provider options at the top level, then `additional_params` as `raw_at`
782/// places them, and applies `rewrites` in order. The only reader of the
783/// request's options, provider options and `additional_params` on the
784/// completion path.
785///
786/// # Errors
787///
788/// When an option or a provider field is refused under
789/// [`OnUnsupported::Error`], the request carries provider options that did
790/// not serialize,
791/// `additional_params` is not an object or holds a malformed `tools` or
792/// cached-content handle, `base` fails, or a rewrite refuses the body.
793pub fn request_params(
794    target: &dyn ReplayTarget,
795    request: &CompletionRequest,
796    base: impl FnOnce(&mut BaseInput<'_>) -> Result<Map<String, Value>, EncodeError>,
797    raw_at: RawAt,
798    rewrites: &[Rewrite],
799) -> Result<FinalBody, EncodeError> {
800    unserialized(request)?;
801    let settled = settle(target, request)?;
802    let mut provider = provider_layer(target, request);
803    // The rewrite drops a raw `background` as it always has; a typed one is
804    // refused rather than dropped unseen.
805    if rewrites.contains(&Rewrite::NoBackground) {
806        provider.refuse(
807            target,
808            request,
809            "background",
810            "a WebSocket session takes no `background`".to_owned(),
811        );
812    }
813    for refusal in provider.refused {
814        refuse(target, request, refusal.name(target), refusal.reason)?;
815    }
816    let mut provider = provider.fields;
817    let mut raw = raw_layer(request)?;
818    let raw_tools = match raw_at {
819        RawAt::Top | RawAt::Split { .. } => remove_preserving_order(&mut raw, "tools"),
820        RawAt::Under(_) | RawAt::Ignored(_) => None,
821    };
822    let mut handles = Vec::new();
823    if rewrites
824        .iter()
825        .any(|rewrite| matches!(rewrite, Rewrite::GeminiCachedContent(_)))
826    {
827        for spelling in ["cachedContent", "cached_content"] {
828            match remove_preserving_order(&mut raw, spelling) {
829                None => {}
830                Some(Value::String(name)) => handles.push(name),
831                Some(other) => {
832                    return Err(EncodeError::request(format!(
833                        "Gemini `additional_params.{spelling}` should be a string, got {other}"
834                    )));
835                }
836            }
837        }
838        // GenerateContent has always read a raw `generationConfig: null` as
839        // absent, so the typed and mapped fields under it are still sent.
840        if raw.get("generationConfig").is_some_and(Value::is_null) {
841            remove_preserving_order(&mut raw, "generationConfig");
842        }
843    }
844    let raw = placed(raw, raw_at);
845    let upper = upper_layers(&settled.sends, &provider, &raw);
846    let mut input = BaseInput {
847        target,
848        request,
849        cache: settled.cache,
850        upper: &upper,
851        provider: &provider,
852        claimed: Vec::new(),
853        raw_tools,
854    };
855    let mut body = base(&mut input)?;
856    for key in input.claimed {
857        remove_preserving_order(&mut provider, key);
858    }
859    for send in settled.sends {
860        if let Value::Object(send) = send {
861            deep_merge(&mut body, send);
862        }
863    }
864    deep_merge(&mut body, provider);
865    deep_merge(&mut body, raw);
866    let mut body = FinalBody {
867        fields: body,
868        last: Vec::new(),
869    };
870    for rewrite in rewrites {
871        apply(target, rewrite, &mut body, &handles)?;
872    }
873    Ok(body)
874}
875
876/// Apply one post-merge write to `body`.
877fn apply(
878    target: &dyn ReplayTarget,
879    rewrite: &Rewrite,
880    body: &mut FinalBody,
881    handles: &[String],
882) -> Result<(), EncodeError> {
883    let FinalBody { fields: body, last } = body;
884    match rewrite {
885        Rewrite::OutputCapRename => {
886            // Read on the full id: a `vendor/model` id (a LiteLLM-style
887            // proxy behind `OPENAI_BASE_URL`) keeps `max_tokens`.
888            let reasoning = body
889                .get("model")
890                .and_then(Value::as_str)
891                .is_some_and(|model| {
892                    let facts = target
893                        .facts()
894                        .unwrap_or_else(|| crate::catalog::ModelFacts::builtin());
895                    !model.contains('/')
896                        && crate::providers::openai::options::reasons(facts, model) == Some(true)
897                });
898            if reasoning && let Some(max_tokens) = remove_preserving_order(body, "max_tokens") {
899                body.entry("max_completion_tokens").or_insert(max_tokens);
900            }
901        }
902        Rewrite::DropUnboundThinking => {
903            let adaptive = body.get("thinking").is_none_or(|thinking| {
904                thinking.get("type").and_then(Value::as_str) == Some("adaptive")
905            });
906            if adaptive {
907                crate::providers::anthropic::completion::drop_unbound_thinking(body);
908            }
909        }
910        Rewrite::AnthropicVersionInBody(version) => {
911            remove_preserving_order(body, "model");
912            body.insert("anthropic_version".to_owned(), version.as_str().into());
913        }
914        Rewrite::ToolChoiceNeedsTools => {
915            let has_tools = body
916                .get("tools")
917                .and_then(Value::as_array)
918                .is_some_and(|tools| !tools.is_empty());
919            if has_tools {
920                body.entry("tool_choice")
921                    .or_insert_with(|| serde_json::json!({ "type": "auto" }));
922            } else {
923                remove_preserving_order(body, "tool_choice");
924            }
925        }
926        Rewrite::Stream(stream) => {
927            body.insert("stream".to_owned(), Value::Bool(*stream));
928        }
929        Rewrite::NoStream => {
930            remove_preserving_order(body, "stream");
931        }
932        Rewrite::NoBackground => {
933            remove_preserving_order(body, "background");
934        }
935        Rewrite::StreamUsage => {
936            if let Some(options) = body
937                .entry("stream_options")
938                .or_insert_with(|| Value::Object(Map::new()))
939                .as_object_mut()
940            {
941                options.entry("include_usage").or_insert(Value::Bool(true));
942            }
943        }
944        Rewrite::ReasoningCiphertext(always) => {
945            let wanted = *always
946                || body.get("reasoning").is_some()
947                || body.get("store") == Some(&Value::Bool(false));
948            if wanted {
949                crate::providers::openai::responses_api::include_ciphertext(body);
950            }
951        }
952        Rewrite::CodexStore => {
953            body.insert("store".to_owned(), Value::Bool(false));
954        }
955        Rewrite::ChatDialect(kind) => {
956            crate::providers::openai::wire::chat::rewrite_body(*kind, body)?;
957        }
958        Rewrite::RouterProvider(route) => {
959            crate::providers::openai::wire::chat::select_router_provider(route, body)?;
960        }
961        Rewrite::GeminiCachedContent(handle) => {
962            for name in handles.iter().chain(handle) {
963                crate::providers::gemini::completion::with_cached_content(body, name)?;
964            }
965        }
966        Rewrite::MoveLast(key) => {
967            if body.contains_key(*key) {
968                last.retain(|previous| previous != key);
969                last.push(*key);
970            }
971        }
972    }
973    Ok(())
974}