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.body_mut().read_json::<Value>().map_err(|e| {
157                        InnateError::Other(format!("{label} response parse error: {e}"))
158                    });
159                }
160                let retry_after = response
161                    .headers()
162                    .get("retry-after")
163                    .and_then(|h| h.to_str().ok())
164                    .and_then(|s| s.trim().parse::<u64>().ok());
165                if status_is_retryable(code) && attempt < HTTP_MAX_ATTEMPTS {
166                    std::thread::sleep(backoff_delay(attempt, retry_after));
167                    continue;
168                }
169                // `status: {code}` is the substring llm_trace classifies into
170                // http_4xx / http_5xx / rate_limited (429); keep it ahead of the body.
171                let detail = response.body_mut().read_to_string().unwrap_or_default();
172                break Err(InnateError::Other(format!(
173                    "{label} HTTP error: status: {code} {detail}"
174                )));
175            }
176            Err(err) => {
177                if attempt < HTTP_MAX_ATTEMPTS {
178                    std::thread::sleep(backoff_delay(attempt, None));
179                    continue;
180                }
181                // `transport:` tag preserves the transport bucket in llm_trace.
182                break Err(InnateError::Other(format!(
183                    "{label} HTTP error: transport: {err}"
184                )));
185            }
186        }
187    };
188    crate::llm_trace::record(label, url, body, &outcome, attempt, start.elapsed());
189    outcome
190}
191
192/// Transient HTTP statuses worth retrying: rate limits and server-side errors.
193fn status_is_retryable(code: u16) -> bool {
194    code == 429 || (500..=599).contains(&code)
195}
196
197/// Backoff before the next attempt. Honors a server `Retry-After` (seconds, capped
198/// at 30s) when present, otherwise exponential: 250ms, 500ms, 1s, ...
199fn backoff_delay(attempt: u32, retry_after_secs: Option<u64>) -> Duration {
200    if let Some(secs) = retry_after_secs {
201        return Duration::from_secs(secs.min(30));
202    }
203    let shift = (attempt - 1).min(6);
204    Duration::from_millis(250u64.saturating_mul(1 << shift))
205}
206
207// ---------------------------------------------------------------------------
208// HTTP distiller — one type for both OpenAI-compatible endpoints (GPT, DeepSeek,
209// local Ollama, ...) and the Anthropic Messages API. The request/response shape
210// is selected per call from `config.provider`; everything else (distill loop,
211// provenance, retry transport) is shared.
212// ---------------------------------------------------------------------------
213
214pub struct HttpDistiller {
215    config: LlmConfig,
216}
217
218impl HttpDistiller {
219    pub fn new(config: LlmConfig) -> Self {
220        Self { config }
221    }
222
223    fn call(&self, prompt: &str) -> Result<String> {
224        if self.config.provider == "anthropic" {
225            self.call_anthropic(prompt)
226        } else {
227            self.call_openai(prompt)
228        }
229    }
230
231    fn call_openai(&self, prompt: &str) -> Result<String> {
232        let api_key = self
233            .config
234            .resolved_api_key()
235            .ok_or_else(|| InnateError::Other("LLM API key not configured".into()))?;
236
237        let base = self.config.resolved_base_url();
238        let url = format!("{base}/chat/completions");
239
240        let body = json!({
241            "model": self.config.model_id,
242            "messages": [{"role": "user", "content": prompt}],
243            "max_tokens": 800,
244            "temperature": 0.2,
245        });
246
247        let auth = format!("Bearer {api_key}");
248        let resp_json = post_json_retry(&url, &[("Authorization", &auth)], &body, "LLM")?;
249
250        resp_json
251            .pointer("/choices/0/message/content")
252            .and_then(Value::as_str)
253            .map(str::to_string)
254            .ok_or_else(|| InnateError::Other("unexpected LLM response shape".into()))
255    }
256
257    fn call_anthropic(&self, prompt: &str) -> Result<String> {
258        let api_key = self
259            .config
260            .resolved_api_key()
261            .ok_or_else(|| InnateError::Other("Anthropic API key not configured".into()))?;
262
263        let base = self.config.resolved_base_url();
264        let url = format!("{base}/v1/messages");
265
266        let body = json!({
267            "model": self.config.model_id,
268            "max_tokens": 800,
269            "messages": [{"role": "user", "content": prompt}],
270        });
271
272        let resp_json = post_json_retry(
273            &url,
274            &[("x-api-key", &api_key), ("anthropic-version", "2023-06-01")],
275            &body,
276            "Anthropic",
277        )?;
278
279        resp_json
280            .pointer("/content/0/text")
281            .and_then(Value::as_str)
282            .map(str::to_string)
283            .ok_or_else(|| InnateError::Other("unexpected Anthropic response shape".into()))
284    }
285}
286
287impl Distiller for HttpDistiller {
288    fn distill(&self, log_entries: &[Value]) -> crate::errors::Result<Vec<DistilledChunk>> {
289        distill_with(log_entries, |prompt| self.call(prompt))
290    }
291
292    fn distill_with_context(
293        &self,
294        primary: &Value,
295        related_logs: &[Value],
296    ) -> crate::errors::Result<Vec<DistilledChunk>> {
297        distill_entry_with(primary, related_logs, |prompt| self.call(prompt))
298    }
299
300    fn provenance(&self) -> DistillProvenance {
301        DistillProvenance {
302            provider: Some(self.config.provider.clone()),
303            model: Some(self.config.model_id.clone()),
304            prompt_version: Some(DISTILL_PROMPT_VERSION.to_string()),
305        }
306    }
307}
308
309// ---------------------------------------------------------------------------
310// Shared parse logic
311// ---------------------------------------------------------------------------
312
313fn distill_with(
314    log_entries: &[Value],
315    call: impl Fn(&str) -> Result<String> + Copy,
316) -> Result<Vec<DistilledChunk>> {
317    let mut out = Vec::new();
318    for entry in log_entries {
319        out.extend(distill_entry_with(entry, log_entries, call)?);
320    }
321    Ok(out)
322}
323
324fn distill_entry_with(
325    entry: &Value,
326    related_logs: &[Value],
327    call: impl Fn(&str) -> Result<String>,
328) -> Result<Vec<DistilledChunk>> {
329    let log_id = entry["id"].as_str().unwrap_or("").to_string();
330    let prompt = build_distill_prompt_with_related(entry, related_logs);
331    let mut raw = call(&prompt)?;
332    let mut parsed = parse_distill_response(&raw);
333    if parsed.is_err() {
334        raw = call(&format!(
335            "{prompt}\n\nYour previous response was invalid. Return only a valid JSON array."
336        ))?;
337        parsed = parse_distill_response(&raw);
338    }
339    let items = parsed.map_err(|error| {
340        InnateError::Other(format!("LLM distillation response invalid: {error}"))
341    })?;
342    let mut out = Vec::new();
343    for parsed in items {
344        let content = parsed
345            .get("content")
346            .and_then(Value::as_str)
347            .map(str::trim)
348            .filter(|s| !s.is_empty());
349        let Some(content) = content else { continue };
350        let skill_name = parsed
351            .get("skill_name")
352            .and_then(Value::as_str)
353            .map(|s| {
354                s.trim()
355                    .split_whitespace()
356                    .take(3)
357                    .collect::<Vec<_>>()
358                    .join(" ")
359            })
360            .filter(|s| !s.is_empty() && s.to_lowercase() != "null");
361        let trigger_desc = parsed
362            .get("trigger_desc")
363            .and_then(Value::as_str)
364            .map(str::to_string)
365            .filter(|s| !s.is_empty());
366        let anti_trigger_desc = parsed
367            .get("anti_trigger_desc")
368            .and_then(Value::as_str)
369            .map(str::to_string)
370            .filter(|s| !s.is_empty() && s.to_lowercase() != "null");
371        out.push(DistilledChunk {
372            content: content.to_string(),
373            skill_name,
374            trigger_desc,
375            anti_trigger_desc,
376            source_log_id: log_id.clone(),
377            nomination: entry
378                .get("nomination")
379                .and_then(Value::as_str)
380                .map(str::to_string),
381            provider_override: None,
382        });
383    }
384    Ok(out)
385}
386
387fn parse_distill_response(raw: &str) -> std::result::Result<Vec<Value>, String> {
388    let json_str = extract_json(raw);
389    let parsed: Value = serde_json::from_str(json_str.trim()).map_err(|e| e.to_string())?;
390    if parsed.get("skip").and_then(Value::as_bool) == Some(true) {
391        return Ok(vec![]);
392    }
393    match parsed {
394        Value::Array(items) => Ok(items),
395        Value::Object(_) => Ok(vec![parsed]),
396        _ => Err("expected a JSON object or array".to_string()),
397    }
398}
399
400fn extract_json(text: &str) -> &str {
401    // Strip markdown code fences if present: ```json ... ``` or ``` ... ```
402    let stripped = text.trim();
403    if let Some(inner) = stripped
404        .strip_prefix("```json")
405        .or_else(|| stripped.strip_prefix("```"))
406    {
407        if let Some(end) = inner.rfind("```") {
408            return inner[..end].trim();
409        }
410    }
411    if let (Some(start), Some(end)) = (stripped.find('['), stripped.rfind(']')) {
412        return &stripped[start..=end];
413    }
414    // Backward-compatible object response.
415    if let (Some(start), Some(end)) = (stripped.find('{'), stripped.rfind('}')) {
416        return &stripped[start..=end];
417    }
418    stripped
419}
420
421// ---------------------------------------------------------------------------
422// Build distiller from settings
423// ---------------------------------------------------------------------------
424
425pub fn build_distiller(config: &LlmConfig) -> std::sync::Arc<dyn Distiller + Send + Sync> {
426    std::sync::Arc::new(HttpDistiller::new(config.clone()))
427}
428
429// ---------------------------------------------------------------------------
430// LLM embedding provider (OpenAI-compatible /v1/embeddings)
431// ---------------------------------------------------------------------------
432
433pub struct LlmEmbeddingProvider {
434    config: EmbeddingConfig,
435}
436
437#[cfg(test)]
438#[allow(clippy::items_after_test_module)]
439mod tests {
440    use std::cell::Cell;
441
442    use serde_json::json;
443
444    use std::time::Duration;
445
446    use super::{
447        backoff_delay, build_distill_prompt, distill_entry_with, distill_with,
448        parse_distill_response, parse_embedding_response, status_is_retryable,
449    };
450
451    #[test]
452    fn embedding_response_is_parsed_fail_closed() {
453        // Happy path: correct dimension parses.
454        let resp = json!({"data": [{"embedding": [0.1, 0.2, 0.3]}]});
455        assert_eq!(
456            parse_embedding_response(&resp, 3).unwrap(),
457            vec![0.1f32, 0.2, 0.3]
458        );
459
460        // Wrong dimension is rejected, not silently accepted.
461        assert!(parse_embedding_response(&resp, 4).is_err());
462
463        // A non-numeric element fails the whole parse (no silent drop).
464        let bad = json!({"data": [{"embedding": [0.1, "oops", 0.3]}]});
465        assert!(parse_embedding_response(&bad, 3).is_err());
466
467        // Missing embedding field is rejected.
468        let shape = json!({"data": []});
469        assert!(parse_embedding_response(&shape, 3).is_err());
470    }
471
472    #[test]
473    fn only_rate_limit_and_5xx_are_retryable() {
474        assert!(status_is_retryable(429));
475        assert!(status_is_retryable(500));
476        assert!(status_is_retryable(503));
477        assert!(status_is_retryable(599));
478        assert!(!status_is_retryable(400));
479        assert!(!status_is_retryable(401));
480        assert!(!status_is_retryable(404));
481        assert!(!status_is_retryable(200));
482    }
483
484    #[test]
485    fn backoff_is_exponential_and_honors_retry_after() {
486        // Exponential schedule: 250ms, 500ms, 1s for attempts 1..3.
487        assert_eq!(backoff_delay(1, None), Duration::from_millis(250));
488        assert_eq!(backoff_delay(2, None), Duration::from_millis(500));
489        assert_eq!(backoff_delay(3, None), Duration::from_millis(1000));
490        // Retry-After overrides the schedule and is capped at 30s.
491        assert_eq!(backoff_delay(1, Some(5)), Duration::from_secs(5));
492        assert_eq!(backoff_delay(1, Some(120)), Duration::from_secs(30));
493    }
494
495    #[test]
496    fn prompt_redacts_secrets_before_external_llm_call() {
497        let prompt = build_distill_prompt(&json!({
498            "query": "debug sk-12345678901234567890",
499            "output_summary": "Authorization: Bearer secret-token-value"
500        }));
501        assert!(!prompt.contains("sk-12345678901234567890"));
502        assert!(!prompt.contains("secret-token-value"));
503        assert!(prompt.contains("[REDACTED]"));
504    }
505
506    #[test]
507    fn malformed_response_is_retried_instead_of_silently_skipped() {
508        let calls = Cell::new(0);
509        let chunks = distill_with(&[json!({"id": "log-1", "query": "q"})], |_| {
510            calls.set(calls.get() + 1);
511            if calls.get() == 1 {
512                Ok("not json".to_string())
513            } else {
514                Ok(r#"[{"content":"retry worked","trigger_desc":"retry"}]"#.to_string())
515            }
516        })
517        .unwrap();
518        assert_eq!(calls.get(), 2);
519        assert_eq!(chunks.len(), 1);
520        assert_eq!(chunks[0].content, "retry worked");
521    }
522
523    #[test]
524    fn parser_accepts_multiple_distilled_chunks() {
525        let parsed = parse_distill_response(
526            r#"[{"content":"one"},{"content":"two","anti_trigger_desc":"never"}]"#,
527        )
528        .unwrap();
529        assert_eq!(parsed.len(), 2);
530    }
531
532    #[test]
533    fn nomination_is_distilled_instead_of_bypassing_the_model() {
534        let prompt_seen = Cell::new(false);
535        let entry = json!({
536            "id": "log-1",
537            "query": "original query",
538            "nomination": "raw agent nomination",
539            "output_summary": "summary",
540            "outcome": "ok"
541        });
542        let chunks = distill_entry_with(&entry, std::slice::from_ref(&entry), |prompt| {
543            prompt_seen.set(prompt.contains("raw agent nomination"));
544            Ok(
545                r#"[{"content":"generalized principle","trigger_desc":"generalize","anti_trigger_desc":null}]"#
546                    .to_string(),
547            )
548        })
549        .unwrap();
550
551        assert!(prompt_seen.get());
552        assert_eq!(chunks[0].content, "generalized principle");
553        assert_eq!(
554            chunks[0].nomination.as_deref(),
555            Some("raw agent nomination")
556        );
557    }
558}
559
560impl LlmEmbeddingProvider {
561    pub fn new(config: EmbeddingConfig) -> Self {
562        Self { config }
563    }
564
565    fn embed(&self, text: &str) -> Result<Vec<f32>> {
566        let api_key = self
567            .config
568            .resolved_api_key()
569            .ok_or_else(|| InnateError::Other("Embedding API key not configured".into()))?;
570
571        let base = self.config.resolved_base_url();
572        let url = format!("{base}/embeddings");
573
574        let body = json!({
575            "input": text,
576            "model": self.config.model_id,
577        });
578
579        let auth = format!("Bearer {api_key}");
580        let resp_json = post_json_retry(&url, &[("Authorization", &auth)], &body, "Embedding")?;
581
582        parse_embedding_response(&resp_json, self.config.dim)
583    }
584}
585
586/// Parse an OpenAI-compatible embedding response, fail-closed.
587///
588/// Every element must be numeric (bad entries are not silently dropped) and the
589/// resulting length must equal `expected_dim`, so a malformed or wrong-dimension
590/// vector never reaches cosine similarity.
591fn parse_embedding_response(resp_json: &Value, expected_dim: usize) -> Result<Vec<f32>> {
592    let embedding = resp_json
593        .pointer("/data/0/embedding")
594        .and_then(Value::as_array)
595        .ok_or_else(|| InnateError::Other("unexpected embedding response shape".into()))?;
596    let vec: Vec<f32> = embedding
597        .iter()
598        .map(|v| {
599            v.as_f64().map(|x| x as f32).ok_or_else(|| {
600                InnateError::Other("embedding response contains a non-numeric element".into())
601            })
602        })
603        .collect::<Result<Vec<f32>>>()?;
604    if vec.len() != expected_dim {
605        return Err(InnateError::Other(format!(
606            "embedding dimension mismatch: provider returned {}, expected {expected_dim} (check embedding.dim)",
607            vec.len(),
608        )));
609    }
610    Ok(vec)
611}
612
613impl EmbeddingProvider for LlmEmbeddingProvider {
614    fn model_name(&self) -> &'static str {
615        "llm-embedding"
616    }
617
618    fn content_dim(&self) -> usize {
619        self.config.dim
620    }
621
622    fn trigger_dim(&self) -> usize {
623        self.config.dim
624    }
625
626    fn embed_content(&self, text: &str) -> Result<Vec<f32>> {
627        self.embed(text)
628    }
629
630    fn embed_trigger(&self, text: &str) -> Result<Vec<f32>> {
631        self.embed(text)
632    }
633
634    /// Content and trigger share the same model and dimension here, so a single
635    /// HTTP request serves both spaces — half the round trips per recall.
636    fn embed_both(&self, text: &str) -> Result<(Vec<f32>, Vec<f32>)> {
637        let v = self.embed(text)?;
638        Ok((v.clone(), v))
639    }
640}
641
642// ---------------------------------------------------------------------------
643// Connection test helpers (used by install)
644// ---------------------------------------------------------------------------
645
646/// Test the LLM config by sending a minimal request. Returns Ok(model_response) or Err.
647pub fn test_llm(config: &LlmConfig) -> Result<String> {
648    let distiller = build_distiller(config);
649    let dummy_log = json!({
650        "id": "test",
651        "query": "connection test",
652        "output_summary": "test",
653        "outcome": "ok"
654    });
655    // We don't care about the result — just that the call succeeds.
656    distiller.distill(&[dummy_log])?;
657    Ok(format!("OK — model: {}", config.model_id))
658}
659
660/// Test the embedding config. Returns Ok(dim) or Err.
661pub fn test_embedding(config: &EmbeddingConfig) -> Result<usize> {
662    let provider = LlmEmbeddingProvider::new(config.clone());
663    let vec = provider.embed("connection test")?;
664    Ok(vec.len())
665}