use serde::{Serialize, Serializer};
use serde_json::{Map, Value};
use crate::WireStyle;
const ANTHROPIC_REQUEST_FIELDS: &[&str] = &[
"model",
"max_tokens",
"messages",
"system",
"temperature",
"tools",
"tool_choice",
"stream",
"thinking",
"stop_sequences",
"output_config",
"cache_control",
];
const OPENAI_COMPATIBLE_REQUEST_FIELDS: &[&str] = &[
"model",
"messages",
"reasoning_effort",
"max_tokens",
"stream",
"stream_options",
"temperature",
"stop",
"tools",
"tool_choice",
"thinking",
"enable_thinking",
"enable_search",
"search_options",
];
const OPENAI_RESPONSE_REQUEST_FIELDS: &[&str] = &[
"model",
"input",
"tools",
"tool_choice",
"parallel_tool_calls",
"max_output_tokens",
"temperature",
"reasoning",
"stream",
"include",
"store",
];
const GEMINI_REQUEST_FIELDS: &[&str] =
&["contents", "systemInstruction", "generationConfig", "tools", "toolConfig"];
impl WireStyle {
pub fn conflicts(&self, extra_body: &Map<String, Value>) -> Vec<String> {
let reserved = match self {
Self::AnthropicMessage => ANTHROPIC_REQUEST_FIELDS,
Self::OpenAiCompatible => OPENAI_COMPATIBLE_REQUEST_FIELDS,
Self::OpenAiResponse => OPENAI_RESPONSE_REQUEST_FIELDS,
Self::Gemini => GEMINI_REQUEST_FIELDS,
};
let mut conflicts: Vec<String> =
extra_body.keys().filter(|key| reserved.contains(&key.as_str())).cloned().collect();
conflicts.sort();
conflicts
}
}
#[derive(Debug)]
pub(crate) enum RequestBody<'a, Req> {
Plain(&'a Req),
Extended { request: &'a Req, extra_body: &'a Map<String, Value> },
}
impl<Req> Serialize for RequestBody<'_, Req>
where
Req: Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::Plain(request) => request.serialize(serializer),
Self::Extended { request, extra_body } => {
#[derive(Serialize)]
struct Merged<'a, Req> {
#[serde(flatten)]
request: &'a Req,
#[serde(flatten)]
extra_body: &'a Map<String, Value>,
}
Merged { request, extra_body }.serialize(serializer)
}
}
}
}
pub(crate) fn decorate<'a, Req>(
request: &'a Req,
extra_body: &'a Map<String, Value>,
) -> RequestBody<'a, Req> {
if extra_body.is_empty() {
return RequestBody::Plain(request);
}
RequestBody::Extended { request, extra_body }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn collision_rules_follow_wire_style() {
let extra_body = [
("messages".to_string(), Value::Array(Vec::new())),
("generationConfig".to_string(), Value::Object(Map::new())),
("service_tier".to_string(), Value::String("priority".to_string())),
("tool_choice".to_string(), Value::String("auto".to_string())),
]
.into_iter()
.collect();
assert_eq!(WireStyle::AnthropicMessage.conflicts(&extra_body), ["messages", "tool_choice"]);
assert_eq!(WireStyle::OpenAiCompatible.conflicts(&extra_body), ["messages", "tool_choice"]);
assert_eq!(WireStyle::Gemini.conflicts(&extra_body), ["generationConfig"]);
}
}