Skip to main content

innate_core/
llm.rs

1use serde_json::{json, Value};
2use std::time::Duration;
3
4use crate::embedding::EmbeddingProvider;
5use crate::errors::{InnateError, Result};
6use crate::refine::{DistillProvenance, DistilledChunk, Distiller};
7use crate::settings::{EmbeddingConfig, LlmConfig};
8
9// ---------------------------------------------------------------------------
10// Prompt for distillation
11// ---------------------------------------------------------------------------
12
13const DISTILL_PROMPT_VERSION: &str = "4";
14
15fn safe_prompt_field(value: Option<&str>) -> String {
16    let value = value.unwrap_or("");
17    let (cleaned, action) = crate::utils::sanitize(value);
18    match action {
19        crate::utils::SanitizeAction::Discard => "[removed unsafe content]".to_string(),
20        _ => cleaned,
21    }
22}
23
24fn build_distill_prompt(log: &Value) -> String {
25    let query = safe_prompt_field(log.get("query").and_then(Value::as_str));
26    let output = safe_prompt_field(log.get("output").and_then(Value::as_str));
27    let output_summary = safe_prompt_field(log.get("output_summary").and_then(Value::as_str));
28    let nomination = safe_prompt_field(log.get("nomination").and_then(Value::as_str));
29    let outcome = safe_prompt_field(log.get("outcome").and_then(Value::as_str));
30
31    let mut context_parts = vec![];
32    if !query.is_empty() {
33        context_parts.push(format!("Query: {query}"));
34    }
35    if !nomination.is_empty() {
36        context_parts.push(format!("Nominated insight: {nomination}"));
37    }
38    if !output_summary.is_empty() {
39        context_parts.push(format!("Summary: {output_summary}"));
40    }
41    if !output.is_empty() {
42        let truncated: String = output.chars().take(1500).collect();
43        context_parts.push(format!("Output (truncated): {truncated}"));
44    }
45    if !outcome.is_empty() {
46        context_parts.push(format!("Outcome: {outcome}"));
47    }
48
49    let context = context_parts.join("\n");
50
51    format!(
52        r#"You are a knowledge distillation assistant. Given an agent interaction log, \
53extract zero or more independent reusable procedural principles. Favor GENERAL, \
54transferable skills, methods, and techniques over project-specific facts.
55
56Agent interaction:
57{context}
58
59Output a JSON array. Each item has:
60{{
61  "skill_name": "<1-3 word skill/topic label for this principle>",
62  "content": "<principle; when it applies; what to avoid>",
63  "trigger_desc": "<2-6 word canonical phrase>",
64  "anti_trigger_desc": "<when NOT to apply this, or null>"
65}}
66Return [] if nothing is worth keeping.
67
68Rules:
69- skill_name is a short human label (1-3 words) naming the skill/topic, e.g.
70  "error handling", "git rebase", "async retries"; not a sentence
71- content must be self-contained and actionable for a future agent reading cold
72- Prefer transferable methods and techniques; a principle that helps across many
73  projects is worth far more than one tied to this codebase
74- Abstract away project-specific detail: strip repo/file/function/path/variable names
75  and one-off identifiers, and rephrase the lesson as a general principle whoever the
76  next project is. Keep concrete project-specific detail ONLY when the lesson genuinely
77  cannot be generalized without losing its meaning
78- trigger_desc must match the vocabulary a future agent would use in a search query;
79  prefer general, technology- or domain-level phrasing over project-name phrasing
80- Never store conversation text verbatim; always distil to reusable principle form
81- If outcome is "fail", focus on what to avoid
82- Keep principles independent; do not combine unrelated lessons"#
83    )
84}
85
86fn build_distill_prompt_with_related(log: &Value, logs: &[Value]) -> String {
87    let mut prompt = build_distill_prompt(log);
88    let log_id = log.get("id").and_then(Value::as_str).unwrap_or("");
89    let context_key = log.get("context_key").and_then(Value::as_str);
90    let related: Vec<String> = logs
91        .iter()
92        .filter(|other| other.get("id").and_then(Value::as_str).unwrap_or("") != log_id)
93        .filter(|other| {
94            context_key.is_some() && other.get("context_key").and_then(Value::as_str) == context_key
95        })
96        .take(4)
97        .map(|other| {
98            let query = safe_prompt_field(other.get("query").and_then(Value::as_str));
99            let summary = safe_prompt_field(other.get("output_summary").and_then(Value::as_str));
100            let outcome = safe_prompt_field(other.get("outcome").and_then(Value::as_str));
101            format!("- Query: {query}; outcome: {outcome}; summary: {summary}")
102        })
103        .collect();
104    if !related.is_empty() {
105        prompt.push_str(
106            "\n\nRelated recent interactions (use only to identify repeated patterns or conflicts):\n",
107        );
108        prompt.push_str(&related.join("\n"));
109    }
110    prompt
111}
112
113// ---------------------------------------------------------------------------
114// Shared HTTP transport with retry/backoff
115// ---------------------------------------------------------------------------
116
117/// Max total attempts (initial try + retries) for a single LLM/embedding call.
118const HTTP_MAX_ATTEMPTS: u32 = 3;
119/// Per-request socket timeout. Each retry gets a fresh timeout window.
120const HTTP_TIMEOUT: Duration = Duration::from_secs(30);
121
122/// POST `body` as JSON to `url` with the given extra headers, retrying transient
123/// failures (network/timeout errors, HTTP 429, and 5xx) with exponential backoff.
124/// `Content-Type: application/json` is set automatically. `label` names the call
125/// site in error messages (e.g. "LLM", "Anthropic", "Embedding").
126fn post_json_retry(
127    url: &str,
128    headers: &[(&str, &str)],
129    body: &Value,
130    label: &str,
131) -> Result<Value> {
132    // Single instrumentation point for all LLM/embedding calls: time the whole
133    // call (across retries) and emit one trace with the final outcome. The
134    // `Authorization` header is never handed to the tracer — only the body.
135    let start = std::time::Instant::now();
136    let mut attempt = 0;
137    let outcome: Result<Value> = loop {
138        attempt += 1;
139        // ureq 3 no longer carries the response inside the status error, so we opt
140        // out of `http_status_as_error`: non-2xx comes back as `Ok(response)` and we
141        // read its code + headers + body ourselves. A genuine `Err` is therefore a
142        // transport-level failure (timeout / connection / I/O) — always retryable.
143        let mut req = ureq::post(url)
144            .config()
145            .timeout_global(Some(HTTP_TIMEOUT))
146            .http_status_as_error(false)
147            .build()
148            .header("Content-Type", "application/json");
149        for (k, v) in headers {
150            req = req.header(*k, *v);
151        }
152        match req.send_json(body) {
153            Ok(mut response) => {
154                let code = response.status().as_u16();
155                if (200..300).contains(&code) {
156                    break response
157                        .body_mut()
158                        .read_json::<Value>()
159                        .map_err(|e| {
160                            InnateError::Other(format!("{label} response parse error: {e}"))
161                        });
162                }
163                let retry_after = response
164                    .headers()
165                    .get("retry-after")
166                    .and_then(|h| h.to_str().ok())
167                    .and_then(|s| s.trim().parse::<u64>().ok());
168                if status_is_retryable(code) && attempt < HTTP_MAX_ATTEMPTS {
169                    std::thread::sleep(backoff_delay(attempt, retry_after));
170                    continue;
171                }
172                // `status: {code}` is the substring llm_trace classifies into
173                // http_4xx / http_5xx / rate_limited (429); keep it ahead of the body.
174                let detail = response.body_mut().read_to_string().unwrap_or_default();
175                break Err(InnateError::Other(format!(
176                    "{label} HTTP error: status: {code} {detail}"
177                )));
178            }
179            Err(err) => {
180                if attempt < HTTP_MAX_ATTEMPTS {
181                    std::thread::sleep(backoff_delay(attempt, None));
182                    continue;
183                }
184                // `transport:` tag preserves the transport bucket in llm_trace.
185                break Err(InnateError::Other(format!(
186                    "{label} HTTP error: transport: {err}"
187                )));
188            }
189        }
190    };
191    crate::llm_trace::record(label, url, body, &outcome, attempt, start.elapsed());
192    outcome
193}
194
195/// Transient HTTP statuses worth retrying: rate limits and server-side errors.
196fn status_is_retryable(code: u16) -> bool {
197    code == 429 || (500..=599).contains(&code)
198}
199
200/// Backoff before the next attempt. Honors a server `Retry-After` (seconds, capped
201/// at 30s) when present, otherwise exponential: 250ms, 500ms, 1s, ...
202fn backoff_delay(attempt: u32, retry_after_secs: Option<u64>) -> Duration {
203    if let Some(secs) = retry_after_secs {
204        return Duration::from_secs(secs.min(30));
205    }
206    let shift = (attempt - 1).min(6);
207    Duration::from_millis(250u64.saturating_mul(1 << shift))
208}
209
210// ---------------------------------------------------------------------------
211// HTTP distiller — one type for both OpenAI-compatible endpoints (GPT, DeepSeek,
212// local Ollama, ...) and the Anthropic Messages API. The request/response shape
213// is selected per call from `config.provider`; everything else (distill loop,
214// provenance, retry transport) is shared.
215// ---------------------------------------------------------------------------
216
217pub struct HttpDistiller {
218    config: LlmConfig,
219}
220
221impl HttpDistiller {
222    pub fn new(config: LlmConfig) -> Self {
223        Self { config }
224    }
225
226    fn call(&self, prompt: &str) -> Result<String> {
227        if self.config.provider == "anthropic" {
228            self.call_anthropic(prompt)
229        } else {
230            self.call_openai(prompt)
231        }
232    }
233
234    fn call_openai(&self, prompt: &str) -> Result<String> {
235        let api_key = self
236            .config
237            .resolved_api_key()
238            .ok_or_else(|| InnateError::Other("LLM API key not configured".into()))?;
239
240        let base = self.config.resolved_base_url();
241        let url = format!("{base}/chat/completions");
242
243        let body = json!({
244            "model": self.config.model_id,
245            "messages": [{"role": "user", "content": prompt}],
246            "max_tokens": 800,
247            "temperature": 0.2,
248        });
249
250        let auth = format!("Bearer {api_key}");
251        let resp_json = post_json_retry(&url, &[("Authorization", &auth)], &body, "LLM")?;
252
253        resp_json
254            .pointer("/choices/0/message/content")
255            .and_then(Value::as_str)
256            .map(str::to_string)
257            .ok_or_else(|| InnateError::Other("unexpected LLM response shape".into()))
258    }
259
260    fn call_anthropic(&self, prompt: &str) -> Result<String> {
261        let api_key = self
262            .config
263            .resolved_api_key()
264            .ok_or_else(|| InnateError::Other("Anthropic API key not configured".into()))?;
265
266        let base = self.config.resolved_base_url();
267        let url = format!("{base}/v1/messages");
268
269        let body = json!({
270            "model": self.config.model_id,
271            "max_tokens": 800,
272            "messages": [{"role": "user", "content": prompt}],
273        });
274
275        let resp_json = post_json_retry(
276            &url,
277            &[("x-api-key", &api_key), ("anthropic-version", "2023-06-01")],
278            &body,
279            "Anthropic",
280        )?;
281
282        resp_json
283            .pointer("/content/0/text")
284            .and_then(Value::as_str)
285            .map(str::to_string)
286            .ok_or_else(|| InnateError::Other("unexpected Anthropic response shape".into()))
287    }
288}
289
290impl Distiller for HttpDistiller {
291    fn distill(&self, log_entries: &[Value]) -> crate::errors::Result<Vec<DistilledChunk>> {
292        distill_with(log_entries, |prompt| self.call(prompt))
293    }
294
295    fn distill_with_context(
296        &self,
297        primary: &Value,
298        related_logs: &[Value],
299    ) -> crate::errors::Result<Vec<DistilledChunk>> {
300        distill_entry_with(primary, related_logs, |prompt| self.call(prompt))
301    }
302
303    fn provenance(&self) -> DistillProvenance {
304        DistillProvenance {
305            provider: Some(self.config.provider.clone()),
306            model: Some(self.config.model_id.clone()),
307            prompt_version: Some(DISTILL_PROMPT_VERSION.to_string()),
308        }
309    }
310}
311
312// ---------------------------------------------------------------------------
313// Shared parse logic
314// ---------------------------------------------------------------------------
315
316fn distill_with(
317    log_entries: &[Value],
318    call: impl Fn(&str) -> Result<String> + Copy,
319) -> Result<Vec<DistilledChunk>> {
320    let mut out = Vec::new();
321    for entry in log_entries {
322        out.extend(distill_entry_with(entry, log_entries, call)?);
323    }
324    Ok(out)
325}
326
327fn distill_entry_with(
328    entry: &Value,
329    related_logs: &[Value],
330    call: impl Fn(&str) -> Result<String>,
331) -> Result<Vec<DistilledChunk>> {
332    let log_id = entry["id"].as_str().unwrap_or("").to_string();
333    let prompt = build_distill_prompt_with_related(entry, related_logs);
334    let mut raw = call(&prompt)?;
335    let mut parsed = parse_distill_response(&raw);
336    if parsed.is_err() {
337        raw = call(&format!(
338            "{prompt}\n\nYour previous response was invalid. Return only a valid JSON array."
339        ))?;
340        parsed = parse_distill_response(&raw);
341    }
342    let items = parsed.map_err(|error| {
343        InnateError::Other(format!("LLM distillation response invalid: {error}"))
344    })?;
345    let mut out = Vec::new();
346    for parsed in items {
347        let content = parsed
348            .get("content")
349            .and_then(Value::as_str)
350            .map(str::trim)
351            .filter(|s| !s.is_empty());
352        let Some(content) = content else { continue };
353        let skill_name = parsed
354            .get("skill_name")
355            .and_then(Value::as_str)
356            .map(|s| s.trim().split_whitespace().take(3).collect::<Vec<_>>().join(" "))
357            .filter(|s| !s.is_empty() && s.to_lowercase() != "null");
358        let trigger_desc = parsed
359            .get("trigger_desc")
360            .and_then(Value::as_str)
361            .map(str::to_string)
362            .filter(|s| !s.is_empty());
363        let anti_trigger_desc = parsed
364            .get("anti_trigger_desc")
365            .and_then(Value::as_str)
366            .map(str::to_string)
367            .filter(|s| !s.is_empty() && s.to_lowercase() != "null");
368        out.push(DistilledChunk {
369            content: content.to_string(),
370            skill_name,
371            trigger_desc,
372            anti_trigger_desc,
373            source_log_id: log_id.clone(),
374            nomination: entry
375                .get("nomination")
376                .and_then(Value::as_str)
377                .map(str::to_string),
378        });
379    }
380    Ok(out)
381}
382
383fn parse_distill_response(raw: &str) -> std::result::Result<Vec<Value>, String> {
384    let json_str = extract_json(raw);
385    let parsed: Value = serde_json::from_str(json_str.trim()).map_err(|e| e.to_string())?;
386    if parsed.get("skip").and_then(Value::as_bool) == Some(true) {
387        return Ok(vec![]);
388    }
389    match parsed {
390        Value::Array(items) => Ok(items),
391        Value::Object(_) => Ok(vec![parsed]),
392        _ => Err("expected a JSON object or array".to_string()),
393    }
394}
395
396fn extract_json(text: &str) -> &str {
397    // Strip markdown code fences if present: ```json ... ``` or ``` ... ```
398    let stripped = text.trim();
399    if let Some(inner) = stripped
400        .strip_prefix("```json")
401        .or_else(|| stripped.strip_prefix("```"))
402    {
403        if let Some(end) = inner.rfind("```") {
404            return inner[..end].trim();
405        }
406    }
407    if let (Some(start), Some(end)) = (stripped.find('['), stripped.rfind(']')) {
408        return &stripped[start..=end];
409    }
410    // Backward-compatible object response.
411    if let (Some(start), Some(end)) = (stripped.find('{'), stripped.rfind('}')) {
412        return &stripped[start..=end];
413    }
414    stripped
415}
416
417// ---------------------------------------------------------------------------
418// Build distiller from settings
419// ---------------------------------------------------------------------------
420
421pub fn build_distiller(config: &LlmConfig) -> std::sync::Arc<dyn Distiller + Send + Sync> {
422    std::sync::Arc::new(HttpDistiller::new(config.clone()))
423}
424
425// ---------------------------------------------------------------------------
426// LLM embedding provider (OpenAI-compatible /v1/embeddings)
427// ---------------------------------------------------------------------------
428
429pub struct LlmEmbeddingProvider {
430    config: EmbeddingConfig,
431}
432
433#[cfg(test)]
434#[allow(clippy::items_after_test_module)]
435mod tests {
436    use std::cell::Cell;
437
438    use serde_json::json;
439
440    use std::time::Duration;
441
442    use super::{
443        backoff_delay, build_distill_prompt, distill_entry_with, distill_with,
444        parse_distill_response, parse_embedding_response, status_is_retryable,
445    };
446
447    #[test]
448    fn embedding_response_is_parsed_fail_closed() {
449        // Happy path: correct dimension parses.
450        let resp = json!({"data": [{"embedding": [0.1, 0.2, 0.3]}]});
451        assert_eq!(parse_embedding_response(&resp, 3).unwrap(), vec![0.1f32, 0.2, 0.3]);
452
453        // Wrong dimension is rejected, not silently accepted.
454        assert!(parse_embedding_response(&resp, 4).is_err());
455
456        // A non-numeric element fails the whole parse (no silent drop).
457        let bad = json!({"data": [{"embedding": [0.1, "oops", 0.3]}]});
458        assert!(parse_embedding_response(&bad, 3).is_err());
459
460        // Missing embedding field is rejected.
461        let shape = json!({"data": []});
462        assert!(parse_embedding_response(&shape, 3).is_err());
463    }
464
465    #[test]
466    fn only_rate_limit_and_5xx_are_retryable() {
467        assert!(status_is_retryable(429));
468        assert!(status_is_retryable(500));
469        assert!(status_is_retryable(503));
470        assert!(status_is_retryable(599));
471        assert!(!status_is_retryable(400));
472        assert!(!status_is_retryable(401));
473        assert!(!status_is_retryable(404));
474        assert!(!status_is_retryable(200));
475    }
476
477    #[test]
478    fn backoff_is_exponential_and_honors_retry_after() {
479        // Exponential schedule: 250ms, 500ms, 1s for attempts 1..3.
480        assert_eq!(backoff_delay(1, None), Duration::from_millis(250));
481        assert_eq!(backoff_delay(2, None), Duration::from_millis(500));
482        assert_eq!(backoff_delay(3, None), Duration::from_millis(1000));
483        // Retry-After overrides the schedule and is capped at 30s.
484        assert_eq!(backoff_delay(1, Some(5)), Duration::from_secs(5));
485        assert_eq!(backoff_delay(1, Some(120)), Duration::from_secs(30));
486    }
487
488    #[test]
489    fn prompt_redacts_secrets_before_external_llm_call() {
490        let prompt = build_distill_prompt(&json!({
491            "query": "debug sk-12345678901234567890",
492            "output_summary": "Authorization: Bearer secret-token-value"
493        }));
494        assert!(!prompt.contains("sk-12345678901234567890"));
495        assert!(!prompt.contains("secret-token-value"));
496        assert!(prompt.contains("[REDACTED]"));
497    }
498
499    #[test]
500    fn malformed_response_is_retried_instead_of_silently_skipped() {
501        let calls = Cell::new(0);
502        let chunks = distill_with(&[json!({"id": "log-1", "query": "q"})], |_| {
503            calls.set(calls.get() + 1);
504            if calls.get() == 1 {
505                Ok("not json".to_string())
506            } else {
507                Ok(r#"[{"content":"retry worked","trigger_desc":"retry"}]"#.to_string())
508            }
509        })
510        .unwrap();
511        assert_eq!(calls.get(), 2);
512        assert_eq!(chunks.len(), 1);
513        assert_eq!(chunks[0].content, "retry worked");
514    }
515
516    #[test]
517    fn parser_accepts_multiple_distilled_chunks() {
518        let parsed = parse_distill_response(
519            r#"[{"content":"one"},{"content":"two","anti_trigger_desc":"never"}]"#,
520        )
521        .unwrap();
522        assert_eq!(parsed.len(), 2);
523    }
524
525    #[test]
526    fn nomination_is_distilled_instead_of_bypassing_the_model() {
527        let prompt_seen = Cell::new(false);
528        let entry = json!({
529            "id": "log-1",
530            "query": "original query",
531            "nomination": "raw agent nomination",
532            "output_summary": "summary",
533            "outcome": "ok"
534        });
535        let chunks = distill_entry_with(&entry, std::slice::from_ref(&entry), |prompt| {
536            prompt_seen.set(prompt.contains("raw agent nomination"));
537            Ok(
538                r#"[{"content":"generalized principle","trigger_desc":"generalize","anti_trigger_desc":null}]"#
539                    .to_string(),
540            )
541        })
542        .unwrap();
543
544        assert!(prompt_seen.get());
545        assert_eq!(chunks[0].content, "generalized principle");
546        assert_eq!(
547            chunks[0].nomination.as_deref(),
548            Some("raw agent nomination")
549        );
550    }
551}
552
553impl LlmEmbeddingProvider {
554    pub fn new(config: EmbeddingConfig) -> Self {
555        Self { config }
556    }
557
558    fn embed(&self, text: &str) -> Result<Vec<f32>> {
559        let api_key = self
560            .config
561            .resolved_api_key()
562            .ok_or_else(|| InnateError::Other("Embedding API key not configured".into()))?;
563
564        let base = self.config.resolved_base_url();
565        let url = format!("{base}/embeddings");
566
567        let body = json!({
568            "input": text,
569            "model": self.config.model_id,
570        });
571
572        let auth = format!("Bearer {api_key}");
573        let resp_json = post_json_retry(
574            &url,
575            &[("Authorization", &auth)],
576            &body,
577            "Embedding",
578        )?;
579
580        parse_embedding_response(&resp_json, self.config.dim)
581    }
582}
583
584/// Parse an OpenAI-compatible embedding response, fail-closed.
585///
586/// Every element must be numeric (bad entries are not silently dropped) and the
587/// resulting length must equal `expected_dim`, so a malformed or wrong-dimension
588/// vector never reaches cosine similarity.
589fn parse_embedding_response(resp_json: &Value, expected_dim: usize) -> Result<Vec<f32>> {
590    let embedding = resp_json
591        .pointer("/data/0/embedding")
592        .and_then(Value::as_array)
593        .ok_or_else(|| InnateError::Other("unexpected embedding response shape".into()))?;
594    let vec: Vec<f32> = embedding
595        .iter()
596        .map(|v| {
597            v.as_f64().map(|x| x as f32).ok_or_else(|| {
598                InnateError::Other("embedding response contains a non-numeric element".into())
599            })
600        })
601        .collect::<Result<Vec<f32>>>()?;
602    if vec.len() != expected_dim {
603        return Err(InnateError::Other(format!(
604            "embedding dimension mismatch: provider returned {}, expected {expected_dim} (check embedding.dim)",
605            vec.len(),
606        )));
607    }
608    Ok(vec)
609}
610
611impl EmbeddingProvider for LlmEmbeddingProvider {
612    fn model_name(&self) -> &'static str {
613        "llm-embedding"
614    }
615
616    fn content_dim(&self) -> usize {
617        self.config.dim
618    }
619
620    fn trigger_dim(&self) -> usize {
621        self.config.dim
622    }
623
624    fn embed_content(&self, text: &str) -> Result<Vec<f32>> {
625        self.embed(text)
626    }
627
628    fn embed_trigger(&self, text: &str) -> Result<Vec<f32>> {
629        self.embed(text)
630    }
631
632    /// Content and trigger share the same model and dimension here, so a single
633    /// HTTP request serves both spaces — half the round trips per recall.
634    fn embed_both(&self, text: &str) -> Result<(Vec<f32>, Vec<f32>)> {
635        let v = self.embed(text)?;
636        Ok((v.clone(), v))
637    }
638}
639
640// ---------------------------------------------------------------------------
641// Connection test helpers (used by install)
642// ---------------------------------------------------------------------------
643
644/// Test the LLM config by sending a minimal request. Returns Ok(model_response) or Err.
645pub fn test_llm(config: &LlmConfig) -> Result<String> {
646    let distiller = build_distiller(config);
647    let dummy_log = json!({
648        "id": "test",
649        "query": "connection test",
650        "output_summary": "test",
651        "outcome": "ok"
652    });
653    // We don't care about the result — just that the call succeeds.
654    distiller.distill(&[dummy_log])?;
655    Ok(format!("OK — model: {}", config.model_id))
656}
657
658/// Test the embedding config. Returns Ok(dim) or Err.
659pub fn test_embedding(config: &EmbeddingConfig) -> Result<usize> {
660    let provider = LlmEmbeddingProvider::new(config.clone());
661    let vec = provider.embed("connection test")?;
662    Ok(vec.len())
663}