Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ during the 2.x migration are no longer part of the TinyAgents workspace.
The unreleased entries below describe the changes accumulated before this
major release.

## Unreleased: a refused reasoning-off call is sent again

A provider endpoint that cannot run without reasoning refuses a request sent
with `ReasoningEffort::None` (`HTTP 400: Reasoning is mandatory for this
endpoint and cannot be disabled.`). That refusal used to end the run. The
request now goes out once more with no reasoning setting, so the provider's
default applies. It mattered most with `RunPolicy::truncated_empty_reasoning_off`,
which turns reasoning off for the call after a dead one on whichever endpoint a
router picks next.

## Unreleased: tool hook denials answer the model

**Breaking (behaviour).** A `tinyagents-hooks` tool-hook `Deny` no longer
Expand Down
8 changes: 8 additions & 0 deletions crates/tinyagents-harness/src/agent_loop/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,14 @@ threshold applies independently of the one-call setting. These controls can
combine with constant-cap retries to avoid spending a larger budget on the
same reasoning-only failure.

Some provider endpoints cannot run without reasoning and refuse a request
that turns it off (OpenRouter relays `HTTP 400: Reasoning is mandatory for
this endpoint and cannot be disabled.`). Any request sent with
`ReasoningEffort::None` that is refused this way, whether these controls or
the caller turned reasoning off, goes out once more with no reasoning setting,
so the provider's own default applies. The resend is not a retry: it is not
counted against `RunPolicy::retry` and emits no `RetryScheduled`.

A hosted reasoning model on a high effort setting can deliberate past the
boosted budget too. Once the retries are spent the loop does not finish on the
blank reply: up to `RunPolicy::truncated_empty_nudges` times (default `1`) it
Expand Down
46 changes: 46 additions & 0 deletions crates/tinyagents-harness/src/agent_loop/model_call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -857,6 +857,23 @@ impl<State: Send + Sync, Ctx: Send + Sync> AgentHarness<State, Ctx> {
match attempt_result {
Ok(response) => break Ok(response),
Err(error) => {
// A provider that cannot run without reasoning
// refuses a request that turns it off. No retry of
// the same request can pass and no fallback is owed:
// the request goes out once more with the provider's
// own reasoning default, which is the only way that
// endpoint answers. The attempt is not counted
// against the retry policy, and it cannot repeat,
// since the request no longer turns reasoning off.
if reasoning_off_refused(&attempt_request, &error) {
tracing::warn!(
call_id = %call_id.as_str(),
model = %current_name,
"[agent_loop] provider refused reasoning off; resending with its default"
);
attempt_request.reasoning = None;
continue;
}
// Provider and run-budget refusals are terminal: a
// retry or another model cannot make the exhausted
// budget available again.
Expand Down Expand Up @@ -2218,6 +2235,35 @@ fn retarget_request_model(request: &mut ModelRequest, name: &str) {
}
}

/// Whether `error` is a provider refusing `request` because the request
/// turns reasoning off and that provider's endpoint cannot run without it
/// (OpenRouter relays this as HTTP 400, "Reasoning is mandatory for this
/// endpoint and cannot be disabled."). Read from the message, as
/// `classify_provider_failure` reads the others: no provider gives the
/// refusal a code of its own. A request that leaves reasoning alone, or asks
/// for some, is never one of these whatever the message says.
fn reasoning_off_refused(request: &ModelRequest, error: &TinyAgentsError) -> bool {
let turned_off = request.reasoning.as_ref().is_some_and(|reasoning| {
reasoning.effort == Some(tinyinference_llm::model::ReasoningEffort::None)
});
if !turned_off {
return false;
}
let message = match error {
TinyAgentsError::Provider(error) => error.message.to_ascii_lowercase(),
TinyAgentsError::Model(message) => message.to_ascii_lowercase(),
_ => return false,
};
message.contains("reasoning")
&& ["mandatory", "cannot be disabled", "can't be disabled"]
.iter()
.any(|refusal| message.contains(refusal))
}

#[cfg(test)]
#[path = "model_call_reasoning_policy_tests.rs"]
mod reasoning_policy_tests;

#[cfg(test)]
#[path = "model_call_reasoning_refused_tests.rs"]
mod reasoning_refused_tests;
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
//! A provider endpoint that cannot run without reasoning refuses a request
//! that turns it off. The call is sent again with the provider's own default
//! instead of failing the run.

use super::*;

use std::sync::{Arc, Mutex};

use async_trait::async_trait;
use tinyinference_llm::message::Message;
use tinyinference_llm::model::{
ChatModel, ModelRequest, ModelResponse, ProviderError, ReasoningConfig, ReasoningEffort,
};

use crate::retry::RetryPolicy;
use crate::runtime::{AgentHarness, RunPolicy};

const REFUSAL: &str = "Reasoning is mandatory for this endpoint and cannot be disabled.";

/// Answers every request but one that turns reasoning off, which it refuses
/// with `refusal` as HTTP 400. Records each request it was sent.
struct ReasoningRequired {
refusal: &'static str,
requests: Mutex<Vec<ModelRequest>>,
}

impl ReasoningRequired {
fn refusing_with(refusal: &'static str) -> Arc<Self> {
Arc::new(Self {
refusal,
requests: Mutex::new(Vec::new()),
})
}

fn efforts(&self) -> Vec<Option<ReasoningEffort>> {
let requests = self.requests.lock().unwrap();
requests
.iter()
.map(|request| request.reasoning.as_ref().and_then(|r| r.effort))
.collect()
}
}

#[async_trait]
impl ChatModel<()> for ReasoningRequired {
async fn invoke(
&self,
_state: &(),
request: ModelRequest,
) -> tinyinference_llm::Result<ModelResponse> {
let off = request
.reasoning
.as_ref()
.is_some_and(|reasoning| reasoning.effort == Some(ReasoningEffort::None));
self.requests.lock().unwrap().push(request);
if off {
return Err(tinyinference_llm::Error::Provider(Box::new(
ProviderError {
provider: "test".into(),
status: Some(400),
message: self.refusal.into(),
retryable: false,
..ProviderError::default()
},
)));
}
Ok(ModelResponse::assistant("answered"))
}
}

/// A harness on `model` alone that sends every call at `effort`, with no
/// retry of its own.
fn harness(model: &Arc<ReasoningRequired>, effort: ReasoningEffort) -> AgentHarness<()> {
let mut harness: AgentHarness<()> = AgentHarness::new();
harness.with_model_resolver(Arc::new(crate::host::FixedModelResolver::named(
"primary",
model.clone(),
)));
harness.with_policy(RunPolicy {
default_reasoning: Some(ReasoningConfig::effort(effort)),
retry: RetryPolicy::default()
.with_max_attempts(1)
.with_backoff_sleep(false),
..RunPolicy::default()
});
harness
}

#[tokio::test]
async fn a_refused_reasoning_off_call_is_sent_again_with_the_providers_default() {
let model = ReasoningRequired::refusing_with(REFUSAL);
let run = harness(&model, ReasoningEffort::None)
.invoke_default(&(), vec![Message::user("hi")])
.await
.expect("the refusal is answered by resending, not by failing the run");
assert_eq!(run.text(), Some("answered".to_string()));
assert_eq!(
model.efforts(),
[Some(ReasoningEffort::None), None],
"sent once more, with no reasoning setting"
);
}

#[tokio::test]
async fn another_refusal_of_a_reasoning_off_call_still_fails() {
let model = ReasoningRequired::refusing_with("Invalid request: unknown parameter.");
let error = harness(&model, ReasoningEffort::None)
.invoke_default(&(), vec![Message::user("hi")])
.await
.expect_err("a 400 about something else is not resent");
assert!(
matches!(error, TinyAgentsError::Provider(_)),
"got {error:?}"
);
assert_eq!(model.efforts(), [Some(ReasoningEffort::None)]);
}

#[tokio::test]
async fn a_call_that_keeps_its_reasoning_is_sent_once() {
let model = ReasoningRequired::refusing_with(REFUSAL);
let run = harness(&model, ReasoningEffort::Low)
.invoke_default(&(), vec![Message::user("hi")])
.await
.expect("a call that asks for reasoning is answered");
assert_eq!(run.text(), Some("answered".to_string()));
assert_eq!(model.efforts(), [Some(ReasoningEffort::Low)]);
}

#[test]
fn only_a_reasoning_off_request_refused_for_it_counts() {
let off = ModelRequest {
reasoning: Some(ReasoningConfig::effort(ReasoningEffort::None)),
..ModelRequest::default()
};
let on = ModelRequest {
reasoning: Some(ReasoningConfig::effort(ReasoningEffort::High)),
..ModelRequest::default()
};
// As a gateway relays it in a plain model error, and as a provider error.
let relayed = TinyAgentsError::Model(format!("ephemeral-route returned HTTP 400: {REFUSAL}"));
let provider = TinyAgentsError::Provider(Box::new(ProviderError {
status: Some(400),
message: REFUSAL.into(),
..ProviderError::default()
}));
assert!(reasoning_off_refused(&off, &relayed));
assert!(reasoning_off_refused(&off, &provider));
assert!(
!reasoning_off_refused(&on, &relayed),
"it asked for reasoning"
);
assert!(!reasoning_off_refused(&ModelRequest::default(), &relayed));
let other = TinyAgentsError::Model("HTTP 400: reasoning effort `none` is not a level".into());
assert!(!reasoning_off_refused(&off, &other));
assert!(!reasoning_off_refused(&off, &TinyAgentsError::Cancelled));
}