use serde_json::{json, Map};
use crate::canonical::{CanonicalError, CanonicalRequest};
use crate::protocol::json::finish_body;
use crate::protocol::{ProviderCtx, WireRequest};
const COUNT_PATH: &str = "/v1/messages/count_tokens";
pub(crate) fn count(
req: &CanonicalRequest,
ctx: &ProviderCtx,
) -> Result<WireRequest, CanonicalError> {
let mut body = Map::new();
body.insert("model".into(), json!(ctx.model));
if let Some(effort) = req.reasoning {
body.insert(
"thinking".into(),
json!({"type": "enabled", "budget_tokens": effort.budget()}),
);
}
if let Some(system) = super::system_value(req)? {
body.insert("system".into(), system);
}
body.insert("messages".into(), super::messages_value(&req.messages)?);
if !req.tools.is_empty() {
body.insert("tools".into(), super::tools_value(&req.tools));
}
if let Some(tc) = super::tool_choice_value(
&req.tool_choice,
req.tools.is_empty(),
req.parallel_tool_calls,
) {
body.insert("tool_choice".into(), tc);
}
super::cache::apply(&mut body);
for (k, v) in &req.extra {
body.entry(k.clone()).or_insert_with(|| v.clone());
}
Ok(finish_body(body, format!("{}{COUNT_PATH}", ctx.base_url)))
}