fix(llm): a reasoning model out of tokens is asked again with a larger budget (#457)
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Successful in 5m24s

This commit was merged in pull request #457.
This commit is contained in:
sharang committed 2026-10-05 19:09:08 +00:00
1 parent 6c9756bebf
commit 96da28dd3f
2 files changed
+138 -3

No files matched your search

+135 -3
View File
@@ -156,11 +156,48 @@ impl LlmClient {
self.send_chat_request(&request_body).await
}
/// Internal method to send a chat completion request and parse the response
/// Send a chat completion request and parse the response.
///
/// A reasoning model can spend the whole token budget thinking and return
/// no answer (`finish_reason: length`, the content empty or an unclosed
/// `<think>` block). The request is then sent once more with
/// [`REASONING_RETRY_TOKENS`].
///
/// # Errors
///
/// The gateway's refusal, an unreadable response, or
/// [`REASONING_EXHAUSTED`] when even the larger budget gave no answer.
async fn send_chat_request(
&self,
request_body: &ChatCompletionRequest,
) -> Result<LlmResponse, AgentError> {
let (response, finish_reason) = self.send_once(request_body).await?;
if !exhausted(&response, finish_reason.as_deref()) {
return Ok(response);
}
if request_body.max_tokens.unwrap_or(0) >= REASONING_RETRY_TOKENS {
return Err(AgentError::Other(REASONING_EXHAUSTED.to_string()));
}
tracing::info!(
budget = request_body.max_tokens,
retry = REASONING_RETRY_TOKENS,
"the model used its token budget reasoning and gave no answer; asking again with more"
);
let mut larger = serde_json::to_value(request_body)
.map_err(|e| AgentError::Other(format!("encode chat request: {e}")))?;
larger["max_tokens"] = serde_json::json!(REASONING_RETRY_TOKENS);
let (response, finish_reason) = self.send_once(&larger).await?;
if exhausted(&response, finish_reason.as_deref()) {
return Err(AgentError::Other(REASONING_EXHAUSTED.to_string()));
}
Ok(response)
}
/// One chat completion request, and the reason the model stopped.
async fn send_once<B: serde::Serialize + ?Sized>(
&self,
request_body: &B,
) -> Result<(LlmResponse, Option<String>), AgentError> {
let mut req = self
.http
.post(self.chat_url())
@@ -193,6 +230,7 @@ impl LlmClient {
.choices
.first()
.ok_or_else(|| AgentError::Other("Empty response from LiteLLM".to_string()))?;
let finish_reason = choice.finish_reason.clone();
// Check for tool calls first
if let Some(tool_calls) = &choice.message.tool_calls {
@@ -211,16 +249,33 @@ impl LlmClient {
.collect();
// Capture any reasoning text the LLM included alongside tool calls
let reasoning = choice.message.content.clone().unwrap_or_default();
return Ok(LlmResponse::ToolCalls { calls, reasoning });
return Ok((LlmResponse::ToolCalls { calls, reasoning }, finish_reason));
}
}
// Otherwise return content
let content = choice.message.content.as_deref().unwrap_or_default();
Ok(LlmResponse::Content(without_reasoning(content)))
Ok((
LlmResponse::Content(without_reasoning(content)),
finish_reason,
))
}
}
/// The token budget of the second request when the first ran out while the
/// model was still reasoning.
const REASONING_RETRY_TOKENS: u32 = 16384;
/// The error when the model gave no answer even with
/// [`REASONING_RETRY_TOKENS`].
const REASONING_EXHAUSTED: &str =
"the model used its whole token budget reasoning and gave no answer (finish_reason=length)";
/// Whether a response is no answer because the model ran out of tokens.
fn exhausted(response: &LlmResponse, finish_reason: Option<&str>) -> bool {
matches!(response, LlmResponse::Content(c) if c.is_empty()) && finish_reason == Some("length")
}
/// `content` without a reasoning model's `<think>…</think>` blocks, which some
/// gateways return inline ahead of the answer; the callers parse the answer as
/// JSON. An unterminated block (the model ran out of tokens while thinking)
@@ -258,3 +313,80 @@ mod reasoning_tests {
assert_eq!(without_reasoning("<think>still going"), "");
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod budget_tests {
use std::sync::{Arc, Mutex};
use axum::extract::State;
use axum::routing::post;
use axum::{Json, Router};
use super::*;
/// The `max_tokens` of every request a fake gateway received; it answers
/// "still thinking" until the budget reaches `answers_from`.
type Seen = Arc<Mutex<Vec<u64>>>;
async fn fake_gateway(seen: Seen, answers_from: u64) -> String {
let app = Router::new()
.route(
"/v1/chat/completions",
post(
move |State(seen): State<Seen>, Json(body): Json<serde_json::Value>| async move {
let budget = body["max_tokens"].as_u64().unwrap_or(0);
seen.lock().unwrap().push(budget);
let (content, finish) = if budget >= answers_from {
("<think>done</think>[{\"action\":\"confirm\"}]", "stop")
} else {
("<think>weighing the first finding against", "length")
};
Json(serde_json::json!({
"choices": [{ "message": { "content": content }, "finish_reason": finish }]
}))
},
),
)
.with_state(seen);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
format!("http://{addr}")
}
fn client(base: String) -> LlmClient {
LlmClient::new(
base,
SecretString::from(String::new()),
"m".into(),
"e".into(),
)
}
#[tokio::test]
async fn a_reasoning_model_out_of_tokens_is_asked_again_with_more() {
let seen: Seen = Arc::default();
let llm = client(fake_gateway(seen.clone(), u64::from(REASONING_RETRY_TOKENS)).await);
let answer = llm.chat("s", "u", None).await.unwrap();
assert_eq!(answer, "[{\"action\":\"confirm\"}]");
assert_eq!(*seen.lock().unwrap(), [4096, 16384]);
}
#[tokio::test]
async fn no_answer_even_with_more_says_why() {
let seen: Seen = Arc::default();
let llm = client(fake_gateway(seen.clone(), u64::MAX).await);
let err = llm.chat("s", "u", None).await.unwrap_err();
assert!(err.to_string().contains("finish_reason=length"), "{err}");
assert_eq!(seen.lock().unwrap().len(), 2);
}
#[tokio::test]
async fn an_answer_in_budget_is_one_request() {
let seen: Seen = Arc::default();
let llm = client(fake_gateway(seen.clone(), 0).await);
llm.chat("s", "u", None).await.unwrap();
assert_eq!(*seen.lock().unwrap(), [4096]);
}
}
+3
View File
@@ -47,6 +47,9 @@ pub(crate) struct ChatCompletionResponse {
#[derive(Deserialize)]
pub(crate) struct ChatChoice {
pub(crate) message: ChatResponseMessage,
/// Why the model stopped; `length` when it ran out of tokens.
#[serde(default)]
pub(crate) finish_reason: Option<String>,
}
#[derive(Deserialize)]