Skip to content

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

Rust

feat(openai-compat): opt-in strict mode via response_format

Bruno Marianoec0cb13980e8
diff --git a/README.md b/README.md
index 9fadf264..2cdc2435 100644
--- a/README.md
+++ b/README.md
@@ -429,6 +429,14 @@ also set `COPILOT_GITHUB_TOKEN`, `GH_TOKEN`, or `GITHUB_TOKEN` on the server.
> model is plenty and is much easier on subscription rate limits. Save the
> high-effort thinking models for your coding agent.
+> [!TIP]
+> **On a local engine (Ollama, vLLM, LM Studio, llama.cpp) with
+> `openai-compat`, if consolidation fails on large sessions** with
+> `did not contain a JSON object` or `serde: unknown variant`, set
+> `AI_MEMORY_LLM_COMPAT_STRICT=true`. It sends `response_format=json_schema`
+> (strict) so the engine constrains output to the schema, with a fallback to
+> the default tolerant parser when the engine ignores it. Off by default.
+
Embeddings are optional and separate from the LLM provider. Set
`AI_MEMORY_EMBEDDING_PROVIDER=openai`, `voyage`, `google`, or `gemini` when
you want vector reranking in addition to FTS5 + graph-neighbor retrieval.
diff --git a/crates/ai-memory-cli/src/commands/llm_test.rs b/crates/ai-memory-cli/src/commands/llm_test.rs
index bc79396a..3d03b6e2 100644
--- a/crates/ai-memory-cli/src/commands/llm_test.rs
+++ b/crates/ai-memory-cli/src/commands/llm_test.rs
@@ -23,6 +23,7 @@ pub async fn run(config: &Config, args: LlmTestArgs) -> Result<()> {
model: args.model,
auth: config.provider_auth(provider, api_key_override),
base_url: args.base_url.or_else(|| config.llm_test_base_url()),
+ compat_strict: config.llm_compat_strict,
};
let client = build_provider(provider_config).context("building LLM provider")?;
info!(
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index c168854c..389b890e 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -59,6 +59,16 @@ pub struct Config {
pub llm_model: Option<String>,
/// Optional LLM base URL override.
pub llm_base_url: Option<String>,
+ /// Opt-in: send `response_format=json_schema` (strict) to the
+ /// `openai-compat` provider instead of asking for prose JSON and
+ /// extracting the first balanced object. Off by default — the tolerant
+ /// parser stays the default for older local engines that ignore
+ /// `response_format`. Modern engines (recent Ollama, vLLM, LM Studio,
+ /// llama.cpp) honour structured output; this lets the operator opt in.
+ /// When the strict call fails, the provider falls back to the tolerant
+ /// parser, so enabling it never regresses below the default. Set with
+ /// `AI_MEMORY_LLM_COMPAT_STRICT=true`.
+ pub llm_compat_strict: bool,
/// Opt-in: run LLM consolidation on SessionEnd (in addition to the
/// always-written heuristic session page), when an LLM provider is
/// configured. Off by default — SessionEnd stays cheap and
@@ -275,6 +285,7 @@ impl Default for Config {
llm_provider: None,
llm_model: None,
llm_base_url: None,
+ llm_compat_strict: false,
consolidate_on_session_end: false,
embedding_provider: None,
embedding_model: None,
@@ -446,6 +457,7 @@ impl Config {
.llm_base_url
.clone()
.or_else(|| self.runtime_env.llm_base_url.clone()),
+ compat_strict: self.llm_compat_strict,
}))
}
diff --git a/crates/ai-memory-llm/src/factory.rs b/crates/ai-memory-llm/src/factory.rs
index cb716270..56720a88 100644
--- a/crates/ai-memory-llm/src/factory.rs
+++ b/crates/ai-memory-llm/src/factory.rs
@@ -87,6 +87,11 @@ pub struct ProviderConfig {
pub auth: ProviderAuth,
/// Base URL override (required for OpenAI-compat).
pub base_url: Option<String>,
+ /// Opt-in strict mode for the `openai-compat` provider: send
+ /// `response_format=json_schema` instead of the tolerant prose-JSON
+ /// parser. Ignored by every other provider. Sourced once from
+ /// `AI_MEMORY_LLM_COMPAT_STRICT` by `Config::load`.
+ pub compat_strict: bool,
}
/// Embedding providers available to ai-memory.
@@ -200,11 +205,10 @@ pub fn build_provider(config: ProviderConfig) -> LlmResult<Arc<dyn LlmProvider>>
let base = config
.base_url
.ok_or_else(|| LlmError::NotConfigured("LLM_BASE_URL".into()))?;
- Ok(Arc::new(OpenAiCompatProvider::new(
- base,
- config.auth.optional_api_key(),
- config.model,
- )?))
+ Ok(Arc::new(
+ OpenAiCompatProvider::new(base, config.auth.optional_api_key(), config.model)?
+ .with_strict(config.compat_strict),
+ ))
}
ProviderChoice::OpenAiOAuth => {
let path = config.auth.require_openai_oauth_token_file()?.to_path_buf();
@@ -276,6 +280,7 @@ mod tests {
model: "gpt-4o-mini".into(),
auth: ProviderAuth::required_api_key_from_env("OPENAI_API_KEY", None),
base_url: None,
+ compat_strict: false,
};
let err = match build_provider(cfg) {
diff --git a/crates/ai-memory-llm/src/openai_compat.rs b/crates/ai-memory-llm/src/openai_compat.rs
index 73c429c2..cad1f75e 100644
--- a/crates/ai-memory-llm/src/openai_compat.rs
+++ b/crates/ai-memory-llm/src/openai_compat.rs
@@ -14,7 +14,7 @@ use secrecy::SecretString;
use tracing::debug;
use crate::error::{LlmError, LlmResult};
-use crate::openai::{OpenAiProvider, RequestDialect};
+use crate::openai::{OpenAiProvider, RequestDialect, enforce_strict_object_schemas};
use crate::provider::LlmProvider;
use crate::text::{suffix_within_bytes, truncate_with_ellipsis};
use crate::types::{ChatRequest, ChatResponse};
@@ -56,6 +56,10 @@ pub(crate) fn strip_reasoning_blocks(s: &str) -> String {
pub struct OpenAiCompatProvider {
inner: OpenAiProvider,
name_tag: &'static str,
+ /// When `true`, structured output sends a strict `response_format`
+ /// instead of the tolerant parser. Set by the factory from
+ /// `ProviderConfig::compat_strict` (sourced once by `Config::load`).
+ strict: bool,
}
impl OpenAiCompatProvider {
@@ -81,8 +85,18 @@ impl OpenAiCompatProvider {
Ok(Self {
inner,
name_tag: "openai-compat",
+ strict: false,
})
}
+
+ /// Set strict mode. The factory calls this with
+ /// `ProviderConfig::compat_strict`; `new` defaults it off so the
+ /// tolerant parser stays the zero-config behaviour.
+ #[must_use]
+ pub fn with_strict(mut self, strict: bool) -> Self {
+ self.strict = strict;
+ self
+ }
}
#[async_trait]
@@ -102,11 +116,40 @@ impl LlmProvider for OpenAiCompatProvider {
async fn complete_structured_raw(
&self,
request: ChatRequest,
- _schema: serde_json::Value,
+ schema: serde_json::Value,
) -> LlmResult<serde_json::Value> {
- // Most local engines don't honour `response_format`. We
- // ask the model to emit a JSON object and fall back to
- // extracting the first balanced `{…}` from the text.
+ // Strict mode (opt-in; see `strict` field): modern local engines
+ // honour `response_format=json_schema`. Normalise the schema
+ // to the strict subset (additionalProperties:false, full required, no
+ // oneOf / no $ref siblings) — the same rewrite the Official dialect
+ // applies — and delegate to the inner provider, which sends the
+ // response_format. The dialect stays Compat, so the api.openai.com
+ // token/temperature quirks do NOT leak into the local engine.
+ //
+ // If the strict call fails (engine that ignores the schema, truncated
+ // JSON, etc.) we fall through to the tolerant parser below instead of
+ // propagating the error — so enabling the flag never regresses below
+ // the default behaviour.
+ if self.strict {
+ let mut strict_schema = schema.clone();
+ enforce_strict_object_schemas(&mut strict_schema);
+ match self
+ .inner
+ .complete_structured_raw(request.clone(), strict_schema)
+ .await
+ {
+ Ok(v) if v.is_object() => return Ok(v),
+ Ok(_) => {
+ debug!("compat strict: non-object response, falling back to tolerant parser");
+ }
+ Err(err) => {
+ debug!(error = %err, "compat strict failed, falling back to tolerant parser");
+ }
+ }
+ }
+ // 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.inner.complete(request).await?;
// Reasoning models (DeepSeek, Qwen, MiniMax M2.7, …) prepend
// `<think>…</think>` before the JSON. Strip those blocks (and any
@@ -186,6 +229,17 @@ fn first_json_object(s: &str) -> Option<&str> {
mod tests {
use super::*;
+ /// `new` defaults strict off; `with_strict` is the only way to turn it
+ /// on, mirroring how the factory threads `ProviderConfig::compat_strict`.
+ #[test]
+ fn strict_defaults_off_and_can_be_overridden() {
+ let p = OpenAiCompatProvider::new("http://localhost:11434/v1", None, "mistral-nemo")
+ .expect("provider builds");
+ assert!(!p.strict);
+ let p = p.with_strict(true);
+ assert!(p.strict);
+ }
+
#[test]
fn first_json_object_finds_balanced_object() {
assert_eq!(first_json_object("noise {\"k\":1} more"), Some("{\"k\":1}"));
diff --git a/evals/src/main.rs b/evals/src/main.rs
index 1c59799d..144db9ac 100644
--- a/evals/src/main.rs
+++ b/evals/src/main.rs
@@ -368,6 +368,9 @@ impl From<ResolvedConfig> for ProviderConfig {
model: r.model,
auth: r.auth,
base_url: r.base_url,
+ // The eval harness benchmarks the default tolerant path; strict
+ // mode is an operator opt-in not modeled by these comparisons.
+ compat_strict: false,
}
}
}