From 5345bdbc188ef792e4f4542172ddb5906c374737 Mon Sep 17 00:00:00 2001 From: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:19:09 +0200 Subject: [PATCH] fix(llm): a reasoning model out of tokens is asked again with a larger budget On stage, a batch triage answer came back empty: the reasoning model (Qwen3.8-27B behind LiteLLM) spent chat()'s 4096 tokens thinking, so the content was empty or an unclosed block, and the client returned "" without saying why. The client now reads finish_reason. An empty answer with finish_reason=length is sent once more with 16384 tokens; if that gives no answer either, the call fails with "the model used its whole token budget reasoning and gave no answer (finish_reason=length)" instead of an empty string. Covers every chat() and chat_with_messages() caller (triage, control judge, code review, help chat). Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01EYKjxacrr6K88DruUmP48p --- compliance-agent/src/llm/client.rs | 138 ++++++++++++++++++++++++++++- compliance-agent/src/llm/types.rs | 3 + 2 files changed, 138 insertions(+), 3 deletions(-) diff --git a/compliance-agent/src/llm/client.rs b/compliance-agent/src/llm/client.rs index 30135e9..4755794 100644 --- a/compliance-agent/src/llm/client.rs +++ b/compliance-agent/src/llm/client.rs @@ -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 + /// `` 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 { + 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( + &self, + request_body: &B, + ) -> Result<(LlmResponse, Option), 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 `…` 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("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>>; + + async fn fake_gateway(seen: Seen, answers_from: u64) -> String { + let app = Router::new() + .route( + "/v1/chat/completions", + post( + move |State(seen): State, Json(body): Json| async move { + let budget = body["max_tokens"].as_u64().unwrap_or(0); + seen.lock().unwrap().push(budget); + let (content, finish) = if budget >= answers_from { + ("done[{\"action\":\"confirm\"}]", "stop") + } else { + ("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]); + } +} diff --git a/compliance-agent/src/llm/types.rs b/compliance-agent/src/llm/types.rs index 110d790..944a4a6 100644 --- a/compliance-agent/src/llm/types.rs +++ b/compliance-agent/src/llm/types.rs @@ -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, } #[derive(Deserialize)] -- 2.54.1