Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
llm: tolerant base-URL + cold-start timeouts + memory_query BM25 fallback
AkitaOnRails8ebf617f53d7
diff --git a/crates/ai-memory-llm/src/anthropic.rs b/crates/ai-memory-llm/src/anthropic.rsindex b7f96257..953304a4 100644--- a/crates/ai-memory-llm/src/anthropic.rs+++ b/crates/ai-memory-llm/src/anthropic.rs@@ -32,8 +32,11 @@ impl AnthropicProvider {/// Returns a `reqwest::Error` if the underlying HTTP client cannot/// be built.pub fn new(api_key: SecretString, model: impl Into<String>) -> LlmResult<Self> {+ // 300s matches the OpenAI/openai-compat client — same reason:+ // first request after a model swap on a local inference server+ // (Ollama, llama-swap, vLLM) can take 30-90s of cold-load.let client = reqwest::Client::builder()- .timeout(Duration::from_secs(120))+ .timeout(Duration::from_secs(300)).build()?;Ok(Self {client,diff --git a/crates/ai-memory-llm/src/embedding.rs b/crates/ai-memory-llm/src/embedding.rsindex f8aee7aa..2e9df444 100644--- a/crates/ai-memory-llm/src/embedding.rs+++ b/crates/ai-memory-llm/src/embedding.rs@@ -19,6 +19,7 @@ use serde::{Deserialize, Serialize};use tracing::debug;use crate::error::{LlmError, LlmResult};+use crate::openai::normalize_openai_base;/// Provider-agnostic embedding API.///@@ -57,8 +58,13 @@ impl OpenAiEmbedder {/// Propagates any `reqwest::Error` thrown while building the HTTP/// client.pub fn new(api_key: SecretString, model: impl Into<String>, dim: u32) -> LlmResult<Self> {+ // 120s tolerates a cold-load of the embedding model on Ollama+ // (small model, but still up to ~30s on first request after+ // unload). Subsequent requests with OLLAMA_KEEP_ALIVE warm are+ // sub-second. When the embedder still fails, memory_query+ // degrades gracefully to BM25-only (see server.rs).let client = reqwest::Client::builder()- .timeout(Duration::from_secs(60))+ .timeout(Duration::from_secs(120)).build()?;Ok(Self {client,@@ -108,7 +114,7 @@ impl Embedder for OpenAiEmbedder {}async fn embed(&self, text: &str) -> LlmResult<Vec<f32>> {- let url = format!("{}/v1/embeddings", self.base_url.trim_end_matches('/'));+ let url = format!("{}/v1/embeddings", normalize_openai_base(&self.base_url));debug!(url, model = %self.model, "POST openai/embeddings");let req = OpenAiEmbeddingRequest {input: text,@@ -160,8 +166,13 @@ impl VoyageEmbedder {/// # Errors/// Propagates the HTTP client construction error.pub fn new(api_key: SecretString, model: impl Into<String>, dim: u32) -> LlmResult<Self> {+ // 120s tolerates a cold-load of the embedding model on Ollama+ // (small model, but still up to ~30s on first request after+ // unload). Subsequent requests with OLLAMA_KEEP_ALIVE warm are+ // sub-second. When the embedder still fails, memory_query+ // degrades gracefully to BM25-only (see server.rs).let client = reqwest::Client::builder()- .timeout(Duration::from_secs(60))+ .timeout(Duration::from_secs(120)).build()?;Ok(Self {client,@@ -211,7 +222,7 @@ impl Embedder for VoyageEmbedder {}async fn embed(&self, text: &str) -> LlmResult<Vec<f32>> {- let url = format!("{}/v1/embeddings", self.base_url.trim_end_matches('/'));+ let url = format!("{}/v1/embeddings", normalize_openai_base(&self.base_url));let req = VoyageRequest {input: [text],model: &self.model,diff --git a/crates/ai-memory-llm/src/openai.rs b/crates/ai-memory-llm/src/openai.rsindex 2c05569e..c92341a7 100644--- a/crates/ai-memory-llm/src/openai.rs+++ b/crates/ai-memory-llm/src/openai.rs@@ -15,6 +15,21 @@ use crate::types::{ChatRequest, ChatResponse, Role, Usage};/// Default OpenAI API base.pub const DEFAULT_BASE_URL: &str = "https://api.openai.com";+/// Trim a trailing `/` and one optional `/v1` segment off an+/// OpenAI-style base URL so the caller can append `/v1/<endpoint>`+/// safely. Tolerates both conventions found in the wild:+/// * `https://api.openai.com` (OpenAI's own docs)+/// * `https://openrouter.ai/api/v1` (OpenRouter's docs)+/// * `http://localhost:11434/v1` (Ollama's openai-compat path)+///+/// Without this, half the providers produce `…/v1/v1/…` 404s the+/// first time consolidation runs.+#[must_use]+pub fn normalize_openai_base(url: &str) -> String {+ let s = url.trim_end_matches('/');+ s.strip_suffix("/v1").unwrap_or(s).to_string()+}+/// OpenAI Chat Completions-backed provider.pub struct OpenAiProvider {client: reqwest::Client,@@ -29,8 +44,12 @@ impl OpenAiProvider {/// # Errors/// Returns a `reqwest::Error` if the HTTP client cannot be built.pub fn new(api_key: SecretString, model: impl Into<String>) -> LlmResult<Self> {+ // 300s tolerates Ollama / llama-swap cold-loading a 30B+ model+ // from disk on first request. Once OLLAMA_KEEP_ALIVE keeps it+ // warm, subsequent requests return in seconds — but the first+ // one after the model unloaded needs the headroom.let client = reqwest::Client::builder()- .timeout(Duration::from_secs(120))+ .timeout(Duration::from_secs(300)).build()?;Ok(Self {client,@@ -194,7 +213,7 @@ impl OpenAiProvider {async fn post<B: Serialize>(&self, body: &B) -> LlmResult<OpenAiResponse> {let url = format!("{}/v1/chat/completions",- self.base_url.trim_end_matches('/')+ normalize_openai_base(&self.base_url));debug!(url, "POST openai");let resp = self@@ -224,3 +243,28 @@ fn truncate(s: &str, n: usize) -> String {format!("{}…", &s[..n])}}++#[cfg(test)]+mod tests {+ use super::normalize_openai_base;++ #[test]+ fn normalize_strips_trailing_slash_and_v1() {+ // The three conventions found in the wild.+ assert_eq!(normalize_openai_base("https://api.openai.com"),+ "https://api.openai.com");+ assert_eq!(normalize_openai_base("https://api.openai.com/"),+ "https://api.openai.com");+ // OpenRouter's docs / ai-memory's OpenRouter env entry.+ assert_eq!(normalize_openai_base("https://openrouter.ai/api/v1"),+ "https://openrouter.ai/api");+ // Ollama's openai-compat path (`docker logs` shows it+ // canonically advertised this way).+ assert_eq!(normalize_openai_base("http://localhost:11434/v1"),+ "http://localhost:11434");+ // Don't accidentally strip a `/v1` that's part of a longer+ // segment (e.g. `/v123/`).+ assert_eq!(normalize_openai_base("https://example.com/v123"),+ "https://example.com/v123");+ }+}diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 50cb14c3..2483389c 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -248,24 +248,36 @@ impl AiMemoryServer {Parameters(args): Parameters<QueryArgs>,) -> Result<CallToolResult, McpError> {let limit = args.limit.unwrap_or(self.default_limit).clamp(1, 100);+ // Hybrid path: try to embed the query; if it fails (provider+ // outage, cold-start timeout, billing, etc.) degrade to BM25+ // instead of erroring the whole query — losing semantic+ // re-ranking is acceptable, denying the user any search isn't.let hits = if let Some(embedder) = &self.embedder {- // Hybrid path: embed the query, RRF-fuse with FTS5.- let qv = embedder- .embed(&args.query)- .await- .map_err(|e| McpError::internal_error(e.to_string(), None))?;- self.reader- .hybrid_search(- self.workspace_id,- self.project_id,- args.query,- Some(qv),- embedder.provider().to_string(),- embedder.model().to_string(),- embedder.dim(),- limit,- )- .await+ match embedder.embed(&args.query).await {+ Ok(qv) => {+ self.reader+ .hybrid_search(+ self.workspace_id,+ self.project_id,+ args.query.clone(),+ Some(qv),+ embedder.provider().to_string(),+ embedder.model().to_string(),+ embedder.dim(),+ limit,+ )+ .await+ }+ Err(e) => {+ tracing::warn!(+ provider = embedder.provider(),+ model = embedder.model(),+ error = %e,+ "embedder failed; degrading memory_query to BM25-only"+ );+ self.reader.search_pages(args.query, limit).await+ }+ }} else {self.reader.search_pages(args.query, limit).await};