Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

Treat truncated and empty structured LLM responses as terminal errors

Djalma Júnior5d04975a5fee
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2c9359fc..917d27a5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- Added `AI_MEMORY_LLM_COMPAT_DISABLE_THINKING` for the `openai-compat`
+ provider (opt-in, off by default, ignored by every other provider): when
+ set, every chat request carries
+ `chat_template_kwargs: {"enable_thinking": false}`, so thinking-capable
+ local engines (vLLM / SGLang serving Qwen3-class models) spend the output
+ budget on the structured payload instead of a reasoning pass. (#PRNUM)
+
### Fixed
- Fixed the scheduled auto-improve tests' intermittent empty log captures
(the same latent flaw #1116 fixed for the hooks checkpoint test): a shared
@@ -54,6 +62,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
is now kept by both, and by the PreCompact and PostCompaction checkpoints,
which rewrote it the same way. The write no longer stamps
`observation_generation`. (#1138)
+- Fixed structured LLM responses stopped at the output budget
+ (`finish_reason = "length"`) or returned without usable content: they now
+ fail with redacted terminal errors, without copying the response. (#1130)
- Fixed the hook spool charging a spooled event's retry budget while the
server was unreachable: an endpoint-level delivery failure (connection
refused, timeout, DNS — the existing `Unreachable` classification) no
diff --git a/crates/ai-memory-cli/src/commands/llm_test.rs b/crates/ai-memory-cli/src/commands/llm_test.rs
index b43330c8..d61b5ba4 100644
--- a/crates/ai-memory-cli/src/commands/llm_test.rs
+++ b/crates/ai-memory-cli/src/commands/llm_test.rs
@@ -24,6 +24,7 @@ pub async fn run(config: &Config, args: LlmTestArgs) -> Result<()> {
auth: config.provider_auth(provider, api_key_override),
base_url: args.base_url.or_else(|| config.llm_test_base_url(provider)),
compat_strict: config.llm_compat_strict,
+ compat_disable_thinking: config.llm_compat_disable_thinking,
request_timeout_secs: config.llm_timeout_secs,
reasoning_effort: config.llm_reasoning_effort,
extra_headers: config
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index 89df0382..bf0fc6f3 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -310,6 +310,15 @@ pub struct Config {
/// already supplies its own schema. Set
/// `AI_MEMORY_LLM_COMPAT_STRICT=false` for an incompatible endpoint.
pub llm_compat_strict: bool,
+ /// OpenAI-compat only: send
+ /// `chat_template_kwargs: {"enable_thinking": false}` with every chat
+ /// request, for thinking-capable local engines (vLLM / SGLang serving
+ /// Qwen3-class models): the engine otherwise spends the output budget
+ /// on a reasoning pass before the structured payload and can truncate
+ /// it mid-JSON. Ignored by every other provider; off by default. Set
+ /// with `AI_MEMORY_LLM_COMPAT_DISABLE_THINKING` (or
+ /// `llm_compat_disable_thinking = true` in `config.toml`).
+ pub llm_compat_disable_thinking: bool,
/// Per-request timeout (seconds) applied to every chat
/// completion request and to the Copilot token exchange; the
/// openai-oauth token refresh keeps the built-in default ceiling
@@ -1078,6 +1087,7 @@ impl Default for Config {
llm_model: None,
llm_base_url: None,
llm_compat_strict: true,
+ llm_compat_disable_thinking: false,
llm_timeout_secs: ai_memory_llm::DEFAULT_REQUEST_TIMEOUT_SECS,
llm_reasoning_effort: None,
llm_headers: Vec::new(),
@@ -2213,6 +2223,7 @@ impl Config {
auth: self.provider_auth(provider, None),
base_url: self.resolve_base_url(provider),
compat_strict: self.llm_compat_strict,
+ compat_disable_thinking: self.llm_compat_disable_thinking,
request_timeout_secs: self.llm_timeout_secs,
reasoning_effort: self.llm_reasoning_effort,
extra_headers: self.llm_extra_headers()?,
@@ -2269,6 +2280,7 @@ impl Config {
auth: self.fallback_provider_auth(provider, resolved_key),
base_url: non_empty(profile.base_url.as_deref()).map(str::to_string),
compat_strict: self.llm_compat_strict,
+ compat_disable_thinking: self.llm_compat_disable_thinking,
request_timeout_secs: self.llm_timeout_secs,
reasoning_effort: self.llm_reasoning_effort,
extra_headers: self.llm_extra_headers()?,
@@ -4852,6 +4864,45 @@ mod tests {
assert!(!provider.compat_strict);
}
+ /// The thinking switch is opt-in: off by default (existing vLLM /
+ /// Ollama / LM Studio setups are unchanged) and forwarded verbatim to
+ /// the provider config when the operator turns it on.
+ #[test]
+ fn openai_compat_disable_thinking_defaults_off_and_is_forwarded() {
+ let mut cfg = Config {
+ llm_provider: Some("openai-compat".into()),
+ llm_model: Some("qwen3.8-27b".into()),
+ llm_base_url: Some("http://localhost:8000/v1".into()),
+ ..Config::default()
+ };
+
+ let provider = cfg.llm_provider_config().unwrap().unwrap();
+ assert!(!provider.compat_disable_thinking);
+
+ cfg.llm_compat_disable_thinking = true;
+ let provider = cfg.llm_provider_config().unwrap().unwrap();
+ assert!(provider.compat_disable_thinking);
+ }
+
+ /// TOML key loads and stays independent from the strict-mode default.
+ #[test]
+ fn load_accepts_llm_compat_disable_thinking_from_toml() {
+ let tmp = TempDir::new().unwrap();
+ let config_path = tmp.path().join("config.toml");
+ std::fs::write(&config_path, "llm_compat_disable_thinking = true\n").unwrap();
+ let cfg = Config::load(Some(&config_path), Some(tmp.path().to_path_buf())).unwrap();
+ assert!(cfg.llm_compat_disable_thinking);
+ // The sibling strict knob keeps its own default — independent keys.
+ assert!(cfg.llm_compat_strict);
+ }
+
+ #[test]
+ fn load_defaults_llm_compat_disable_thinking_off() {
+ let tmp = TempDir::new().unwrap();
+ let cfg = Config::load(None, Some(tmp.path().to_path_buf())).unwrap();
+ assert!(!cfg.llm_compat_disable_thinking);
+ }
+
#[test]
fn openai_oauth_provider_uses_data_dir_token_file() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-llm/src/error.rs b/crates/ai-memory-llm/src/error.rs
index e78732da..66cde7c9 100644
--- a/crates/ai-memory-llm/src/error.rs
+++ b/crates/ai-memory-llm/src/error.rs
@@ -31,6 +31,32 @@ pub enum LlmError {
#[error("unexpected response shape: {0}")]
UnexpectedShape(String),
+ /// Structured response stopped at the provider's token budget
+ /// (`finish_reason = "length"`): the engine ran out of output budget
+ /// before finishing the JSON. Terminal — a retry reproduces the same
+ /// truncation and doubles the spend. Carries only the configured
+ /// model label and the provider-reported completion token count —
+ /// never response content, prompt text, or secrets.
+ #[error(
+ "structured response truncated at token budget (finish_reason=length) for model {model}"
+ )]
+ TruncatedResponse {
+ /// Configured model label.
+ model: String,
+ /// `usage.completion_tokens` when the provider reported it.
+ completion_tokens: Option<u32>,
+ },
+
+ /// Structured request got HTTP 2xx but no usable message content
+ /// (`message.content` missing, empty, or whitespace-only). Terminal
+ /// and distinct from [`Self::TruncatedResponse`] and from a JSON
+ /// parse error: nothing was produced to parse.
+ #[error("provider returned no message content for model {model}")]
+ EmptyContent {
+ /// Configured model label.
+ model: String,
+ },
+
/// Configured provider lacks the env var we need.
#[error("provider not configured: {0}")]
NotConfigured(String),
@@ -97,6 +123,8 @@ impl LlmError {
Self::Provider { .. } => "provider",
Self::Serde(_) => "serde",
Self::UnexpectedShape(_) => "unexpected-shape",
+ Self::TruncatedResponse { .. } => "truncated-response",
+ Self::EmptyContent { .. } => "empty-content",
Self::NotConfigured(_) => "not-configured",
Self::Auth(_) => "auth",
Self::Schema(_) => "schema",
@@ -156,6 +184,43 @@ mod tests {
assert!(!LlmError::NotConfigured("no key".into()).is_transient());
}
+ // A `length` stop or an empty 2xx is a definitive answer about this
+ // response: it is not transient, and the error must carry no response
+ // content in its message.
+ #[test]
+ fn truncated_and_empty_content_are_terminal_and_content_free() {
+ let truncated = LlmError::TruncatedResponse {
+ model: "qwen3.8-27b".into(),
+ completion_tokens: Some(4096),
+ };
+ assert_eq!(truncated.class(), "truncated-response");
+ assert!(!truncated.is_transient());
+ assert_eq!(truncated.http_status(), None);
+ let rendered = truncated.to_string();
+ assert!(rendered.contains("finish_reason=length"), "{rendered}");
+ assert!(rendered.contains("qwen3.8-27b"), "{rendered}");
+
+ let empty = LlmError::EmptyContent {
+ model: "qwen3.8-27b".into(),
+ };
+ assert_eq!(empty.class(), "empty-content");
+ assert!(!empty.is_transient());
+ assert_eq!(empty.http_status(), None);
+ }
+
+ #[test]
+ fn truncated_response_message_carries_no_content() {
+ let err = LlmError::TruncatedResponse {
+ model: "qwen3.8-27b".into(),
+ completion_tokens: None,
+ };
+ let rendered = err.to_string();
+ // Only the class, the wire fact, and the operator's own model
+ // label may appear — never the (truncated) completion text.
+ assert!(!rendered.contains('{'), "{rendered}");
+ assert_eq!(rendered.matches('"').count(), 0, "{rendered}");
+ }
+
#[test]
fn all_candidates_failed_is_not_transient() {
// The aggregate error is terminal: nothing is left to advance to.
@@ -196,6 +261,17 @@ mod tests {
LlmError::UnexpectedShape("no tool block".into()),
"unexpected-shape",
),
+ (
+ LlmError::TruncatedResponse {
+ model: "qwen3.8-27b".into(),
+ completion_tokens: Some(4096),
+ },
+ "truncated-response",
+ ),
+ (
+ LlmError::EmptyContent { model: "m".into() },
+ "empty-content",
+ ),
(LlmError::NotConfigured("no key".into()), "not-configured"),
(LlmError::Auth("expired".into()), "auth"),
(LlmError::Schema("bad".into()), "schema"),
diff --git a/crates/ai-memory-llm/src/factory.rs b/crates/ai-memory-llm/src/factory.rs
index f358acee..2162c189 100644
--- a/crates/ai-memory-llm/src/factory.rs
+++ b/crates/ai-memory-llm/src/factory.rs
@@ -123,6 +123,14 @@ pub struct ProviderConfig {
/// parser. Enabled by default and ignored by every other provider.
/// Sourced once from `AI_MEMORY_LLM_COMPAT_STRICT` by `Config::load`.
pub compat_strict: bool,
+ /// OpenAI-compat only: send
+ /// `chat_template_kwargs: {"enable_thinking": false}` with every chat
+ /// request, for thinking-capable local engines (vLLM / SGLang serving
+ /// Qwen3-class models) that would otherwise spend the output budget on
+ /// a reasoning pass and truncate the structured payload. Opt-in, off
+ /// by default, ignored by every other provider. Sourced once from
+ /// `AI_MEMORY_LLM_COMPAT_DISABLE_THINKING` by `Config::load`.
+ pub compat_disable_thinking: bool,
/// Per-request timeout for every chat provider, in seconds.
/// Sourced once from `AI_MEMORY_LLM_TIMEOUT_SECS` by `Config::load`;
/// defaults to [`crate::DEFAULT_REQUEST_TIMEOUT_SECS`].
@@ -419,6 +427,7 @@ pub fn build_provider(config: ProviderConfig) -> LlmResult<Arc<dyn LlmProvider>>
Ok(Arc::new(
OpenAiCompatProvider::new(base, config.auth.optional_api_key(), config.model)?
.with_strict(config.compat_strict)
+ .with_disable_thinking(config.compat_disable_thinking)
.with_timeout_secs(timeout)
.with_reasoning_effort(config.reasoning_effort)
.with_extra_headers(extra_headers)
@@ -639,6 +648,7 @@ mod tests {
auth: ProviderAuth::required_api_key_from_env("OPENAI_API_KEY", None),
base_url: None,
compat_strict: false,
+ compat_disable_thinking: false,
request_timeout_secs: crate::DEFAULT_REQUEST_TIMEOUT_SECS,
reasoning_effort: None,
extra_headers: crate::ExtraHeaders::default(),
@@ -658,6 +668,7 @@ mod tests {
auth: ProviderAuth::optional_api_key_from_env("LLM_API_KEY", None),
base_url: Some("http://127.0.0.1:11434/v1".into()),
compat_strict: true,
+ compat_disable_thinking: false,
request_timeout_secs: crate::DEFAULT_REQUEST_TIMEOUT_SECS,
reasoning_effort: None,
extra_headers,
@@ -706,6 +717,7 @@ mod tests {
),
base_url: None,
compat_strict: false,
+ compat_disable_thinking: false,
request_timeout_secs: crate::DEFAULT_REQUEST_TIMEOUT_SECS,
reasoning_effort: None,
extra_headers: headers,
diff --git a/crates/ai-memory-llm/src/openai.rs b/crates/ai-memory-llm/src/openai.rs
index 1acd8284..a8f59d31 100644
--- a/crates/ai-memory-llm/src/openai.rs
+++ b/crates/ai-memory-llm/src/openai.rs
@@ -116,6 +116,10 @@ pub struct OpenAiProvider {
/// turns it on only for the configured `openai-compat` provider, so
/// the official OpenAI and OpenCode providers never gain the header.
request_id_header: bool,
+ /// OpenAI-compat only: send `chat_template_kwargs` with every chat
+ /// request (see [`Self::with_disable_thinking`]). Ignored by the
+ /// `Official` dialect, which would 400 on the unknown parameter.
+ disable_thinking: bool,
}
/// Defaults for a provider whose gateway wants the caller identified: an
@@ -146,6 +150,7 @@ impl OpenAiProvider {
extra_headers: ExtraHeaders::default(),
client_headers: None,
request_id_header: false,
+ disable_thinking: false,
})
}
@@ -228,6 +233,28 @@ impl OpenAiProvider {
self
}
+ /// Send `chat_template_kwargs: {"enable_thinking": false}` with every
+ /// chat request. Thinking-capable local engines (vLLM / SGLang serving
+ /// Qwen3-class models) otherwise spend the output budget on a reasoning
+ /// pass before the structured payload and can truncate it. The
+ /// `Official` dialect never emits the field — api.openai.com rejects
+ /// unknown top-level parameters — so the flag only ever reaches the
+ /// wire through the openai-compat wrapper
+ /// (`AI_MEMORY_LLM_COMPAT_DISABLE_THINKING`).
+ #[must_use]
+ pub(crate) fn with_disable_thinking(mut self, enabled: bool) -> Self {
+ self.disable_thinking = enabled;
+ self
+ }
+
+ /// Test-visible state so wrapper tests (`OpenAiCompatProvider`) can
+ /// assert the thinking switch reached the inner client without
+ /// exposing the field.
+ #[cfg(test)]
+ pub(crate) fn disable_thinking(&self) -> bool {
+ self.disable_thinking
+ }
+
/// Endpoint the client will call. Test-visible so wrappers that default
/// the base URL and let it be overridden can assert which one is set.
#[cfg(test)]
@@ -252,6 +279,23 @@ struct OpenAiRequest<'a> {
reasoning_effort: Option<ReasoningEffort>,
#[serde(skip_serializing_if = "Option::is_none")]
reasoning: Option<OpenAiReasoning>,
+ /// vLLM / SGLang / llama.cpp chat-template overrides. Emitted only by
+ /// the `Compat` dialect with the thinking switch on (see
+ /// [`OpenAiProvider::with_disable_thinking`]).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ chat_template_kwargs: Option<ChatTemplateKwargs>,
+}
+
+/// Chat-template override payload for local engines.
+///
+/// Today this carries only the thinking switch: Qwen3-class thinking
+/// models on a local engine otherwise emit `reasoning_content` (or
+/// think blocks inside `content`) that consume the output budget and
+/// truncate the structured payload that follows.
+#[derive(Debug, Serialize)]
+struct ChatTemplateKwargs {
+ /// `false` turns the engine's thinking pass off.
+ enable_thinking: bool,
}
#[derive(Debug, Serialize)]
@@ -293,6 +337,11 @@ struct OpenAiResponse {
#[derive(Debug, Deserialize)]
struct OpenAiChoice {
message: OpenAiMessageResponse,
+ /// Why the engine stopped generating: `stop`, `length`, `tool_calls`,
+ /// `content_filter`, … Engines that predate the field omit it, so the
+ /// value is optional.
+ #[serde(default)]
+ finish_reason: Option<String>,
}
#[derive(Debug, Deserialize)]
@@ -353,6 +402,27 @@ impl LlmProvider for OpenAiProvider {
}
impl OpenAiProvider {
+ /// Plain chat completion that also reports the engine's
+ /// `finish_reason` for the first choice, so the openai-compat tolerant
+ /// path can classify a `length`-truncated response before trying to
+ /// parse it. The [`LlmProvider`] [`Self::complete_with_operation_id`]
+ /// path deliberately drops the field: prose cut at the token budget is
+ /// a normal outcome there, not an error.
+ pub(crate) async fn complete_with_operation_id_and_finish_reason(
+ &self,
+ request: ChatRequest,
+ operation_id: LlmOperationId,
+ ) -> LlmResult<(ChatResponse, Option<String>)> {
+ let response = self
+ .post(&self.build_request(&request, None), operation_id)
+ .await?;
+ let finish_reason = response
+ .choices
+ .first()
+ .and_then(|c| c.finish_reason.clone());
+ Ok((self.to_chat_response(response), finish_reason))
+ }
+
async fn complete_structured(
&self,
request: ChatRequest,
@@ -378,11 +448,36 @@ impl OpenAiProvider {
operation_id,
)
.await?;
- let text = response
+ // A `length` stop on a structured response means the engine hit
+ // its output budget before the JSON could finish (observed on
+ // vLLM-hosted Qwen3 with the thinking pass on). Surface a
+ // terminal, content-free error: a tolerant retry would just
+ // re-truncate and double the token spend, and a parse failure is
+ // the wrong class — nothing is wrong with the JSON, it is cut
+ // short.
+ let finish_reason = response
+ .choices
+ .first()
+ .and_then(|c| c.finish_reason.clone());
+ if is_length_truncated(finish_reason.as_deref()) {
+ return Err(LlmError::TruncatedResponse {
+ model: self.model.clone(),
+ completion_tokens: response.usage.as_ref().map(|u| u.completion_tokens),
+ });
+ }
+ // No content at all (missing, empty, or whitespace-only) is a
+ // distinct terminal failure, not a JSON parse error: there is
+ // nothing to parse and no retry can conjure output.
+ let Some(text) = response
.choices
.first()
.and_then(|c| c.message.content.as_deref())
- .unwrap_or("");
+ .filter(|t| !t.trim().is_empty())
+ else {
+ return Err(LlmError::EmptyContent {
+ model: self.model.clone(),
+ });
+ };
serde_json::from_str::<serde_json::Value>(text).map_err(LlmError::from)
}
@@ -433,6 +528,15 @@ impl OpenAiProvider {
}
};
let (reasoning_effort, reasoning) = self.chat_reasoning_fields();
+ // Only the `Compat` dialect may carry chat-template overrides —
+ // api.openai.com rejects unknown top-level parameters, so the
+ // `Official` dialect must never emit this even if the flag was
+ // set on a wrapped client.
+ let chat_template_kwargs = (self.dialect == RequestDialect::Compat
+ && self.disable_thinking)
+ .then_some(ChatTemplateKwargs {
+ enable_thinking: false,
+ });
OpenAiRequest {
model: &self.model,
messages,
@@ -442,6 +546,7 @@ impl OpenAiProvider {
response_format,
reasoning_effort,
reasoning,
+ chat_template_kwargs,
}
}
@@ -540,6 +645,14 @@ impl OpenAiProvider {
}
}
+/// `true` when the engine reports the output stopped at the token budget
+/// rather than at a natural end. OpenAI and the local engines spell it
+/// `length`; engines that omit the field report `None` and are never
+/// truncated by this classifier.
+pub(crate) fn is_length_truncated(finish_reason: Option<&str>) -> bool {
+ finish_reason.is_some_and(|reason| reason.trim().eq_ignore_ascii_case("length"))
+}
+
/// Recursively normalise a JSON schema for OpenAI Structured Outputs
/// (`strict: true`). The endpoint rejects schemas missing either:
///
@@ -719,8 +832,9 @@ fn max_output_tokens_for(model: &str) -> u32 {
#[cfg(test)]
mod tests {
use super::{
- OpenAiProvider, REQUEST_ID_HEADER, RequestDialect, enforce_strict_object_schemas,
- model_requires_max_completion_tokens, normalize_openai_base,
+ OpenAiJsonSchema, OpenAiProvider, OpenAiResponse, OpenAiResponseFormat, REQUEST_ID_HEADER,
+ RequestDialect, STRUCTURED_OUTPUT_SCHEMA_NAME, enforce_strict_object_schemas,
+ is_length_truncated, model_requires_max_completion_tokens, normalize_openai_base,
};
use crate::provider::LlmProvider;
use crate::types::{ChatMessage, ChatRequest, LlmOperationId, ReasoningEffort, Role};
@@ -1247,6 +1361,102 @@ mod tests {
);
}
+ #[test]
+ fn build_request_compat_omits_chat_template_kwargs_by_default() {
+ // The thinking switch is opt-in: an unconfigured vLLM / Ollama /
+ // LM Studio setup must see a byte-identical request shape, so the
+ // key is absent entirely rather than false.
+ let p = OpenAiProvider::new(SecretString::new("dummy".into()), "qwen3.8-27b")
+ .unwrap()
+ .with_dialect(RequestDialect::Compat);
+ let json = serde_json::to_value(p.build_request(&chat_request(), None)).unwrap();
+ assert!(
+ json.get("chat_template_kwargs").is_none(),
+ "no chat_template_kwargs without opt-in, got {json}"
+ );
+ }
+
+ #[test]
+ fn build_request_compat_sends_enable_thinking_false_when_opted_in() {
+ let p = OpenAiProvider::new(SecretString::new("dummy".into()), "qwen3.8-27b")
+ .unwrap()
+ .with_dialect(RequestDialect::Compat)
+ .with_disable_thinking(true);
+ let json = serde_json::to_value(p.build_request(&chat_request(), None)).unwrap();
+ assert_eq!(
+ json["chat_template_kwargs"],
+ json!({ "enable_thinking": false }),
+ "opt-in must send the vLLM/SGLang thinking switch verbatim"
+ );
+ }
+
+ #[test]
+ fn build_request_official_never_emits_chat_template_kwargs() {
+ // api.openai.com rejects unknown top-level parameters; the dialect
+ // gate must hold even if the flag somehow reaches an official
+ // client (only the openai-compat wrapper sets it today).
+ let p = provider_for("gpt-4o-mini").with_disable_thinking(true);
+ let json = serde_json::to_value(p.build_request(&chat_request(), None)).unwrap();
+ assert!(
+ json.get("chat_template_kwargs").is_none(),
+ "the Official dialect must never send chat_template_kwargs, got {json}"
+ );
+ }
+
+ #[test]
+ fn build_request_structured_request_keeps_chat_template_kwargs() {
+ // The thinking switch is per-request-body, not per-endpoint: the
+ // structured path (response_format set) carries it too.
+ let p = OpenAiProvider::new(SecretString::new("dummy".into()), "qwen3.8-27b")
+ .unwrap()
+ .with_dialect(RequestDialect::Compat)
+ .with_disable_thinking(true);
+ let response_format = OpenAiResponseFormat::JsonSchema {
+ json_schema: OpenAiJsonSchema {
+ name: STRUCTURED_OUTPUT_SCHEMA_NAME.into(),
+ schema: json!({
+ "type": "object",
+ "properties": { "ok": { "type": "boolean" } },
+ "required": ["ok"]
+ }),
+ strict: true,
+ },
+ };
+ let json =
+ serde_json::to_value(p.build_request(&chat_request(), Some(response_format))).unwrap();
+ assert_eq!(
+ json["chat_template_kwargs"],
+ json!({ "enable_thinking": false }),
+ "the structured request must carry the thinking switch alongside response_format"
+ );
+ assert_eq!(json["response_format"]["type"], "json_schema");
+ }
+
+ #[test]
+ fn is_length_truncated_classifies_engine_values() {
+ assert!(is_length_truncated(Some("length")));
+ // Defensive: an engine that pads or uppercases the value must
+ // still classify, and every other stop reason must not.
+ assert!(is_length_truncated(Some(" length ")));
+ assert!(is_length_truncated(Some("LENGTH")));
+ assert!(!is_length_truncated(None));
+ assert!(!is_length_truncated(Some("stop")));
+ assert!(!is_length_truncated(Some("tool_calls")));
+ assert!(!is_length_truncated(Some("content_filter")));
+ assert!(!is_length_truncated(Some("")));
+ }
+
+ #[test]
+ fn response_without_finish_reason_or_usage_deserializes() {
+ // Engines that predate the field omit it; the shape must stay
+ // backwards compatible and classify as not truncated.
+ let body = r#"{"choices":[{"message":{"role":"assistant","content":"hi"}}],"model":"m"}"#;
+ let resp: OpenAiResponse = serde_json::from_str(body).expect("deserialises");
+ let finish_reason = resp.choices.first().and_then(|c| c.finish_reason.clone());
+ assert_eq!(finish_reason, None);
+ assert!(!is_length_truncated(finish_reason.as_deref()));
+ }
+
#[test]
fn build_request_does_not_cap_gpt5() {
// Reasoning models have a much larger output cap (128K+); leave
diff --git a/crates/ai-memory-llm/src/openai_compat.rs b/crates/ai-memory-llm/src/openai_compat.rs
index e2016fd0..03ed9208 100644
--- a/crates/ai-memory-llm/src/openai_compat.rs
+++ b/crates/ai-memory-llm/src/openai_compat.rs
@@ -15,7 +15,9 @@ use secrecy::SecretString;
use tracing::debug;
use crate::error::{LlmError, LlmResult};
-use crate::openai::{OpenAiProvider, RequestDialect, enforce_strict_object_schemas};
+use crate::openai::{
+ OpenAiProvider, RequestDialect, enforce_strict_object_schemas, is_length_truncated,
+};
use crate::provider::LlmProvider;
use crate::text::{suffix_within_bytes, truncate_with_ellipsis};
use crate::types::{ChatRequest, ChatResponse, LlmOperationId};
@@ -99,6 +101,21 @@ impl OpenAiCompatProvider {
self
}
+ /// Send `chat_template_kwargs: {"enable_thinking": false}` with every
+ /// request, for thinking-capable local engines (vLLM / SGLang serving
+ /// Qwen3-class models): the engine otherwise spends the output budget
+ /// on a reasoning pass before the structured payload and can truncate
+ /// it. The factory calls this with
+ /// `ProviderConfig::compat_disable_thinking`; `new` defaults it off so
+ /// existing vLLM / Ollama / LM Studio setups are unchanged. Forwarded
+ /// to the inner Chat Completions client, where the `Compat` dialect
+ /// gate keeps it off the wire for every other dialect.
+ #[must_use]
+ pub fn with_disable_thinking(mut self, enabled: bool) -> Self {
+ self.inner = self.inner.with_disable_thinking(enabled);
+ self
+ }
+
/// Repoint the wrapped [`OpenAiProvider`] at another base URL.
///
/// For a wrapper that constructs with a product default and lets the
@@ -282,10 +299,26 @@ impl OpenAiCompatProvider {
// Default (and strict fallback): most older local engines don't
// honour `response_format`. Ask for JSON and extract the first
// balanced `{…}` object from the text.
- let res = self
+ let (res, finish_reason) = self
.inner
- .complete_with_operation_id(request, operation_id)
+ .complete_with_operation_id_and_finish_reason(request, operation_id)
.await?;
+ // A `length` stop means the engine hit its output budget before
+ // the JSON could finish (the Qwen3-with-thinking-on case this
+ // guard exists for). Terminal and content-free: a tolerant retry
+ // would just re-truncate and double the token spend, and the old
+ // `unexpected-shape` / `serde` classes pointed at the wrong cause.
+ if is_length_truncated(finish_reason.as_deref()) {
+ return Err(LlmError::TruncatedResponse {
+ model: res.model,
+ completion_tokens: res.usage.as_ref().map(|u| u.output_tokens),
+ });
+ }
+ // No content at all (missing, empty, or whitespace-only) is a
+ // distinct terminal failure: nothing was produced to parse.
+ if res.text.trim().is_empty() {
+ return Err(LlmError::EmptyContent { model: res.model });
+ }
// Reasoning models (DeepSeek, Qwen, MiniMax M2.7, …) prepend
// `<think>…</think>` before the JSON. Strip those blocks (and any
// surrounding markdown fences) before trying to parse — otherwise
@@ -574,6 +607,18 @@ mod tests {
assert!(p.strict);
}
+ /// The thinking switch is opt-in at the wrapper too: `new` leaves it
+ /// off (existing vLLM / Ollama / LM Studio setups are unchanged) and
+ /// `with_disable_thinking` forwards it to the inner client.
+ #[test]
+ fn disable_thinking_defaults_off_and_reaches_the_inner_provider() {
+ let p = OpenAiCompatProvider::new("http://localhost:11434/v1", None, "qwen3.8-27b")
+ .expect("provider builds");
+ assert!(!p.inner.disable_thinking());
+ let p = p.with_disable_thinking(true);
+ assert!(p.inner.disable_thinking());
+ }
+
#[test]
fn timeout_override_reaches_the_inner_provider() {
let p = OpenAiCompatProvider::new("http://localhost:11434/v1", None, "mistral-nemo")
diff --git a/crates/ai-memory-llm/src/opencode.rs b/crates/ai-memory-llm/src/opencode.rs
index cb8aa6f4..cfc77ca1 100644
--- a/crates/ai-memory-llm/src/opencode.rs
+++ b/crates/ai-memory-llm/src/opencode.rs
@@ -805,6 +805,7 @@ mod tests {
),
base_url: Some(base),
compat_strict: false,
+ compat_disable_thinking: false,
request_timeout_secs: 5,
reasoning_effort: Some(ReasoningEffort::High),
extra_headers: ExtraHeaders::parse(["x-test: routed"]).unwrap(),
diff --git a/crates/ai-memory-llm/tests/suite/extra_headers_on_the_wire.rs b/crates/ai-memory-llm/tests/suite/extra_headers_on_the_wire.rs
index 3df23fb1..b78c700b 100644
--- a/crates/ai-memory-llm/tests/suite/extra_headers_on_the_wire.rs
+++ b/crates/ai-memory-llm/tests/suite/extra_headers_on_the_wire.rs
@@ -52,6 +52,7 @@ async fn captured_request(headers: ExtraHeaders) -> Request {
auth: ProviderAuth::optional_api_key_from_env("LLM_API_KEY", None),
base_url: Some(server.uri()),
compat_strict: false,
+ compat_disable_thinking: false,
request_timeout_secs: 30,
reasoning_effort: None,
extra_headers: headers,
@@ -153,6 +154,7 @@ async fn openrouter_app_headers_reach_the_provider_request() {
auth: ProviderAuth::optional_api_key_from_env("LLM_API_KEY", None),
base_url: Some(base_url),
compat_strict: false,
+ compat_disable_thinking: false,
request_timeout_secs: 30,
reasoning_effort: None,
extra_headers: ExtraHeaders::default(),
@@ -199,6 +201,7 @@ async fn an_operator_base_url_redirects_the_opencode_provider() {
),
base_url: Some(server.uri()),
compat_strict: false,
+ compat_disable_thinking: false,
request_timeout_secs: 30,
reasoning_effort: None,
extra_headers: ExtraHeaders::default(),
@@ -250,6 +253,7 @@ async fn an_operator_session_header_beats_the_per_operation_default() {
),
base_url: Some(server.uri()),
compat_strict: false,
+ compat_disable_thinking: false,
request_timeout_secs: 30,
reasoning_effort: None,
extra_headers: ExtraHeaders::parse([
diff --git a/crates/ai-memory-llm/tests/suite/mod.rs b/crates/ai-memory-llm/tests/suite/mod.rs
index b034c653..57a918d0 100644
--- a/crates/ai-memory-llm/tests/suite/mod.rs
+++ b/crates/ai-memory-llm/tests/suite/mod.rs
@@ -7,4 +7,5 @@ mod copilot_provider;
mod extra_headers_on_the_wire;
mod fallback_provider;
mod openai_compat_embedder;
+mod openai_compat_guardrails;
mod openai_compat_strict;
diff --git a/crates/ai-memory-llm/tests/suite/openai_compat_guardrails.rs b/crates/ai-memory-llm/tests/suite/openai_compat_guardrails.rs
new file mode 100644
index 00000000..f1cccfc5
--- /dev/null
+++ b/crates/ai-memory-llm/tests/suite/openai_compat_guardrails.rs
@@ -0,0 +1,325 @@
+//! Integration tests for the openai-compat guardrails, driving the real
+//! HTTP client against an in-process wiremock server that synthesises
+//! the engine responses (a vLLM-hosted Qwen3-class thinking model that
+//! truncates the structured payload at the output budget).
+//!
+//! Two behaviours are proven end-to-end on the wire — no production
+//! endpoint, no real key:
+//!
+//! 1. The opt-in `chat_template_kwargs: {"enable_thinking": false}`
+//! request payload is ABSENT by default and present verbatim when
+//! opted in, on the `openai-compat` dialect only.
+//! 2. A structured response with `finish_reason = "length"` and a
+//! response with no usable `message.content` are terminal errors with
+//! clear classes (`truncated-response`, `empty-content`): no retry /
+//! tolerant fallback, no response content in the error message, and
+//! intact JSON responses still parse successfully.
+
+use ai_memory_llm::types::ChatRequest;
+use ai_memory_llm::{LlmError, LlmProvider, OpenAiCompatProvider, OpenAiProvider};
+use secrecy::SecretString;
+use serde_json::json;
+use wiremock::matchers::{method, path};
+use wiremock::{Mock, MockServer, ResponseTemplate};
+
+const QWEN_MODEL: &str = "applianceai01/qwen3.8-27b";
+
+/// Truncated mid-value: exactly what a `length` stop leaves behind.
+/// Deliberately unbalanced so no extractor could "recover" an object.
+const TRUNCATED_JSON: &str = "{ \"findings\": [\"kept the\" ";
+
+fn tiny_request() -> ChatRequest {
+ ChatRequest::user_prompt("emit JSON: { \"findings\": [] }")
+}
+
+fn tiny_schema() -> serde_json::Value {
+ json!({
+ "type": "object",
+ "properties": {
+ "findings": { "type": "array", "items": { "type": "string" } }
+ },
+ "required": ["findings"]
+ })
+}
+
+/// Synthesise an OpenAI-wire chat completion body. `content = None`
+/// omits the key entirely (an engine that returns no content block).
+fn qwen_body(
+ content: Option<&str>,
+ finish_reason: &str,
+ completion_tokens: u32,
+) -> serde_json::Value {
+ let mut message = json!({ "role": "assistant" });
+ if let Some(content) = content {
+ message["content"] = json!(content);
+ }
+ json!({
+ "id": "chatcmpl-qwen",
+ "object": "chat.completion",
+ "created": 0,
+ "model": QWEN_MODEL,
+ "choices": [{
+ "index": 0,
+ "message": message,
+ "finish_reason": finish_reason
+ }],
+ "usage": {
+ "prompt_tokens": 12,
+ "completion_tokens": completion_tokens,
+ "total_tokens": 12 + completion_tokens
+ }
+ })
+}
+
+fn body_mock(body: serde_json::Value) -> Mock {
+ Mock::given(method("POST"))
+ .and(path("/v1/chat/completions"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(body))
+}
+
+fn tolerant_provider(base_url: String) -> OpenAiCompatProvider {
+ OpenAiCompatProvider::new(base_url, None, QWEN_MODEL).expect("provider builds")
+}
+
+/// Default request shape is byte-stable: no `chat_template_kwargs` key
+/// at all (not even `false`), so unconfigured vLLM / Ollama / LM Studio
+/// setups see exactly what they saw before.
+#[tokio::test]
+async fn request_omits_chat_template_kwargs_by_default() {
+ let server = MockServer::start().await;
+ body_mock(qwen_body(Some("prose"), "stop", 5))
+ .mount(&server)
+ .await;
+
+ let provider = tolerant_provider(server.uri());
+ provider
+ .complete(tiny_request())
+ .await
+ .expect("plain completion succeeds");
+
+ let requests = server.received_requests().await.expect("requests recorded");
+ assert_eq!(requests.len(), 1);
+ let body: serde_json::Value =
+ serde_json::from_slice(&requests[0].body).expect("request body is JSON");
+ assert!(
+ body.get("chat_template_kwargs").is_none(),
+ "no chat_template_kwargs without the opt-in, got {body}"
+ );
+}
+
+/// Opted in, the exact vLLM / SGLang payload is on the wire.
+#[tokio::test]
+async fn request_sends_enable_thinking_false_when_opted_in() {
+ let server = MockServer::start().await;
+ body_mock(qwen_body(Some("prose"), "stop", 5))
+ .mount(&server)
+ .await;
+
+ let provider = tolerant_provider(server.uri()).with_disable_thinking(true);
+ provider
+ .complete(tiny_request())
+ .await
+ .expect("plain completion succeeds");
+
+ let requests = server.received_requests().await.expect("requests recorded");
+ assert_eq!(requests.len(), 1);
+ let body: serde_json::Value =
+ serde_json::from_slice(&requests[0].body).expect("request body is JSON");
+ assert_eq!(
+ body["chat_template_kwargs"],
+ json!({ "enable_thinking": false }),
+ "the opt-in payload must be sent verbatim, got {body}"
+ );
+}
+
+/// Tolerant path: a `length`-truncated structured response is a
+/// terminal `truncated-response` error — one upstream call (no retry),
+/// the provider-reported completion token count is carried, and the
+/// error message carries no response content.
+#[tokio::test]
+async fn tolerant_truncated_response_is_terminal_truncated_response() {
+ let server = MockServer::start().await;
+ body_mock(qwen_body(Some(TRUNCATED_JSON), "length", 4096))
+ .mount(&server)
+ .await;
+
+ let provider = tolerant_provider(server.uri()).with_disable_thinking(true);
+ let err = provider
+ .complete_structured_raw(tiny_request(), tiny_schema())
+ .await
+ .expect_err("a length stop must not parse");
+
+ match &err {
+ LlmError::TruncatedResponse {
+ model,
+ completion_tokens,
+ } => {
+ assert_eq!(model, QWEN_MODEL);
+ assert_eq!(*completion_tokens, Some(4096));
+ }
+ other => panic!("expected TruncatedResponse, got {other:?}"),
+ }
+ assert_eq!(err.class(), "truncated-response");
+ assert!(!err.is_transient(), "a length stop must not be retried");
+ let rendered = err.to_string();
+ assert!(
+ !rendered.contains("kept the"),
+ "the error message must not carry response content: {rendered}"
+ );
+ let requests = server.received_requests().await.expect("requests recorded");
+ assert_eq!(
+ requests.len(),
+ 1,
+ "a length stop must not trigger a second upstream call"
+ );
+}
+
+/// Strict path: the same `length` stop must NOT fall through to the
+/// tolerant parser — that would be a second HTTP call re-truncating the
+/// same output and doubling the spend.
+#[tokio::test]
+async fn strict_truncated_response_is_terminal_without_fallback() {
+ let server = MockServer::start().await;
+ body_mock(qwen_body(Some(TRUNCATED_JSON), "length", 4096))
+ .mount(&server)
+ .await;
+
+ let provider = tolerant_provider(server.uri()).with_strict(true);
+ let err = provider
+ .complete_structured_raw(tiny_request(), tiny_schema())
+ .await
+ .expect_err("a length stop must not fall back to the tolerant parser");
+
+ assert_eq!(err.class(), "truncated-response");
+ assert!(!err.is_transient());
+ let requests = server.received_requests().await.expect("requests recorded");
+ assert_eq!(
+ requests.len(),
+ 1,
+ "strict length stop must hit upstream exactly once (no tolerant fallback)"
+ );
+}
+
+/// The guard lives in the shared OpenAI-wire structured path, so the
+/// `Official` dialect (api.openai.com shape) classifies the same way.
+#[tokio::test]
+async fn official_truncated_structured_response_is_terminal() {
+ let server = MockServer::start().await;
+ body_mock(qwen_body(Some(TRUNCATED_JSON), "length", 4096))
+ .mount(&server)
+ .await;
+
+ let provider = OpenAiProvider::new(SecretString::new("dummy".into()), QWEN_MODEL)
+ .expect("provider builds")
+ .with_base_url(server.uri());
+ let err = provider
+ .complete_structured_raw(tiny_request(), tiny_schema())
+ .await
+ .expect_err("a length stop must not parse");
+
+ assert_eq!(err.class(), "truncated-response");
+ assert!(!err.is_transient());
+ let requests = server.received_requests().await.expect("requests recorded");
+ assert_eq!(requests.len(), 1);
+}
+
+/// Empty content is one class with hostile variants: an empty string,
+/// whitespace only, and a `content` key missing entirely. Each must be
+/// the terminal `empty-content` error — distinct from `serde` /
+/// `unexpected-shape` — with a single upstream call.
+#[tokio::test]
+async fn tolerant_empty_content_variants_are_terminal_empty_content() {
+ for (label, content) in [
+ ("empty string", Some("")),
+ ("whitespace only", Some(" \n\t ")),
+ ("missing content key", None),
+ ] {
+ let server = MockServer::start().await;
+ body_mock(qwen_body(content, "stop", 0))
+ .mount(&server)
+ .await;
+
+ let provider = tolerant_provider(server.uri());
+ let err = provider
+ .complete_structured_raw(tiny_request(), tiny_schema())
+ .await
+ .expect_err("empty content must surface a typed error");
+
+ match &err {
+ LlmError::EmptyContent { model } => assert_eq!(model, QWEN_MODEL),
+ other => panic!("{label}: expected EmptyContent, got {other:?}"),
+ }
+ assert_eq!(err.class(), "empty-content");
+ assert!(!err.is_transient(), "{label} must not be retried");
+ let requests = server.received_requests().await.expect("requests recorded");
+ assert_eq!(requests.len(), 1, "{label}: exactly one upstream call");
+ }
+}
+
+/// Strict path, empty content: the tolerant fallback must NOT run —
+/// there is nothing a second call can conjure.
+#[tokio::test]
+async fn strict_empty_content_is_terminal_without_fallback() {
+ let server = MockServer::start().await;
+ body_mock(qwen_body(Some(""), "stop", 0))
+ .mount(&server)
+ .await;
+
+ let provider = tolerant_provider(server.uri()).with_strict(true);
+ let err = provider
+ .complete_structured_raw(tiny_request(), tiny_schema())
+ .await
+ .expect_err("empty content must not fall back");
+ assert_eq!(err.class(), "empty-content");
+ let requests = server.received_requests().await.expect("requests recorded");
+ assert_eq!(
+ requests.len(),
+ 1,
+ "strict empty content must hit upstream exactly once (no tolerant fallback)"
+ );
+}
+
+/// Control: an intact response — including a reasoning model's
+/// think-block prefix with a complete JSON object after it, the
+/// normal Qwen flow — still parses and succeeds.
+#[tokio::test]
+async fn tolerant_intact_json_response_succeeds() {
+ let server = MockServer::start().await;
+ // The reasoning tags are built from escapes so this source file
+ // never contains a literal tag sequence (editing tooling mangles
+ // one in transit).
+ let open = "\u{3C}think";
+ let close = "\u{3C}/think\u{3E}";
+ let content =
+ format!("{open}Let me emit the requested JSON.{close}\n{{\"findings\": [\"kept the\"]}}");
+ body_mock(qwen_body(Some(content.as_str()), "stop", 321))
+ .mount(&server)
+ .await;
+
+ let provider = tolerant_provider(server.uri()).with_disable_thinking(true);
+ let value = provider
+ .complete_structured_raw(tiny_request(), tiny_schema())
+ .await
+ .expect("an intact structured response must parse");
+ assert_eq!(value, json!({ "findings": ["kept the"] }));
+}
+
+/// Plain (non-structured) completions keep working when the engine
+/// stops at the budget: a prose answer cut at `max_tokens` is a normal
+/// outcome, not an error.
+#[tokio::test]
+async fn plain_complete_with_length_finish_reason_still_succeeds() {
+ let server = MockServer::start().await;
+ let content = "partial answer that was cut at the token budget";
+ body_mock(qwen_body(Some(content), "length", 4096))
+ .mount(&server)
+ .await;
+
+ let provider = tolerant_provider(server.uri());
+ let response = provider
+ .complete(tiny_request())
+ .await
+ .expect("a prose completion cut at the budget is a normal outcome");
+ assert_eq!(response.text, content);
+ assert_eq!(response.usage.map(|u| u.output_tokens), Some(4096));
+}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 65a664af..85962bc0 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -1069,6 +1069,12 @@ LLM_BASE_URL the unprefixed cross-tool convention, accepted for
an operator's leftover Ollama URL must not silently
rewrite every Gemini request into a 404
AI_MEMORY_LLM_COMPAT_STRICT true by default; false disables response_format=json_schema
+AI_MEMORY_LLM_COMPAT_DISABLE_THINKING openai-compat only, false by default; true sends
+ chat_template_kwargs:{"enable_thinking":false} on every
+ request (vLLM / SGLang thinking models). A structured
+ response that stops with finish_reason=length, or a 2xx
+ with empty message.content, is a terminal error
+ (classes truncated-response / empty-content)
AI_MEMORY_LLM_TIMEOUT_SECS per-request timeout for chat providers; 300 by default
AI_MEMORY_LLM_REASONING_EFFORT optional reasoning/thinking effort
(none|minimal|low|medium|high|xhigh|max|ultra|persistent)
diff --git a/docs/deploy.md b/docs/deploy.md
index 464b03e9..d6ad5b7a 100644
--- a/docs/deploy.md
+++ b/docs/deploy.md
@@ -188,7 +188,12 @@ alternatives:
> Claude with extended thinking, GPT-o3, Gemini "thinking" variants) — they burn
> token budget on internal reasoning before emitting output and hang or emit empty
> responses with the strict-JSON consolidation prompt. If you must use one, turn
-> reasoning off.
+> reasoning off. For a vLLM / SGLang-hosted Qwen3-class model the local equivalent
+> is `AI_MEMORY_LLM_COMPAT_DISABLE_THINKING=true` (it sends
+> `chat_template_kwargs: {"enable_thinking": false}` on every openai-compat
+> request); if the engine still truncates the structured payload or returns empty
+> content, the job now fails fast with a terminal `truncated-response` /
+> `empty-content` error instead of retrying.
ai-memory's hosted OpenAI-family providers use `json_schema` strict mode for
structured output. The OpenAI provider normalizes schemars output into
diff --git a/docs/llm-providers.md b/docs/llm-providers.md
index 21d98e7c..58ae2960 100644
--- a/docs/llm-providers.md
+++ b/docs/llm-providers.md
@@ -342,6 +342,22 @@ also set `COPILOT_GITHUB_TOKEN`, `GH_TOKEN`, or `GITHUB_TOKEN` on the server.
> endpoint explicitly rejects that field or returns a malformed shape. Set
> `AI_MEMORY_LLM_COMPAT_STRICT=false` only for an incompatible endpoint.
+> [!TIP]
+> **Thinking-capable local engines (vLLM / SGLang serving Qwen3-class
+> models).** Such engines spend the output budget on a reasoning pass before
+> the structured payload and can truncate the JSON mid-object
+> (`finish_reason = "length"`). Set
+> `AI_MEMORY_LLM_COMPAT_DISABLE_THINKING=true` to send
+> `chat_template_kwargs: {"enable_thinking": false}` on every openai-compat
+> request so the engine spends the budget on the payload instead. The knob is
+> opt-in, openai-compat only, and off by default — existing vLLM / Ollama /
+> LM Studio setups are unchanged unless it is set, and every other provider
+> ignores it. When the engine still truncates a structured response, or
+> returns HTTP 2xx with an empty `message.content`, the call now fails fast
+> with the terminal errors `truncated-response` / `empty-content` — no
+> retry, no second HTTP call, and the error text carries no response
+> content.
+
For small-context local models, configure both consolidation limits. The input
target accounts for the complete rendered prompt, including bounded slot and
current-page context plus the structured-output schema; the output limit is
diff --git a/evals/src/ab.rs b/evals/src/ab.rs
index f2ee5cd1..9b8ae285 100644
--- a/evals/src/ab.rs
+++ b/evals/src/ab.rs
@@ -364,6 +364,9 @@ impl From<ResolvedConfig> for ProviderConfig {
// Match the product default so provider comparisons exercise the
// same schema-constrained path operators receive.
compat_strict: true,
+ // Comparisons must not differ by engine-side thinking behaviour;
+ // keep the product default (off) for every candidate.
+ compat_disable_thinking: false,
request_timeout_secs: ai_memory_llm::DEFAULT_REQUEST_TIMEOUT_SECS,
// The A/B harness compares consolidation quality; reasoning
// effort stays at each model's own default unless a future
diff --git a/evals/src/retrieval/qa.rs b/evals/src/retrieval/qa.rs
index 3b575df0..47bc9523 100644
--- a/evals/src/retrieval/qa.rs
+++ b/evals/src/retrieval/qa.rs
@@ -375,6 +375,9 @@ fn build_llm_provider(
auth,
base_url: base_url.map(str::to_string),
compat_strict: true,
+ // Comparisons must not differ by engine-side thinking behaviour;
+ // keep the product default (off) for every candidate.
+ compat_disable_thinking: false,
request_timeout_secs: ai_memory_llm::DEFAULT_REQUEST_TIMEOUT_SECS,
reasoning_effort: None,
extra_headers: ai_memory_llm::ExtraHeaders::default(),