Skip to main content

gemini_adk_rs/live/
extractor.rs

1//! Turn-windowed extraction — OOB LLM structured data extraction between turns.
2//!
3//! A `TurnExtractor` runs after each turn completes, taking a window of recent
4//! transcript turns and producing a structured JSON value via an out-of-band
5//! LLM call.
6
7use std::sync::Arc;
8
9use async_trait::async_trait;
10use serde_json::Value;
11
12use crate::llm::{BaseLlm, LlmError, LlmRequest, LlmResponse};
13use crate::state::State;
14
15use super::phase::Phase;
16use super::transcript::TranscriptTurn;
17
18/// Controls WHEN an extractor runs.
19///
20/// The default is `EveryTurn`. Use `AfterToolCall` when tool calls are the primary state source,
21/// `Interval(n)` to reduce extraction frequency, or `OnPhaseChange`
22/// to extract only when entering a new conversation phase.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub enum ExtractionTrigger {
25    /// Run on every TurnComplete event (current default).
26    EveryTurn,
27    /// Run every N TurnComplete events.
28    Interval(u32),
29    /// Run after tool calls complete.
30    AfterToolCall,
31    /// Run when a phase transition occurs.
32    OnPhaseChange,
33    /// Run on GenerationComplete, as soon as the model has generated its
34    /// response and before the turn completes. Current Live models send no
35    /// GenerationComplete for an interrupted turn.
36    OnGenerationComplete,
37}
38
39/// How an extracted field should be merged into authoritative session state.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum MergePolicy {
42    /// Keep an existing state value; write only when the target key is absent.
43    KeepKnown,
44    /// Always overwrite the target state key with the extracted field value.
45    Overwrite,
46}
47
48/// Predicate used to decide whether an extracted field may be promoted.
49pub type PromotionPredicate = Arc<dyn Fn(&State, &Value) -> bool + Send + Sync>;
50
51/// Rule for promoting one raw extraction field into authoritative state.
52#[derive(Clone)]
53pub struct FieldPromotion {
54    /// Field name inside the extractor's JSON object.
55    pub field: String,
56    /// State key to write when the field is accepted.
57    pub state_key: String,
58    /// Merge behavior for the target state key.
59    pub merge: MergePolicy,
60    /// Optional acceptance predicate.
61    pub accept: Option<PromotionPredicate>,
62}
63
64impl FieldPromotion {
65    /// Promote `field` into the same state key using [`MergePolicy::KeepKnown`].
66    pub fn keep_known(field: impl Into<String>) -> Self {
67        let field = field.into();
68        Self {
69            state_key: field.clone(),
70            field,
71            merge: MergePolicy::KeepKnown,
72            accept: None,
73        }
74    }
75
76    /// Promote `field` into the same state key using [`MergePolicy::Overwrite`].
77    pub fn overwrite(field: impl Into<String>) -> Self {
78        let field = field.into();
79        Self {
80            state_key: field.clone(),
81            field,
82            merge: MergePolicy::Overwrite,
83            accept: None,
84        }
85    }
86
87    /// Promote a boolean field only when its extracted value is `true`.
88    pub fn true_only(field: impl Into<String>) -> Self {
89        Self::overwrite(field).accept_when(|_, value| value.as_bool() == Some(true))
90    }
91
92    /// Promote a string field only when its extracted value is non-empty.
93    pub fn non_empty(field: impl Into<String>) -> Self {
94        Self::overwrite(field)
95            .accept_when(|_, value| value.as_str().is_some_and(|s| !s.trim().is_empty()))
96    }
97
98    /// Promote into a custom target state key.
99    pub fn to(mut self, state_key: impl Into<String>) -> Self {
100        self.state_key = state_key.into();
101        self
102    }
103
104    /// Only accept this promotion when `predicate` returns true.
105    ///
106    /// This is the escape hatch for application-specific logic:
107    /// `FieldPromotion::overwrite("intent").accept_when(|state, value| ...)`.
108    pub fn accept_when(
109        mut self,
110        predicate: impl Fn(&State, &Value) -> bool + Send + Sync + 'static,
111    ) -> Self {
112        self.accept = Some(Arc::new(predicate));
113        self
114    }
115
116    /// Add an additional acceptance predicate, preserving any existing predicate.
117    pub fn and_accept_when(
118        mut self,
119        predicate: impl Fn(&State, &Value) -> bool + Send + Sync + 'static,
120    ) -> Self {
121        let previous = self.accept.take();
122        self.accept = Some(Arc::new(move |state, value| {
123            previous.as_ref().is_none_or(|accept| accept(state, value)) && predicate(state, value)
124        }));
125        self
126    }
127
128    /// Only promote after the named concept has been presented by a phase.
129    pub fn after_presented(self, concept: impl Into<String>) -> Self {
130        let concept = concept.into();
131        self.and_accept_when(move |state, _| Phase::is_presented(state, &concept))
132    }
133}
134
135/// Whether the newest turn of `window` has no caller words while an earlier
136/// one does: a turn the caller said nothing in, with input transcription on.
137/// Extracting it cannot find anything new from the caller.
138pub(crate) fn nothing_new_from_caller(window: &[TranscriptTurn]) -> bool {
139    window.last().is_some_and(|t| t.user.trim().is_empty())
140        && window.iter().any(|t| !t.user.trim().is_empty())
141}
142
143/// Trait for between-turn extraction from transcript windows.
144///
145/// Implementations receive a window of recent transcript turns and produce
146/// a structured JSON value. The processor stores the result in `State`
147/// under the extractor's name.
148#[async_trait]
149pub trait TurnExtractor: Send + Sync {
150    /// Name of this extractor (used as the State key).
151    fn name(&self) -> &str;
152
153    /// How many recent turns this extractor needs.
154    fn window_size(&self) -> usize;
155
156    /// Whether this extractor should run for the current turn.
157    ///
158    /// Override to skip extraction on trivial turns (e.g., short utterances,
159    /// turns without user speech). Default returns `true` (always extract).
160    ///
161    /// This is checked before launching the async extraction, so returning
162    /// `false` avoids an LLM round-trip entirely.
163    fn should_extract(&self, window: &[TranscriptTurn]) -> bool {
164        let _ = window;
165        true
166    }
167
168    /// The trigger mode for this extractor.
169    ///
170    /// Controls when the extractor runs. Default is `EveryTurn`.
171    fn trigger(&self) -> ExtractionTrigger {
172        ExtractionTrigger::EveryTurn
173    }
174
175    /// Field promotion rules for this extractor.
176    ///
177    /// When empty, the runtime auto-flattens every top-level non-null field of
178    /// the extraction into state under the field's own name. When non-empty,
179    /// only these rules can promote raw extraction fields into authoritative
180    /// state.
181    fn promotion_rules(&self) -> &[FieldPromotion] {
182        &[]
183    }
184
185    /// Whether this extractor may write the state key `key`.
186    ///
187    /// The tool lane asks this to pick the extractors to run early when a
188    /// guard that reads `key` refuses a tool. The default: a promotion rule
189    /// targets `key`, or there are no rules, in which case every field is
190    /// promoted under its own name and any key may be written.
191    fn may_write(&self, key: &str) -> bool {
192        let rules = self.promotion_rules();
193        rules.is_empty() || rules.iter().any(|r| r.state_key == key)
194    }
195
196    /// Extract structured data from the transcript window.
197    async fn extract(&self, window: &[TranscriptTurn]) -> Result<Value, LlmError>;
198
199    /// Extract with access to session `State` — for extractors whose sources
200    /// bind arguments from `State` (e.g. async fetch/agent resolvers).
201    ///
202    /// The default delegates to [`extract`](Self::extract), so transcript-only
203    /// extractors need not implement it. The pipeline always calls this method.
204    async fn extract_with_state(
205        &self,
206        window: &[TranscriptTurn],
207        state: &State,
208    ) -> Result<Value, LlmError> {
209        let _ = state;
210        self.extract(window).await
211    }
212
213    /// An optional agent to run when this extractor's results land in state —
214    /// the `on_complete(dispatch(agent))` effect. Fired by the pipeline after
215    /// promotion, only when the extractor produced a non-empty object.
216    fn on_complete(&self) -> Option<OnComplete> {
217        None
218    }
219}
220
221/// A state mutation or promotion decision produced by the shared extraction reducer.
222#[derive(Clone, Debug)]
223pub enum PromotionEvent {
224    /// A field was promoted and can be observed under this extraction event name.
225    Promoted {
226        /// Event name.
227        name: String,
228        /// Promoted value.
229        value: Value,
230    },
231    /// An explicit promotion rule accepted or rejected its field.
232    Decision {
233        /// Source field.
234        field: String,
235        /// Destination key.
236        state_key: String,
237        /// Whether the value was accepted.
238        accepted: bool,
239        /// Stable explanatory reason.
240        reason: String,
241        /// Observed value.
242        value: Value,
243    },
244}
245/// Apply the same null, merge and acceptance rules for Live and owned task extraction.
246pub fn promote_fields(
247    extractor: &dyn TurnExtractor,
248    name: &str,
249    value: &Value,
250    state: &State,
251) -> Vec<PromotionEvent> {
252    let mut events = Vec::new();
253    let Some(object) = value.as_object() else {
254        return events;
255    };
256    let rules = extractor.promotion_rules();
257    if rules.is_empty() {
258        for (field, value) in object {
259            if value.is_null() {
260                continue;
261            }
262            let _ = state.set(field, value.clone());
263            events.push(PromotionEvent::Promoted {
264                name: format!("{name}.{field}"),
265                value: value.clone(),
266            });
267        }
268        return events;
269    }
270    for rule in rules {
271        let Some(value) = object.get(&rule.field) else {
272            continue;
273        };
274        let reason = if value.is_null() {
275            Some("extracted value was null")
276        } else if state
277            .get_raw(&rule.state_key)
278            .is_some_and(|known| crate::state::equivalent_values(&known, value))
279        {
280            // Re-stating a known value in other words is not news; writing it
281            // would only churn the journal and could read as a correction.
282            Some("an equivalent value is already known")
283        } else if rule
284            .accept
285            .as_ref()
286            .is_some_and(|accept| !accept(state, value))
287        {
288            Some("promotion predicate rejected the value")
289        } else if matches!(rule.merge, MergePolicy::KeepKnown) && state.contains(&rule.state_key) {
290            Some("existing state value was kept")
291        } else {
292            None
293        };
294        if reason.is_none() {
295            let _ = state.set(&rule.state_key, value.clone());
296            let _ = state.set(
297                format!("state_meta:{}", rule.state_key),
298                serde_json::json!({"source":"extraction", "extractor":name, "field":rule.field}),
299            );
300            events.push(PromotionEvent::Promoted {
301                name: format!("{name}.{}", rule.field),
302                value: value.clone(),
303            });
304        }
305        events.push(PromotionEvent::Decision {
306            field: rule.field.clone(),
307            state_key: rule.state_key.clone(),
308            accepted: reason.is_none(),
309            reason: reason.unwrap_or("promotion rule accepted the value").into(),
310            value: value.clone(),
311        });
312    }
313    events
314}
315
316/// A downstream agent fired when an extractor's results land in state.
317#[derive(Clone)]
318pub struct OnComplete {
319    /// The agent to run; it reads its inputs from `State`.
320    pub agent: Arc<dyn crate::text::TextAgent>,
321    /// How to run it (`Call` awaits inline; `Dispatch`/`Background` detached).
322    pub mode: crate::orchestration::AgentMode,
323}
324
325/// Appended to every extraction prompt: a field the transcript does not
326/// state is null, never a guess.
327const NULL_GUIDANCE: &str = "\n\nUse null for any field the transcript does not state. \
328     Never guess, and never use placeholders such as \"unknown\", empty strings or zero.";
329
330/// Appended when some fields are already in state: re-reading the window
331/// every turn, the model would otherwise re-state known values in new words,
332/// and each re-statement would read as a correction. The latest turn is also
333/// quoted after the transcript: told only to compare with "the latest turn",
334/// `gemini-3.5-flash-lite` without thinking re-stated a known slot in 17 of
335/// 20 turns that changed nothing (7 in other words, read as corrections);
336/// with the turn quoted, in none of 30, and it still caught a real change in
337/// 30 of 30.
338const KNOWN_GUIDANCE: &str = "\n\nSome fields are already known (listed before the transcript). \
339     Compare each known field only with the user's latest turn, quoted after the transcript: \
340     return it only if that turn gives a different value. Agreeing, confirming, repeating or \
341     rewording a known value is not a change: return null.";
342
343/// The schema with every top-level property allowed to be null, so the
344/// model can say "not stated" instead of inventing a value of the right type.
345fn nullable_fields(schema: &Value) -> Value {
346    let mut schema = schema.clone();
347    let Some(properties) = schema.get_mut("properties").and_then(Value::as_object_mut) else {
348        return schema;
349    };
350    for property in properties.values_mut() {
351        let Some(object) = property.as_object_mut() else {
352            continue;
353        };
354        match object.get_mut("type") {
355            Some(Value::String(t)) if t != "null" => {
356                let t = t.clone();
357                object.insert("type".into(), serde_json::json!([t, "null"]));
358            }
359            Some(Value::Array(types)) => {
360                if !types.iter().any(|t| t == "null") {
361                    types.push(Value::String("null".into()));
362                }
363            }
364            Some(_) => {}
365            None => {
366                let inner = Value::Object(std::mem::take(object));
367                object.insert(
368                    "anyOf".into(),
369                    serde_json::json!([inner, { "type": "null" }]),
370                );
371            }
372        }
373    }
374    schema
375}
376
377/// LLM-backed turn extractor that sends transcript windows to an OOB LLM
378/// with a structured extraction prompt.
379pub struct LlmExtractor {
380    name: String,
381    llm: Arc<dyn BaseLlm>,
382    prompt: String,
383    window_size: usize,
384    schema: Option<Value>,
385    /// Pre-rendered schema string (computed once at construction)
386    schema_str: Option<String>,
387    /// Minimum word count in the last user utterance to trigger extraction.
388    min_words: usize,
389    /// When this extractor should fire.
390    trigger: ExtractionTrigger,
391    /// Field promotion rules. Empty means every top-level non-null field is
392    /// auto-flattened into state under its own name.
393    promotion_rules: Vec<FieldPromotion>,
394    /// Thinking budget sent with each request; `None` leaves the model's
395    /// default.
396    thinking_budget: Option<u32>,
397    /// How far down [`FALLBACK_THINKING_BUDGET`] the model has pushed the
398    /// budget: 0 sends `thinking_budget`, 1 the fallback, 2 none. Kept so a
399    /// rejected budget is not sent again.
400    budget_step: std::sync::atomic::AtomicU8,
401}
402
403/// The budget sent when a model rejects a thinking budget of 0, such as
404/// `gemini-3.5-flash-lite` ("Request contains an invalid argument"). That
405/// model accepts budgets from 1, and below about 1024 it does not think at
406/// all, so this keeps thinking off at the smallest budget it accepts.
407pub const FALLBACK_THINKING_BUDGET: u32 = 64;
408
409impl LlmExtractor {
410    /// Create a new LLM-backed extractor.
411    ///
412    /// - `name`: key for storing results in State
413    /// - `llm`: the out-of-band LLM to use for extraction
414    /// - `prompt`: system instruction describing what to extract
415    /// - `window_size`: how many recent turns to include
416    pub fn new(
417        name: impl Into<String>,
418        llm: Arc<dyn BaseLlm>,
419        prompt: impl Into<String>,
420        window_size: usize,
421    ) -> Self {
422        Self {
423            name: name.into(),
424            llm,
425            prompt: prompt.into(),
426            window_size,
427            schema: None,
428            schema_str: None,
429            min_words: 0,
430            trigger: ExtractionTrigger::EveryTurn,
431            promotion_rules: Vec::new(),
432            thinking_budget: Some(0),
433            budget_step: std::sync::atomic::AtomicU8::new(0),
434        }
435    }
436
437    /// Set the thinking budget sent with each extraction request.
438    ///
439    /// The default is `Some(0)`: extraction reads a few turns, and the turn
440    /// pipeline waits for it, so thinking costs seconds of latency on every
441    /// turn. Measured on `gemini-flash-latest`, a budget of 0 cut a short
442    /// extraction from 7.7 s to 2.3 s with the same results. `None` leaves
443    /// the model's default. When a model rejects a budget of 0 (some only
444    /// work in thinking mode, and `gemini-3.5-flash-lite` needs at least 1),
445    /// the extractor retries with [`FALLBACK_THINKING_BUDGET`], then without
446    /// a budget, and keeps sending the first one the model accepted.
447    pub fn with_thinking_budget(mut self, budget: Option<u32>) -> Self {
448        self.thinking_budget = budget;
449        self
450    }
451
452    /// Set the minimum word count in the last user utterance to trigger extraction.
453    ///
454    /// Turns where the user said fewer than `n` words will skip the LLM call.
455    /// Useful for filtering out "uh huh", "ok", "yes" style responses.
456    pub fn with_min_words(mut self, n: usize) -> Self {
457        self.min_words = n;
458        self
459    }
460
461    /// Set a JSON Schema for structured output.
462    ///
463    /// When set, the schema is included in the prompt to guide the LLM
464    /// toward producing valid JSON matching the schema.
465    pub fn with_schema(mut self, schema: Value) -> Self {
466        self.schema_str = serde_json::to_string_pretty(&schema).ok();
467        self.schema = Some(schema);
468        self
469    }
470
471    /// Set the trigger mode for this extractor.
472    pub fn with_trigger(mut self, trigger: ExtractionTrigger) -> Self {
473        self.trigger = trigger;
474        self
475    }
476
477    /// Set explicit field promotion rules.
478    ///
479    /// Once promotion rules are present, top-level fields are no longer
480    /// automatically flattened into state; only accepted rules promote.
481    pub fn with_promotions(mut self, rules: Vec<FieldPromotion>) -> Self {
482        self.promotion_rules = rules;
483        self
484    }
485
486    /// The values already in state for this extractor's fields, keyed by
487    /// field name: the promotion targets when there are rules, otherwise the
488    /// schema's properties.
489    fn known_fields(&self, state: &State) -> serde_json::Map<String, Value> {
490        let pairs: Vec<(String, String)> = if self.promotion_rules.is_empty() {
491            self.schema
492                .as_ref()
493                .and_then(|s| s.get("properties"))
494                .and_then(Value::as_object)
495                .map(|p| p.keys().map(|k| (k.clone(), k.clone())).collect())
496                .unwrap_or_default()
497        } else {
498            self.promotion_rules
499                .iter()
500                .map(|r| (r.field.clone(), r.state_key.clone()))
501                .collect()
502        };
503        pairs
504            .into_iter()
505            .filter_map(|(field, key)| {
506                state
507                    .get_raw(&key)
508                    .filter(|v| !v.is_null())
509                    .map(|v| (field, v))
510            })
511            .collect()
512    }
513
514    async fn extract_knowing(
515        &self,
516        window: &[TranscriptTurn],
517        known: &serde_json::Map<String, Value>,
518    ) -> Result<Value, LlmError> {
519        let transcript = Self::format_transcript(window);
520        let (preamble, latest, guidance) = if known.is_empty() {
521            (String::new(), String::new(), "")
522        } else {
523            let latest = window
524                .iter()
525                .rev()
526                .map(|t| t.user.trim())
527                .find(|u| !u.is_empty())
528                .unwrap_or_default();
529            (
530                format!("Already known: {}\n\n", Value::Object(known.clone())),
531                format!(
532                    "The user's latest turn: {}\n\n",
533                    Value::String(latest.to_string())
534                ),
535                KNOWN_GUIDANCE,
536            )
537        };
538        let mut request = LlmRequest::from_text(format!(
539            "{preamble}Transcript:\n{transcript}\n{latest}Extract the requested information."
540        ));
541        request.system_instruction = Some(format!("{}{NULL_GUIDANCE}{guidance}", self.prompt));
542
543        // Use native JSON mode when a schema is available — the API constrains
544        // the model to produce valid JSON matching the schema, eliminating
545        // markdown fences and malformed output. Every field may be null:
546        // constrained to a bare type, the model fills fields the transcript
547        // never mentions with placeholders ("unknown", "", 0).
548        if let Some(ref schema) = self.schema {
549            request.response_mime_type = Some("application/json".to_string());
550            request.response_json_schema = Some(nullable_fields(schema));
551        } else {
552            request.response_mime_type = Some("application/json".to_string());
553        }
554
555        let response = self.generate(request).await?;
556        let text = response.text();
557
558        // Fallback: strip markdown code fences if the model still wraps output
559        let cleaned = crate::utils::text::strip_code_fence(&text);
560
561        serde_json::from_str(cleaned).map_err(|e| {
562            LlmError::Other(format!(
563                "Failed to parse extraction result as JSON: {e}. Raw: {text}"
564            ))
565        })
566    }
567
568    /// Send `request` with the thinking budget, falling back without it if
569    /// the model rejects it, and retrying once on a transient error: a lost
570    /// extraction loses what the caller said in that turn.
571    async fn generate(&self, mut request: LlmRequest) -> Result<LlmResponse, LlmError> {
572        use std::sync::atomic::Ordering;
573        loop {
574            let step = self.budget_step.load(Ordering::Relaxed);
575            let budget = match step {
576                0 => self.thinking_budget,
577                1 => Some(FALLBACK_THINKING_BUDGET),
578                _ => None,
579            };
580            request.thinking_budget = budget;
581            match self.llm.generate(request.clone()).await {
582                Err(LlmError::Api { status: 400, .. }) if budget.is_some() => {
583                    let next = if step == 0 && budget != Some(FALLBACK_THINKING_BUDGET) {
584                        1
585                    } else {
586                        2
587                    };
588                    tracing::warn!(
589                        extractor = %self.name,
590                        "the extraction model rejected thinking budget {budget:?}; \
591                         trying {:?}",
592                        if next == 1 { Some(FALLBACK_THINKING_BUDGET) } else { None }
593                    );
594                    self.budget_step.fetch_max(next, Ordering::Relaxed);
595                }
596                Err(e) if e.is_retryable() => {
597                    tracing::warn!(extractor = %self.name, "extraction failed ({e}); retrying once");
598                    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
599                    return self.llm.generate(request).await;
600                }
601                other => return other,
602            }
603        }
604    }
605
606    /// Format transcript turns for the LLM prompt.
607    fn format_transcript(window: &[TranscriptTurn]) -> String {
608        let mut out = String::new();
609        for turn in window {
610            if !turn.user.is_empty() {
611                out.push_str("User: ");
612                out.push_str(turn.user.trim());
613                out.push('\n');
614            }
615            if !turn.model.is_empty() {
616                out.push_str("Assistant: ");
617                out.push_str(turn.model.trim());
618                out.push('\n');
619            }
620            out.push('\n');
621        }
622        out
623    }
624}
625
626#[async_trait]
627impl TurnExtractor for LlmExtractor {
628    fn name(&self) -> &str {
629        &self.name
630    }
631
632    fn window_size(&self) -> usize {
633        self.window_size
634    }
635
636    fn should_extract(&self, window: &[TranscriptTurn]) -> bool {
637        // A turn the caller said nothing in, such as the model speaking a
638        // tool's result, holds no new caller information, and the turn
639        // pipeline waits for every extraction: in live runs each one held up
640        // the next tool call by seconds. Only when the window shows the
641        // caller's words are transcribed at all, so a session without input
642        // transcription still extracts.
643        if self.trigger == ExtractionTrigger::EveryTurn && nothing_new_from_caller(window) {
644            return false;
645        }
646        if self.min_words == 0 {
647            return true;
648        }
649        // Check the last user utterance
650        window
651            .iter()
652            .rev()
653            .find(|t| !t.user.is_empty())
654            .is_some_and(|t| t.user.split_whitespace().count() >= self.min_words)
655    }
656
657    fn trigger(&self) -> ExtractionTrigger {
658        self.trigger.clone()
659    }
660
661    fn promotion_rules(&self) -> &[FieldPromotion] {
662        &self.promotion_rules
663    }
664
665    fn may_write(&self, key: &str) -> bool {
666        // Without rules every top-level field is promoted under its own
667        // name; the schema says which fields there are.
668        if self.promotion_rules.is_empty()
669            && let Some(properties) = self
670                .schema
671                .as_ref()
672                .and_then(|s| s.get("properties"))
673                .and_then(Value::as_object)
674        {
675            return properties.contains_key(key);
676        }
677        self.promotion_rules.is_empty() || self.promotion_rules.iter().any(|r| r.state_key == key)
678    }
679
680    async fn extract(&self, window: &[TranscriptTurn]) -> Result<Value, LlmError> {
681        self.extract_knowing(window, &serde_json::Map::new()).await
682    }
683
684    /// Extract, telling the model which fields are already known so it
685    /// returns only what the latest turn adds or changes.
686    async fn extract_with_state(
687        &self,
688        window: &[TranscriptTurn],
689        state: &State,
690    ) -> Result<Value, LlmError> {
691        self.extract_knowing(window, &self.known_fields(state))
692            .await
693    }
694}
695
696#[cfg(test)]
697mod tests {
698    use super::*;
699    use crate::llm::{LlmResponse, MockLlm};
700    use gemini_genai_rs::prelude::{Content, Part, Role};
701    use std::time::Instant;
702
703    fn make_turns(pairs: &[(&str, &str)]) -> Vec<TranscriptTurn> {
704        pairs
705            .iter()
706            .enumerate()
707            .map(|(i, (user, model))| TranscriptTurn {
708                turn_number: i as u32,
709                user: user.to_string(),
710                model: model.to_string(),
711                tool_calls: Vec::new(),
712                timestamp: Instant::now(),
713            })
714            .collect()
715    }
716
717    #[tokio::test]
718    async fn llm_extractor_produces_json() {
719        let llm = Arc::new(MockLlm::text(
720            r#"{"phase": "ordering", "items": ["pizza"]}"#,
721        ));
722
723        let extractor = LlmExtractor::new("OrderState", llm, "Extract order state", 3);
724
725        let turns = make_turns(&[
726            ("I'd like a pizza", "Great! What size?"),
727            ("Large please", "Coming right up!"),
728        ]);
729
730        let result = extractor.extract(&turns).await.unwrap();
731        assert_eq!(result["phase"], "ordering");
732        assert_eq!(result["items"][0], "pizza");
733    }
734
735    #[tokio::test]
736    async fn llm_extractor_with_schema() {
737        let llm = Arc::new(MockLlm::text(r#"{"sentiment": "positive", "score": 0.9}"#));
738
739        let schema = serde_json::json!({
740            "type": "object",
741            "properties": {
742                "sentiment": {"type": "string", "enum": ["positive", "neutral", "negative"]},
743                "score": {"type": "number"}
744            }
745        });
746
747        let extractor =
748            LlmExtractor::new("Sentiment", llm, "Rate sentiment", 1).with_schema(schema);
749
750        let turns = make_turns(&[("This is great!", "Glad you think so!")]);
751        let result = extractor.extract(&turns).await.unwrap();
752        assert_eq!(result["sentiment"], "positive");
753    }
754
755    #[tokio::test]
756    async fn llm_extractor_invalid_json_returns_error() {
757        let llm = Arc::new(MockLlm::text("not json at all"));
758
759        let extractor = LlmExtractor::new("Bad", llm, "Extract", 1);
760        let turns = make_turns(&[("hi", "hello")]);
761        let result = extractor.extract(&turns).await;
762        assert!(result.is_err());
763    }
764
765    #[test]
766    fn format_transcript_readable() {
767        let turns = make_turns(&[("Hello", "Hi there!"), ("How are you?", "I'm doing well")]);
768        let formatted = LlmExtractor::format_transcript(&turns);
769        assert!(formatted.contains("User: Hello"));
770        assert!(formatted.contains("Assistant: Hi there!"));
771        assert!(formatted.contains("User: How are you?"));
772    }
773
774    #[tokio::test]
775    async fn llm_extractor_handles_markdown_fenced_json() {
776        let llm = Arc::new(MockLlm::text("```json\n{\"status\": \"ok\"}\n```"));
777
778        let extractor = LlmExtractor::new("Fenced", llm, "Extract", 1);
779        let turns = make_turns(&[("test", "reply")]);
780        let result = extractor.extract(&turns).await.unwrap();
781        assert_eq!(result["status"], "ok");
782    }
783
784    #[test]
785    fn every_field_of_the_extraction_schema_may_be_null() {
786        let schema = serde_json::json!({
787            "type": "object",
788            "properties": {
789                "party_size": { "type": "integer" },
790                "slot": { "type": ["string"] },
791                "kind": { "enum": ["a", "b"] },
792                "note": { "type": ["string", "null"] }
793            }
794        });
795        let nullable = nullable_fields(&schema);
796        let props = &nullable["properties"];
797        assert_eq!(
798            props["party_size"]["type"],
799            serde_json::json!(["integer", "null"])
800        );
801        assert_eq!(props["slot"]["type"], serde_json::json!(["string", "null"]));
802        assert_eq!(
803            props["kind"]["anyOf"],
804            serde_json::json!([{ "enum": ["a", "b"] }, { "type": "null" }])
805        );
806        assert_eq!(props["note"]["type"], serde_json::json!(["string", "null"]));
807        // A schema without properties is left alone.
808        assert_eq!(
809            nullable_fields(&serde_json::json!({ "type": "object" })),
810            serde_json::json!({ "type": "object" })
811        );
812    }
813
814    #[tokio::test]
815    async fn the_extraction_request_allows_and_asks_for_null() {
816        struct Capture(parking_lot::Mutex<Option<LlmRequest>>);
817        #[async_trait]
818        impl BaseLlm for Capture {
819            fn model_id(&self) -> &str {
820                "capture"
821            }
822            async fn generate(&self, request: LlmRequest) -> Result<LlmResponse, LlmError> {
823                *self.0.lock() = Some(request);
824                Ok(LlmResponse {
825                    content: Content {
826                        role: Some(Role::Model),
827                        parts: vec![Part::Text { text: "{}".into() }],
828                    },
829                    finish_reason: Some("STOP".into()),
830                    usage: None,
831                })
832            }
833        }
834        let llm = Arc::new(Capture(parking_lot::Mutex::new(None)));
835        let extractor = LlmExtractor::new("booking", llm.clone(), "Extract the booking.", 3)
836            .with_schema(serde_json::json!({
837                "type": "object",
838                "properties": { "party_size": { "type": "integer" } }
839            }));
840        extractor
841            .extract(&make_turns(&[("hi", "hello")]))
842            .await
843            .unwrap();
844        let request = llm.0.lock().take().unwrap();
845        assert_eq!(
846            request.response_json_schema.unwrap()["properties"]["party_size"]["type"],
847            serde_json::json!(["integer", "null"])
848        );
849        let system = request.system_instruction.unwrap();
850        assert!(system.starts_with("Extract the booking."));
851        assert!(system.contains("Use null for any field the transcript does not state"));
852    }
853
854    #[tokio::test]
855    async fn known_fields_are_sent_with_the_transcript() {
856        struct Capture(parking_lot::Mutex<Vec<LlmRequest>>);
857        #[async_trait]
858        impl BaseLlm for Capture {
859            fn model_id(&self) -> &str {
860                "capture"
861            }
862            async fn generate(&self, request: LlmRequest) -> Result<LlmResponse, LlmError> {
863                self.0.lock().push(request);
864                Ok(LlmResponse {
865                    content: Content {
866                        role: Some(Role::Model),
867                        parts: vec![Part::Text { text: "{}".into() }],
868                    },
869                    finish_reason: Some("STOP".into()),
870                    usage: None,
871                })
872            }
873        }
874        let llm = Arc::new(Capture(parking_lot::Mutex::new(Vec::new())));
875        let extractor = LlmExtractor::new("booking", llm.clone(), "Extract the booking.", 3)
876            .with_promotions(vec![
877                FieldPromotion::overwrite("party_size"),
878                FieldPromotion::overwrite("slot").to("requested_slot"),
879            ]);
880        let state = State::new();
881        let window = make_turns(&[("seven is perfect", "great")]);
882
883        // Nothing known yet: no preamble and no known-field guidance.
884        extractor.extract_with_state(&window, &state).await.unwrap();
885        // Known values are listed by field name, read from their state keys.
886        let _ = state.set("party_size", 4);
887        let _ = state.set("requested_slot", "tomorrow at 7 pm");
888        extractor.extract_with_state(&window, &state).await.unwrap();
889
890        let requests = llm.0.lock();
891        let text = |r: &LlmRequest| {
892            r.contents[0]
893                .parts
894                .iter()
895                .filter_map(|p| match p {
896                    Part::Text { text } => Some(text.clone()),
897                    _ => None,
898                })
899                .collect::<String>()
900        };
901        assert!(text(&requests[0]).starts_with("Transcript:"));
902        assert!(
903            !requests[0]
904                .system_instruction
905                .as_ref()
906                .unwrap()
907                .contains("already known")
908        );
909        let second = text(&requests[1]);
910        assert!(second.starts_with("Already known: "), "{second}");
911        assert!(
912            second.contains("The user's latest turn: \"seven is perfect\""),
913            "{second}"
914        );
915        assert!(!text(&requests[0]).contains("latest turn"));
916        assert!(
917            second.contains(r#""party_size":4"#) && second.contains(r#""slot":"tomorrow at 7 pm""#)
918        );
919        assert!(
920            requests[1]
921                .system_instruction
922                .as_ref()
923                .unwrap()
924                .contains("Some fields are already known")
925        );
926    }
927
928    #[test]
929    fn a_restated_value_is_not_promoted_again() {
930        let llm = Arc::new(MockLlm::text("{}"));
931        let extractor = LlmExtractor::new("booking", llm, "x", 3)
932            .with_promotions(vec![FieldPromotion::overwrite("slot")]);
933        let state = State::new();
934        let _ = state.set("slot", "tomorrow at 7 pm");
935        let before = state.get_raw("slot");
936        let events = promote_fields(
937            &extractor,
938            "booking",
939            &serde_json::json!({ "slot": "Tomorrow at 7 PM." }),
940            &state,
941        );
942        assert_eq!(state.get_raw("slot"), before, "the known wording is kept");
943        assert!(events.iter().any(|e| matches!(
944            e,
945            PromotionEvent::Decision { accepted: false, reason, .. }
946                if reason == "an equivalent value is already known"
947        )));
948
949        // A different value is still promoted.
950        promote_fields(
951            &extractor,
952            "booking",
953            &serde_json::json!({ "slot": "8 pm" }),
954            &state,
955        );
956        assert_eq!(state.get::<String>("slot").as_deref(), Some("8 pm"));
957    }
958
959    #[test]
960    fn extractor_name_and_window_size() {
961        let llm = Arc::new(MockLlm::text("{}"));
962        let ext = LlmExtractor::new("TestExtractor", llm, "test", 5);
963        assert_eq!(ext.name(), "TestExtractor");
964        assert_eq!(ext.window_size(), 5);
965    }
966
967    #[test]
968    fn extractor_default_trigger_is_every_turn() {
969        let llm = Arc::new(MockLlm::text("{}"));
970        let ext = LlmExtractor::new("Test", llm, "test", 5);
971        assert_eq!(ext.trigger(), ExtractionTrigger::EveryTurn);
972    }
973
974    #[test]
975    fn extractor_with_trigger() {
976        let llm = Arc::new(MockLlm::text("{}"));
977        let ext = LlmExtractor::new("Test", llm, "test", 5)
978            .with_trigger(ExtractionTrigger::AfterToolCall);
979        assert_eq!(ext.trigger(), ExtractionTrigger::AfterToolCall);
980    }
981
982    /// Answers with each scripted result in turn and records every request.
983    struct Scripted {
984        replies: parking_lot::Mutex<Vec<Result<&'static str, LlmError>>>,
985        requests: parking_lot::Mutex<Vec<LlmRequest>>,
986    }
987
988    impl Scripted {
989        fn new(replies: Vec<Result<&'static str, LlmError>>) -> Arc<Self> {
990            Arc::new(Self {
991                replies: parking_lot::Mutex::new(replies),
992                requests: parking_lot::Mutex::new(Vec::new()),
993            })
994        }
995        fn budgets(&self) -> Vec<Option<u32>> {
996            self.requests
997                .lock()
998                .iter()
999                .map(|r| r.thinking_budget)
1000                .collect()
1001        }
1002    }
1003
1004    #[async_trait]
1005    impl BaseLlm for Scripted {
1006        fn model_id(&self) -> &str {
1007            "scripted"
1008        }
1009        async fn generate(&self, request: LlmRequest) -> Result<LlmResponse, LlmError> {
1010            self.requests.lock().push(request);
1011            let text = self.replies.lock().remove(0)?;
1012            Ok(LlmResponse {
1013                content: Content {
1014                    role: Some(Role::Model),
1015                    parts: vec![Part::Text { text: text.into() }],
1016                },
1017                finish_reason: Some("STOP".into()),
1018                usage: None,
1019            })
1020        }
1021    }
1022
1023    fn bad_request() -> LlmError {
1024        LlmError::Api {
1025            status: 400,
1026            message: "Budget 0 is invalid. This model only works in thinking mode.".into(),
1027        }
1028    }
1029
1030    #[tokio::test]
1031    async fn extraction_does_not_think_by_default() {
1032        let llm = Scripted::new(vec![Ok("{}")]);
1033        let extractor = LlmExtractor::new("x", llm.clone(), "Extract.", 2);
1034        extractor
1035            .extract(&make_turns(&[("hi", "hello")]))
1036            .await
1037            .unwrap();
1038        assert_eq!(llm.budgets(), [Some(0)]);
1039
1040        let llm = Scripted::new(vec![Ok("{}")]);
1041        let extractor =
1042            LlmExtractor::new("x", llm.clone(), "Extract.", 2).with_thinking_budget(None);
1043        extractor
1044            .extract(&make_turns(&[("hi", "hello")]))
1045            .await
1046            .unwrap();
1047        assert_eq!(llm.budgets(), [None], "None leaves the model's default");
1048    }
1049
1050    #[tokio::test]
1051    async fn a_rejected_budget_of_zero_falls_back_to_the_smallest_accepted() {
1052        let llm = Scripted::new(vec![Err(bad_request()), Ok(r#"{"a": 1}"#), Ok("{}")]);
1053        let extractor = LlmExtractor::new("x", llm.clone(), "Extract.", 2);
1054        let window = make_turns(&[("hi", "hello")]);
1055        assert_eq!(extractor.extract(&window).await.unwrap()["a"], 1);
1056        extractor.extract(&window).await.unwrap();
1057        assert_eq!(
1058            llm.budgets(),
1059            [
1060                Some(0),
1061                Some(FALLBACK_THINKING_BUDGET),
1062                Some(FALLBACK_THINKING_BUDGET)
1063            ],
1064            "the accepted fallback is kept"
1065        );
1066    }
1067
1068    #[tokio::test]
1069    async fn a_model_that_rejects_every_budget_gets_none() {
1070        let llm = Scripted::new(vec![
1071            Err(bad_request()),
1072            Err(bad_request()),
1073            Ok(r#"{"a": 1}"#),
1074            Ok("{}"),
1075        ]);
1076        let extractor = LlmExtractor::new("x", llm.clone(), "Extract.", 2);
1077        let window = make_turns(&[("hi", "hello")]);
1078        assert_eq!(extractor.extract(&window).await.unwrap()["a"], 1);
1079        extractor.extract(&window).await.unwrap();
1080        assert_eq!(
1081            llm.budgets(),
1082            [Some(0), Some(FALLBACK_THINKING_BUDGET), None, None]
1083        );
1084
1085        // A configured budget the model rejects goes straight to none when it
1086        // is the fallback already.
1087        let llm = Scripted::new(vec![Err(bad_request()), Ok("{}")]);
1088        let extractor = LlmExtractor::new("x", llm.clone(), "Extract.", 2)
1089            .with_thinking_budget(Some(FALLBACK_THINKING_BUDGET));
1090        extractor.extract(&window).await.unwrap();
1091        assert_eq!(llm.budgets(), [Some(FALLBACK_THINKING_BUDGET), None]);
1092    }
1093
1094    #[tokio::test]
1095    async fn a_bad_request_without_a_budget_is_not_retried() {
1096        let llm = Scripted::new(vec![Err(bad_request())]);
1097        let extractor =
1098            LlmExtractor::new("x", llm.clone(), "Extract.", 2).with_thinking_budget(None);
1099        assert!(
1100            extractor
1101                .extract(&make_turns(&[("hi", "hello")]))
1102                .await
1103                .is_err()
1104        );
1105        assert_eq!(llm.requests.lock().len(), 1);
1106    }
1107
1108    #[tokio::test]
1109    async fn a_transient_failure_is_retried_once() {
1110        let unavailable = || LlmError::Api {
1111            status: 503,
1112            message: "Service Unavailable".into(),
1113        };
1114        let llm = Scripted::new(vec![Err(unavailable()), Ok(r#"{"a": 1}"#)]);
1115        let extractor = LlmExtractor::new("x", llm.clone(), "Extract.", 2);
1116        let window = make_turns(&[("hi", "hello")]);
1117        assert_eq!(extractor.extract(&window).await.unwrap()["a"], 1);
1118
1119        let llm = Scripted::new(vec![Err(unavailable()), Err(unavailable())]);
1120        let extractor = LlmExtractor::new("x", llm.clone(), "Extract.", 2);
1121        assert!(extractor.extract(&window).await.is_err());
1122        assert_eq!(llm.requests.lock().len(), 2, "one retry, not more");
1123    }
1124
1125    #[test]
1126    fn may_write_follows_the_rules_or_the_schema() {
1127        let llm = Scripted::new(vec![]);
1128        let with_rules = LlmExtractor::new("x", llm.clone(), "Extract.", 2)
1129            .with_promotions(vec![FieldPromotion::true_only("ok").to("confirmed")]);
1130        assert!(with_rules.may_write("confirmed"));
1131        assert!(!with_rules.may_write("ok"));
1132
1133        let flattened = LlmExtractor::new("x", llm.clone(), "Extract.", 2).with_schema(
1134            serde_json::json!({ "type": "object", "properties": { "confirmed": { "type": "boolean" } } }),
1135        );
1136        assert!(flattened.may_write("confirmed"));
1137        assert!(!flattened.may_write("slot"));
1138
1139        let unknown = LlmExtractor::new("x", llm, "Extract.", 2);
1140        assert!(
1141            unknown.may_write("anything"),
1142            "no schema, no rules: it may write any key"
1143        );
1144    }
1145
1146    #[test]
1147    fn a_turn_without_the_caller_is_not_extracted() {
1148        let llm = Scripted::new(vec![]);
1149        let extractor = LlmExtractor::new("x", llm, "Extract.", 3);
1150        // The model speaks a tool's result: nothing new from the caller.
1151        assert!(!extractor.should_extract(&make_turns(&[
1152            ("Four at seven.", "Let me check."),
1153            ("", "Seven is free."),
1154        ])));
1155        assert!(extractor.should_extract(&make_turns(&[
1156            ("", "Seven is free."),
1157            ("Book it.", "Done."),
1158        ])));
1159        // No caller words anywhere: transcription may be off, so extract.
1160        assert!(extractor.should_extract(&make_turns(&[("", "Hello.")])));
1161        // Extractors that read the model's own words still run.
1162        let on_generation = LlmExtractor::new("y", Scripted::new(vec![]), "Extract.", 3)
1163            .with_trigger(ExtractionTrigger::OnGenerationComplete);
1164        assert!(on_generation.should_extract(&make_turns(&[
1165            ("Four at seven.", "Let me check."),
1166            ("", "Seven is free."),
1167        ])));
1168    }
1169}