use anyhow::Result;
use once_cell::sync::Lazy;
use regex::Regex;
use serde_json::Value;
use crate::llmtrim::gate::{GateKind, PlanEntry, Transform};
use crate::llmtrim::ir::Request;
use crate::llmtrim::provider::{Provider, Role};
use crate::llmtrim::stages::tools::{detect_lang, is_first_turn};
const PROSE_SAMPLE_MAX_BYTES: usize = 4096;
fn user_prose(req: &Request, provider: &dyn Provider) -> String {
let user_texts: Vec<&str> = provider
.content_text_pointers(req)
.into_iter()
.filter(|ptr| provider.role_at(req, ptr) == Some(Role::User))
.filter_map(|ptr| req.get_str(&ptr))
.collect();
let mut prose = String::new();
for text in user_texts.iter().rev() {
let stripped = strip_code(text);
let mut take = PROSE_SAMPLE_MAX_BYTES
.saturating_sub(prose.len())
.min(stripped.len());
while take > 0 && !stripped.is_char_boundary(take) {
take -= 1;
}
prose.push_str(&stripped[..take]);
prose.push(' ');
if prose.len() >= PROSE_SAMPLE_MAX_BYTES {
break;
}
}
prose
}
static FENCED_CODE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?s)```.*?```|~~~.*?~~~").unwrap());
static INLINE_CODE_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"`[^`\n]*`").unwrap());
fn strip_code(text: &str) -> String {
let no_fenced = FENCED_CODE_RE.replace_all(text, " ");
let no_inline = INLINE_CODE_RE.replace_all(&no_fenced, " ");
no_inline
.lines()
.filter(|line| !looks_like_code_line(line))
.collect::<Vec<_>>()
.join("\n")
}
fn looks_like_code_line(line: &str) -> bool {
if line.starts_with(" ") || line.starts_with('\t') {
return true;
}
let trimmed = line.trim();
if trimmed.is_empty() {
return false;
}
let symbol_count = trimmed
.chars()
.filter(|c| "{}();=<>|&/\\[]".contains(*c))
.count();
let letter_count = trimmed.chars().filter(|c| c.is_alphabetic()).count();
symbol_count > 0 && symbol_count >= letter_count
}
pub const TERSE_INSTRUCTION: &str = include_str!("../prompts/output_terse.txt");
pub const REPLY_LANGUAGE_CLAUSE: &str = " Reply in the user's language.";
pub const DRAFT_INSTRUCTION: &str = include_str!("../prompts/output_draft.txt");
pub const COMPACT_CODE_INSTRUCTION: &str = include_str!("../prompts/output_compact_code.txt");
pub const TOKEN_BUDGET_TMPL: &str = include_str!("../prompts/output_token_budget.txt");
pub const TOOLS_FRUGAL_INSTRUCTION: &str = include_str!("../prompts/tools_frugal.txt");
const TOOLS_FRUGAL_MARKER: &str = "fewest tool-use turns";
pub const ANTI_OVERTHINK_INSTRUCTION: &str = include_str!("../prompts/output_anti_overthink.txt");
const ANTI_OVERTHINK_MARKER: &str = "commit to it immediately";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputLevel {
Terse,
Draft,
}
impl OutputLevel {
pub fn parse(s: &str) -> Self {
match s.to_ascii_lowercase().as_str() {
"draft" | "cod" => OutputLevel::Draft,
_ => OutputLevel::Terse,
}
}
fn instruction(self) -> &'static str {
match self {
OutputLevel::Terse => TERSE_INSTRUCTION,
OutputLevel::Draft => DRAFT_INSTRUCTION,
}
}
}
pub struct OutputControlStage {
pub output_control: bool,
pub level: OutputLevel,
pub max_tokens: Option<u64>,
pub token_budget: Option<u64>,
pub compact_code: bool,
pub frugal_tools: bool,
pub anti_overthink: bool,
}
impl Transform for OutputControlStage {
fn name(&self) -> &str {
"output-control"
}
fn gate_kind(&self) -> GateKind {
GateKind::OutputShaping
}
fn apply(
&self,
req: &mut Request,
provider: &dyn Provider,
_plan: &mut Vec<PlanEntry>,
) -> Result<()> {
let mut injected_any = false;
if self.output_control && (!tool_call_shaped(req) || is_first_turn(req)) {
provider.add_system_instruction(req, self.level.instruction());
injected_any = true;
}
if !tool_call_shaped(req) {
if let Some(budget) = self.token_budget
&& !reasoning_model_request(req)
{
provider.add_system_instruction(
req,
&TOKEN_BUDGET_TMPL.replace("{budget}", &budget.to_string()),
);
injected_any = true;
}
if self.compact_code {
provider.add_system_instruction(req, COMPACT_CODE_INSTRUCTION);
injected_any = true;
}
}
if self.frugal_tools
&& tool_call_shaped(req)
&& is_first_turn(req)
&& crate::llmtrim::capability::model_honors_steering(req.model_id().unwrap_or(""))
&& !frugal_directive_present(req, provider)
{
provider.add_system_instruction(req, TOOLS_FRUGAL_INSTRUCTION);
injected_any = true;
}
if self.anti_overthink
&& (!tool_call_shaped(req) || is_first_turn(req))
&& (reasoning_model_request(req)
|| crate::llmtrim::capability::model_is_reasoning_capable(
req.model_id().unwrap_or(""),
))
&& !anti_overthink_present(req, provider)
{
provider.add_system_instruction(req, ANTI_OVERTHINK_INSTRUCTION);
injected_any = true;
}
if injected_any && detect_lang(&user_prose(req, provider)) != Some(whatlang::Lang::Eng) {
provider.add_system_instruction(req, REPLY_LANGUAGE_CLAUSE.trim());
}
if let Some(cap) = self.max_tokens
&& provider.max_tokens(req).is_none()
{
provider.set_max_tokens(req, cap);
}
Ok(())
}
}
fn tool_call_shaped(req: &Request) -> bool {
let raw = req.raw();
raw.get("tools")
.and_then(Value::as_array)
.is_some_and(|t| !t.is_empty())
&& raw.get("tool_choice").and_then(Value::as_str) != Some("none")
}
fn frugal_directive_present(req: &Request, provider: &dyn Provider) -> bool {
provider.content_text_pointers(req).iter().any(|ptr| {
matches!(provider.role_at(req, ptr), Some(Role::System) | None)
&& req
.get_str(ptr)
.is_some_and(|t| t.contains(TOOLS_FRUGAL_MARKER))
})
}
fn anti_overthink_present(req: &Request, provider: &dyn Provider) -> bool {
provider.content_text_pointers(req).iter().any(|ptr| {
matches!(provider.role_at(req, ptr), Some(Role::System) | None)
&& req
.get_str(ptr)
.is_some_and(|t| t.contains(ANTI_OVERTHINK_MARKER))
})
}
fn reasoning_model_request(req: &Request) -> bool {
let raw = req.raw();
raw.get("reasoning").is_some()
|| raw.get("reasoning_effort").is_some()
|| raw.get("thinking").is_some()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::llmtrim::ir::ProviderKind;
use crate::llmtrim::pipeline;
use crate::llmtrim::provider::OpenAiProvider;
use crate::llmtrim::tokenizer::counter_for;
use serde_json::json;
fn run_one(body: Value, stage: OutputControlStage) -> Request {
let mut req = Request::from_value(ProviderKind::OpenAi, body);
let counter = counter_for(ProviderKind::OpenAi, Some("gpt-4o")).unwrap();
let stages: Vec<Box<dyn Transform>> = vec![Box::new(stage)];
let _ = pipeline::run(&mut req, &OpenAiProvider, counter.as_ref(), &stages);
req
}
fn run_with(
kind: ProviderKind,
provider: &dyn Provider,
body: Value,
stage: OutputControlStage,
) -> Request {
let mut req = Request::from_value(kind, body);
let counter = counter_for(ProviderKind::OpenAi, Some("gpt-4o")).unwrap();
let stages: Vec<Box<dyn Transform>> = vec![Box::new(stage)];
let _ = pipeline::run(&mut req, provider, counter.as_ref(), &stages);
req
}
fn frugal_stage() -> OutputControlStage {
OutputControlStage {
output_control: false,
level: OutputLevel::Terse,
max_tokens: None,
token_budget: None,
compact_code: false,
frugal_tools: true,
anti_overthink: false,
}
}
#[test]
fn level_parses() {
assert_eq!(OutputLevel::parse("draft"), OutputLevel::Draft);
assert_eq!(OutputLevel::parse("terse"), OutputLevel::Terse);
assert_eq!(OutputLevel::parse("ultra"), OutputLevel::Terse);
assert_eq!(OutputLevel::parse("whatever"), OutputLevel::Terse);
}
#[test]
fn draft_injects_chain_of_draft() {
let req = run_one(
json!({"messages":[{"role":"user","content":"hi"}]}),
OutputControlStage {
output_control: true,
level: OutputLevel::Draft,
max_tokens: None,
token_budget: None,
compact_code: false,
frugal_tools: false,
anti_overthink: false,
},
);
let sys = req.get_str("/messages/0/content").unwrap();
assert!(sys.contains("draft") && sys.contains("step"));
}
#[test]
fn token_budget_injects_soft_limit() {
let req = run_one(
json!({"messages":[{"role":"user","content":"hi"}]}),
OutputControlStage {
output_control: true,
level: OutputLevel::Terse,
max_tokens: None,
token_budget: Some(120),
compact_code: false,
frugal_tools: false,
anti_overthink: false,
},
);
let joined: String = req
.raw()
.pointer("/messages")
.and_then(Value::as_array)
.unwrap()
.iter()
.filter_map(|m| m.get("content").and_then(Value::as_str))
.collect();
assert!(joined.contains("120 tokens"), "soft budget injected");
}
#[test]
fn first_turn_tool_call_gets_terse_but_not_budget_or_compact() {
let req = run_one(
json!({"messages":[{"role":"user","content":"book a flight"}],
"tools":[{"type":"function","function":{"name":"book","parameters":{}}}],
"tool_choice":"auto"}),
OutputControlStage {
output_control: true,
level: OutputLevel::Terse,
max_tokens: Some(900),
token_budget: Some(120),
compact_code: true,
frugal_tools: false,
anti_overthink: false,
},
);
let joined: String = req
.raw()
.pointer("/messages")
.and_then(Value::as_array)
.unwrap()
.iter()
.filter_map(|m| m.get("content").and_then(Value::as_str))
.collect();
assert!(
joined.contains("concise"),
"first-turn terse injected: {joined}"
);
assert!(
!joined.contains("120 tokens"),
"soft budget stays prose-only: {joined}"
);
assert_eq!(
req.raw()
.get("max_completion_tokens")
.and_then(Value::as_u64),
Some(900),
"hard cap still set (free)"
);
}
#[test]
fn later_tool_call_turn_skips_terse() {
let req = run_one(
json!({"messages":[
{"role":"user","content":"book a flight"},
{"role":"assistant","tool_calls":[
{"id":"c1","type":"function","function":{"name":"book","arguments":"{}"}}]},
{"role":"tool","tool_call_id":"c1","content":"no seats"}],
"tools":[{"type":"function","function":{"name":"book","parameters":{}}}],
"tool_choice":"auto"}),
OutputControlStage {
output_control: true,
level: OutputLevel::Terse,
max_tokens: None,
token_budget: None,
compact_code: false,
frugal_tools: false,
anti_overthink: false,
},
);
let joined: String = req
.raw()
.pointer("/messages")
.and_then(Value::as_array)
.unwrap()
.iter()
.filter_map(|m| m.get("content").and_then(Value::as_str))
.collect();
assert!(
!joined.contains("concise"),
"no terse on a later tool-call turn: {joined}"
);
}
#[test]
fn tool_choice_none_restores_prose_shaping() {
let req = run_one(
json!({"messages":[{"role":"user","content":"book a flight"}],
"tools":[{"type":"function","function":{"name":"book","parameters":{}}}],
"tool_choice":"none"}),
OutputControlStage {
output_control: true,
level: OutputLevel::Terse,
max_tokens: None,
token_budget: None,
compact_code: false,
frugal_tools: false,
anti_overthink: false,
},
);
let sys = req.get_str("/messages/0/content").unwrap();
assert!(sys.contains("concise"), "prose shaping applies: {sys}");
}
#[test]
fn frugal_tools_injects_on_tool_call_request_only() {
let req = run_one(
json!({"messages":[{"role":"user","content":"find the bug"}],
"tools":[{"type":"function","function":{"name":"grep","parameters":{}}}],
"tool_choice":"auto"}),
OutputControlStage {
output_control: true,
level: OutputLevel::Terse,
max_tokens: None,
token_budget: None,
compact_code: false,
frugal_tools: true,
anti_overthink: false,
},
);
let joined = joined_content(&req);
assert!(
joined.contains("fewest tool-use turns") && joined.contains("concise"),
"frugal directive and first-turn terse both fire on tool-call shape: {joined}"
);
let prose = run_one(
json!({"messages":[{"role":"user","content":"explain this"}]}),
OutputControlStage {
output_control: true,
level: OutputLevel::Terse,
max_tokens: None,
token_budget: None,
compact_code: false,
frugal_tools: true,
anti_overthink: false,
},
);
let pj = joined_content(&prose);
assert!(
pj.contains("concise") && !pj.contains("fewest tool-use turns"),
"no frugal directive on a prose request: {pj}"
);
}
#[test]
fn frugal_tools_gated_by_model_capability() {
let body = |model: &str| {
json!({"model": model,
"messages":[{"role":"user","content":"find the bug"}],
"tools":[{"type":"function","function":{"name":"grep","parameters":{}}}],
"tool_choice":"auto"})
};
let weak = run_one(body("gpt-4o-mini"), frugal_stage());
assert!(
!joined_content(&weak).contains("fewest tool-use turns"),
"weak model is gated out of the frugal directive: {}",
joined_content(&weak)
);
let capable = run_one(body("claude-opus-4-8"), frugal_stage());
assert!(
joined_content(&capable).contains("fewest tool-use turns"),
"capable model still gets the directive: {}",
joined_content(&capable)
);
}
#[test]
fn frugal_gate_reads_gemini_model_from_url_hint() {
use crate::llmtrim::provider::GoogleProvider;
let run_gemini = |model: &str| -> Request {
let mut req = Request::from_value(
ProviderKind::Google,
json!({"contents":[{"role":"user","parts":[{"text":"find the bug"}]}],
"tools":[{"functionDeclarations":[{"name":"grep"}]}]}),
);
req.set_model_hint(Some(model));
let counter = counter_for(ProviderKind::OpenAi, Some("gpt-4o")).unwrap();
let stages: Vec<Box<dyn Transform>> = vec![Box::new(frugal_stage())];
let _ = pipeline::run(&mut req, &GoogleProvider, counter.as_ref(), &stages);
req
};
let has_directive = |req: &Request| {
GoogleProvider.content_text_pointers(req).iter().any(|p| {
req.get_str(p)
.is_some_and(|t| t.contains(TOOLS_FRUGAL_MARKER))
})
};
assert!(
!has_directive(&run_gemini("gemini-2.0-flash")),
"weak Gemini tier (URL model, below the bar) is gated out"
);
assert!(
has_directive(&run_gemini("gemini-3-pro")),
"capable Gemini tier still gets the directive via the URL-model hint"
);
}
#[test]
fn frugal_tools_skips_past_first_turn() {
let req = run_one(
json!({"messages":[
{"role":"user","content":"find the bug"},
{"role":"assistant","content":null,
"tool_calls":[{"id":"c1","type":"function",
"function":{"name":"grep","arguments":"{}"}}]},
{"role":"tool","tool_call_id":"c1","content":"match at line 4"}],
"tools":[{"type":"function","function":{"name":"grep","parameters":{}}}],
"tool_choice":"auto"}),
OutputControlStage {
output_control: true,
level: OutputLevel::Terse,
max_tokens: None,
token_budget: None,
compact_code: false,
frugal_tools: true,
anti_overthink: false,
},
);
assert!(
!joined_content(&req).contains("fewest tool-use turns"),
"no re-inject once the loop is live: {}",
joined_content(&req)
);
}
#[test]
fn frugal_tools_idempotent_when_already_present() {
let req = run_one(
json!({"messages":[
{"role":"system","content":TOOLS_FRUGAL_INSTRUCTION},
{"role":"user","content":"find the bug"}],
"tools":[{"type":"function","function":{"name":"grep","parameters":{}}}],
"tool_choice":"auto"}),
OutputControlStage {
output_control: true,
level: OutputLevel::Terse,
max_tokens: None,
token_budget: None,
compact_code: false,
frugal_tools: true,
anti_overthink: false,
},
);
let hits = joined_content(&req)
.matches("fewest tool-use turns")
.count();
assert_eq!(hits, 1, "directive present exactly once, not duplicated");
}
#[test]
fn frugal_marker_is_substring_of_the_prompt() {
assert!(
TOOLS_FRUGAL_INSTRUCTION.contains(TOOLS_FRUGAL_MARKER),
"marker {TOOLS_FRUGAL_MARKER:?} must be a substring of the prompt {TOOLS_FRUGAL_INSTRUCTION:?}"
);
}
#[test]
fn frugal_alone_does_not_leak_terse_on_prose() {
let req = run_one(
json!({"messages":[{"role":"user","content":"explain this"}]}),
frugal_stage(),
);
let joined = joined_content(&req);
assert!(
!joined.contains("concise") && !joined.contains("fewest tool-use turns"),
"frugal-only stage stays silent on a prose request: {joined}"
);
}
#[test]
fn frugal_idempotent_on_anthropic_top_level_system() {
let req = run_with(
ProviderKind::Anthropic,
&crate::llmtrim::provider::AnthropicProvider,
json!({"system": TOOLS_FRUGAL_INSTRUCTION,
"messages":[{"role":"user","content":"find the bug"}],
"tools":[{"name":"grep","input_schema":{"type":"object"}}]}),
frugal_stage(),
);
let system = req
.raw()
.get("system")
.and_then(Value::as_str)
.unwrap_or("");
assert_eq!(
system.matches("fewest tool-use turns").count(),
1,
"directive present exactly once in Anthropic system, not duplicated: {system}"
);
}
#[test]
fn frugal_injects_on_anthropic_first_turn() {
let req = run_with(
ProviderKind::Anthropic,
&crate::llmtrim::provider::AnthropicProvider,
json!({"system":"You are a helpful assistant.",
"messages":[{"role":"user","content":"find the bug"}],
"tools":[{"name":"grep","input_schema":{"type":"object"}}]}),
frugal_stage(),
);
let system = req
.raw()
.get("system")
.and_then(Value::as_str)
.unwrap_or("");
assert!(
system.contains("fewest tool-use turns"),
"directive injected into Anthropic system on first turn: {system}"
);
}
#[test]
fn frugal_idempotent_on_responses_instructions() {
let req = run_with(
ProviderKind::OpenAi,
&OpenAiProvider,
json!({"instructions": TOOLS_FRUGAL_INSTRUCTION,
"input":[{"role":"user","content":"find the bug"}],
"tools":[{"type":"function","name":"grep","parameters":{}}]}),
frugal_stage(),
);
let instr = req
.raw()
.get("instructions")
.and_then(Value::as_str)
.unwrap_or("");
assert_eq!(
instr.matches("fewest tool-use turns").count(),
1,
"directive present exactly once in Responses instructions, not duplicated: {instr}"
);
}
#[test]
fn terse_injects_concise() {
let req = run_one(
json!({"messages":[{"role":"user","content":"hi"}]}),
OutputControlStage {
output_control: true,
level: OutputLevel::Terse,
max_tokens: None,
token_budget: None,
compact_code: false,
frugal_tools: false,
anti_overthink: false,
},
);
let sys = req.get_str("/messages/0/content").unwrap();
assert!(sys.contains("concise"));
assert!(
sys.contains("Reply in the user's language."),
"language-preservation clause rides the shaping instruction: {sys}"
);
assert_eq!(
req.raw()
.pointer("/messages/0/role")
.and_then(Value::as_str),
Some("system")
);
}
#[test]
fn non_english_prompt_gets_language_clause() {
let req = run_one(
json!({"messages":[{"role":"user",
"content":"Peux-tu m'expliquer comment fonctionne ce module de compression ?"}]}),
OutputControlStage {
output_control: true,
level: OutputLevel::Terse,
max_tokens: None,
token_budget: None,
compact_code: false,
frugal_tools: false,
anti_overthink: false,
},
);
let sys = req.get_str("/messages/0/content").unwrap();
assert!(
sys.contains("Reply in the user's language."),
"non-English prompt keeps the language clause: {sys}"
);
}
#[test]
fn english_prompt_skips_language_clause() {
let req = run_one(
json!({"messages":[{"role":"user",
"content":"Can you explain how this compression module works under the hood?"}]}),
OutputControlStage {
output_control: true,
level: OutputLevel::Terse,
max_tokens: None,
token_budget: None,
compact_code: false,
frugal_tools: false,
anti_overthink: false,
},
);
let sys = req.get_str("/messages/0/content").unwrap();
assert!(sys.contains("concise"), "shaping still applies: {sys}");
assert!(
!sys.contains("Reply in the user's language."),
"English prompt pays no clause tokens: {sys}"
);
}
#[test]
fn user_prose_caps_a_huge_block_without_panicking() {
let huge = "é".repeat(1_000_000); let req = Request::from_value(
ProviderKind::OpenAi,
json!({"messages": [{"role": "user", "content": huge}]}),
);
let sample = user_prose(&req, &OpenAiProvider);
assert!(
sample.len() <= PROSE_SAMPLE_MAX_BYTES + 1,
"sample bounded: {}",
sample.len()
);
}
#[test]
fn non_english_prompt_with_leading_code_still_gets_language_clause() {
let code_block = format!(
"```rust\n{}\n```",
"fn compress(input: &str) -> String { input.to_string() }\n".repeat(200)
);
let req = run_one(
json!({"messages":[
{"role":"user","content": code_block},
{"role":"user",
"content":"Peux-tu m'expliquer comment fonctionne ce module de compression ?"}
]}),
OutputControlStage {
output_control: true,
level: OutputLevel::Terse,
max_tokens: None,
token_budget: None,
compact_code: false,
frugal_tools: false,
anti_overthink: false,
},
);
let sys = req.get_str("/messages/0/content").unwrap();
assert!(
sys.contains("Reply in the user's language."),
"leading pasted code must not hide the live French question: {sys}"
);
}
#[test]
fn strip_code_removes_fenced_inline_and_indented_code() {
let text = "Explique-moi ce code:\n\
```rust\n\
fn main() { println!(\"hi\"); }\n\
```\n\
Utilise la fonction `foo()` pour ça.\n\
Et cette ligne indentée:\n\
\x20\x20\x20\x20let x = 1 + 2;\n\
Merci beaucoup pour ton aide !";
let stripped = strip_code(text);
assert!(
!stripped.contains("println"),
"fenced block removed: {stripped}"
);
assert!(
!stripped.contains("foo()"),
"inline span removed: {stripped}"
);
assert!(
!stripped.contains("let x = 1"),
"indented code removed: {stripped}"
);
assert!(
stripped.contains("Explique-moi ce code"),
"surrounding prose kept: {stripped}"
);
assert!(
stripped.contains("Merci beaucoup pour ton aide"),
"surrounding prose kept: {stripped}"
);
}
#[test]
fn user_prose_prefers_last_turn_over_earlier_huge_paste() {
let huge_code = format!(
"```\n{}\n```",
"const x = { a: 1, b: 2 }; y = (a || b) && c;\n".repeat(5000)
);
let req = Request::from_value(
ProviderKind::OpenAi,
json!({"messages": [
{"role": "user", "content": huge_code},
{"role": "user",
"content": "Peux-tu m'expliquer comment fonctionne ce module de compression ?"}
]}),
);
let sample = user_prose(&req, &OpenAiProvider);
assert!(
sample.contains("Peux-tu"),
"last turn's French prose must survive the budget cap: {sample}"
);
assert_eq!(
detect_lang(&sample),
Some(whatlang::Lang::Fra),
"sample must detect as French: {sample}"
);
}
#[test]
fn user_prose_prefers_last_turn_over_earlier_huge_non_code_prose() {
let huge_prose = "This is a filler sentence about nothing in particular. ".repeat(200);
assert!(
huge_prose.len() > PROSE_SAMPLE_MAX_BYTES,
"filler prose must exceed the budget on its own"
);
let req = Request::from_value(
ProviderKind::OpenAi,
json!({"messages": [
{"role": "user", "content": huge_prose},
{"role": "user",
"content": "Peux-tu m'expliquer comment fonctionne ce module de compression ?"}
]}),
);
let sample = user_prose(&req, &OpenAiProvider);
assert!(
sample.contains("Peux-tu"),
"last turn's French prose must survive the budget cap: {sample}"
);
assert_eq!(
detect_lang(&sample),
Some(whatlang::Lang::Fra),
"sample must detect as French: {sample}"
);
}
#[test]
fn sets_max_tokens_only_when_absent() {
let req = run_one(
json!({"messages":[{"role":"user","content":"hi"}]}),
OutputControlStage {
output_control: true,
level: OutputLevel::Terse,
max_tokens: Some(256),
token_budget: None,
compact_code: false,
frugal_tools: false,
anti_overthink: false,
},
);
assert_eq!(OpenAiProvider.max_tokens(&req), Some(256));
let req2 = run_one(
json!({"max_tokens":99,"messages":[{"role":"user","content":"hi"}]}),
OutputControlStage {
output_control: true,
level: OutputLevel::Terse,
max_tokens: Some(256),
token_budget: None,
compact_code: false,
frugal_tools: false,
anti_overthink: false,
},
);
assert_eq!(
OpenAiProvider.max_tokens(&req2),
Some(99),
"must not overwrite a caller-set cap"
);
}
fn joined_content(req: &Request) -> String {
req.raw()
.pointer("/messages")
.and_then(Value::as_array)
.unwrap()
.iter()
.filter_map(|m| m.get("content").and_then(Value::as_str))
.collect()
}
#[test]
fn reasoning_request_skips_soft_budget_keeps_terse_and_cap() {
let req = run_one(
json!({"model":"deepseek/deepseek-r1","reasoning":{"effort":"high"},
"messages":[{"role":"user","content":"hi"}]}),
OutputControlStage {
output_control: true,
level: OutputLevel::Terse,
max_tokens: Some(256),
token_budget: Some(120),
compact_code: false,
frugal_tools: false,
anti_overthink: false,
},
);
let joined = joined_content(&req);
assert!(
!joined.contains("120 tokens"),
"soft budget must be skipped on a reasoning model: {joined}"
);
assert!(
joined.contains("concise"),
"terse instruction still injected: {joined}"
);
assert_eq!(OpenAiProvider.max_tokens(&req), Some(256), "hard cap stays");
}
#[test]
fn reasoning_field_skips_soft_budget() {
let req = run_one(
json!({"model":"some-model","reasoning":{"effort":"low"},
"messages":[{"role":"user","content":"hi"}]}),
OutputControlStage {
output_control: true,
level: OutputLevel::Terse,
max_tokens: None,
token_budget: Some(120),
compact_code: false,
frugal_tools: false,
anti_overthink: false,
},
);
assert!(!joined_content(&req).contains("120 tokens"));
}
#[test]
fn non_reasoning_model_still_gets_soft_budget() {
let req = run_one(
json!({"model":"gpt-4o-mini",
"messages":[{"role":"user","content":"hi"}]}),
OutputControlStage {
output_control: true,
level: OutputLevel::Terse,
max_tokens: None,
token_budget: Some(120),
compact_code: false,
frugal_tools: false,
anti_overthink: false,
},
);
assert!(
joined_content(&req).contains("120 tokens"),
"soft budget must still be injected on a non-reasoning model"
);
}
fn req_with(body: Value) -> Request {
Request::from_value(ProviderKind::OpenAi, body)
}
#[test]
fn detects_reasoning_request_fields() {
assert!(reasoning_model_request(&req_with(
json!({"model":"x","reasoning":{"effort":"low"}})
)));
assert!(reasoning_model_request(&req_with(
json!({"model":"x","reasoning_effort":"high"})
)));
assert!(reasoning_model_request(&req_with(
json!({"model":"claude-3-7-sonnet","thinking":{"type":"enabled","budget_tokens":1024}})
)));
}
#[test]
fn model_id_alone_never_marks_reasoning() {
for id in [
"deepseek/deepseek-r1",
"o1-mini",
"openai/gpt-5",
"qwen/qwq-32b",
"gpt-4o",
"phi-4",
"solar-pro",
] {
assert!(
!reasoning_model_request(&req_with(json!({"model": id}))),
"{id}: id-based detection must never fire (fields-only)"
);
}
assert!(!reasoning_model_request(&req_with(
json!({"messages":[{"role":"user","content":"hi"}]})
)));
}
#[test]
fn compact_code_injects_instruction() {
let req = run_one(
json!({"messages":[{"role":"user","content":"hi"}]}),
OutputControlStage {
output_control: true,
level: OutputLevel::Terse,
max_tokens: None,
token_budget: None,
compact_code: true,
frugal_tools: false,
anti_overthink: false,
},
);
let joined: String = req
.raw()
.pointer("/messages")
.and_then(Value::as_array)
.unwrap()
.iter()
.filter_map(|m| m.get("content").and_then(Value::as_str))
.collect();
assert!(
joined.contains("minified"),
"compact-code instruction injected"
);
}
fn anti_overthink_stage() -> OutputControlStage {
OutputControlStage {
output_control: false,
level: OutputLevel::Terse,
max_tokens: None,
token_budget: None,
compact_code: false,
frugal_tools: false,
anti_overthink: true,
}
}
#[test]
fn anti_overthink_marker_is_substring_of_the_prompt() {
assert!(
ANTI_OVERTHINK_INSTRUCTION.contains(ANTI_OVERTHINK_MARKER),
"marker {ANTI_OVERTHINK_MARKER:?} must be a substring of the prompt {ANTI_OVERTHINK_INSTRUCTION:?}"
);
}
#[test]
fn anti_overthink_injects_on_any_reasoning_pass() {
for req in [
json!({"provider":{"quantizations":["fp4"]},
"reasoning":{"effort":"medium"},
"messages":[{"role":"user","content":"what is 2+2?"}]}),
json!({"reasoning":{"effort":"medium"},
"messages":[{"role":"user","content":"what is 2+2?"}]}),
json!({"thinking":{"type":"enabled","budget_tokens":1024},
"messages":[{"role":"user","content":"what is 2+2?"}]}),
] {
let out = run_one(req, anti_overthink_stage());
assert!(
joined_content(&out).contains(ANTI_OVERTHINK_MARKER),
"reasoning pass gets the directive: {}",
joined_content(&out)
);
}
let no_reasoning = json!({"provider":{"quantizations":["fp4"]},
"messages":[{"role":"user","content":"what is 2+2?"}]});
let req = run_one(no_reasoning, anti_overthink_stage());
assert!(
!joined_content(&req).contains(ANTI_OVERTHINK_MARKER),
"non-reasoning request stays silent: {}",
joined_content(&req)
);
}
#[test]
fn anti_overthink_fires_on_tool_call_shaped_reasoning_requests() {
let req = run_one(
json!({"reasoning":{"effort":"medium"},
"messages":[{"role":"user","content":"find the bug"}],
"tools":[{"type":"function","function":{"name":"grep","parameters":{}}}],
"tool_choice":"auto"}),
anti_overthink_stage(),
);
assert!(
joined_content(&req).contains(ANTI_OVERTHINK_MARKER),
"anti-overthink directive rides a tool-call-shaped reasoning request: {}",
joined_content(&req)
);
}
#[test]
fn anti_overthink_detects_reasoning_model_by_id_without_a_wire_field() {
let req = run_one(
json!({"model":"claude-sonnet-5",
"messages":[{"role":"user","content":"find the bug"}],
"tools":[{"type":"function","function":{"name":"grep","parameters":{}}}],
"tool_choice":"auto"}),
anti_overthink_stage(),
);
assert!(
joined_content(&req).contains(ANTI_OVERTHINK_MARKER),
"anti-overthink fires on a known reasoning model with no wire field: {}",
joined_content(&req)
);
let req = run_one(
json!({"model":"gpt-4o-mini",
"messages":[{"role":"user","content":"find the bug"}],
"tools":[{"type":"function","function":{"name":"grep","parameters":{}}}],
"tool_choice":"auto"}),
anti_overthink_stage(),
);
assert!(
!joined_content(&req).contains(ANTI_OVERTHINK_MARKER),
"non-reasoning model stays silent: {}",
joined_content(&req)
);
}
#[test]
fn anti_overthink_first_turn_gate_applies_only_to_the_agent_path() {
let chat = run_one(
json!({"model":"claude-sonnet-5",
"messages":[
{"role":"user","content":"hi"},
{"role":"assistant","content":"hello"},
{"role":"user","content":"what is 17*23?"}]}),
anti_overthink_stage(),
);
assert!(
joined_content(&chat).contains(ANTI_OVERTHINK_MARKER),
"multi-turn prose chat keeps the directive: {}",
joined_content(&chat)
);
let later_agent_turn = run_one(
json!({"model":"claude-sonnet-5",
"messages":[
{"role":"user","content":"find the bug"},
{"role":"assistant","tool_calls":[
{"id":"c1","type":"function","function":{"name":"grep","arguments":"{}"}}]},
{"role":"tool","tool_call_id":"c1","content":"no match"}],
"tools":[{"type":"function","function":{"name":"grep","parameters":{}}}],
"tool_choice":"auto"}),
anti_overthink_stage(),
);
assert!(
!joined_content(&later_agent_turn).contains(ANTI_OVERTHINK_MARKER),
"later agent turn stays silent (first-turn-only on the tool path): {}",
joined_content(&later_agent_turn)
);
}
#[test]
fn anti_overthink_idempotent_when_already_present() {
let req = run_one(
json!({"provider":{"quantizations":["fp4"]},
"reasoning":{"effort":"medium"},
"messages":[
{"role":"system","content":ANTI_OVERTHINK_INSTRUCTION},
{"role":"user","content":"what is 2+2?"}]}),
anti_overthink_stage(),
);
let hits = joined_content(&req).matches(ANTI_OVERTHINK_MARKER).count();
assert_eq!(hits, 1, "directive present exactly once, not duplicated");
}
#[test]
fn agent_rag_code_aggressive_presets_enable_anti_overthink() {
for p in ["agent", "rag", "code", "aggressive"] {
assert!(
crate::llmtrim::config::DenseConfig::preset(p)
.unwrap()
.output_anti_overthink,
"{p} should enable the anti-overthink lever"
);
}
for p in ["safe", "lossless", "frugal"] {
assert!(
!crate::llmtrim::config::DenseConfig::preset(p)
.unwrap()
.output_anti_overthink,
"{p} must stay silent — no behavioral directive"
);
}
}
}