Skip to main content

gemini_adk_rs/
tape.rs

1//! Record model and resolver outputs once; replay them without the network.
2//!
3//! [`replay_session`](crate::live::replay::replay_session) re-drives a
4//! recorded Live session through the real control plane, but anything that
5//! calls a model or a remote service out of band still runs for real:
6//!
7//! - an LLM extractor;
8//! - an async resolver behind a slot;
9//! - a background agent.
10//!
11//! A replay would then cost money, need credentials, and could answer
12//! differently. A [`Tape`] closes that gap. While recording, every call's
13//! input and output are appended to it. While replaying, calls are answered
14//! from it, in the order they were recorded, and nothing leaves the process.
15//!
16//! - [`TapedLlm`] wraps any [`BaseLlm`]. [`TapedLlm::recording`] passes calls
17//!   through and records them; [`TapedLlm::replaying`] needs no inner model
18//!   and no credentials.
19//! - [`taped_resolver`] wraps a resolver's `fetch` the same way, for
20//!   `Extract::field_resolve` and `Conversation::resolve_slot`.
21//!
22//! Calls are matched on their canonical JSON input: the request, or the
23//! resolver's name and arguments. The same input recorded twice replays its
24//! two outputs in order. A replay that asks for something the tape does not
25//! hold fails loudly rather than calling out.
26//!
27//! ```
28//! # async fn demo() -> Result<(), Box<dyn std::error::Error>> {
29//! use std::sync::Arc;
30//! use gemini_adk_rs::llm::{BaseLlm, LlmRequest, LlmResponse, MockLlm};
31//! use gemini_adk_rs::tape::{MemoryTape, TapedLlm};
32//!
33//! let tape = Arc::new(MemoryTape::new());
34//!
35//! // Record against a real (here: scripted) model.
36//! let live = TapedLlm::recording(MockLlm::script([LlmResponse::from_text("Paris")]), tape.clone());
37//! live.generate(LlmRequest::from_text("Capital of France?")).await?;
38//!
39//! // Replay with no model at all.
40//! let offline = TapedLlm::replaying("gemini-2.5-flash", tape);
41//! let reply = offline.generate(LlmRequest::from_text("Capital of France?")).await?;
42//! assert_eq!(reply.text(), "Paris");
43//! # Ok(())
44//! # }
45//! ```
46
47use std::collections::{HashMap, VecDeque};
48use std::fs::{File, OpenOptions};
49use std::future::Future;
50use std::io::{BufRead, BufReader, BufWriter, Write};
51use std::path::{Path, PathBuf};
52use std::sync::Arc;
53
54use async_trait::async_trait;
55use parking_lot::Mutex;
56use serde::{Deserialize, Serialize};
57use serde_json::Value;
58
59use crate::llm::{BaseLlm, LlmError, LlmRequest, LlmResponse, ModelCapabilities};
60use crate::utils::text::truncate_chars;
61
62/// The kind of call a [`TapeEntry`] records.
63pub const LLM_CALL: &str = "llm";
64
65/// One recorded call: what went in and what came out.
66#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
67pub struct TapeEntry {
68    /// What kind of call this was: [`LLM_CALL`], or `resolver:{name}`.
69    pub kind: String,
70    /// The call's input as canonical JSON (object keys sorted).
71    pub input: String,
72    /// The call's output, or the error message it failed with.
73    pub output: Result<Value, String>,
74}
75
76/// Where recorded calls are kept.
77pub trait Tape: Send + Sync {
78    /// Append a call.
79    fn record(&self, entry: TapeEntry);
80
81    /// Take the next unreplayed output recorded for `kind` and `input`, in
82    /// recording order. `None` when the tape holds no (more) such call.
83    fn next(&self, kind: &str, input: &str) -> Option<Result<Value, String>>;
84}
85
86/// Recorded calls, queued per `(kind, input)` for replay.
87#[derive(Debug, Default)]
88struct Queues {
89    entries: Vec<TapeEntry>,
90    pending: HashMap<(String, String), VecDeque<Result<Value, String>>>,
91}
92
93impl Queues {
94    fn push(&mut self, entry: TapeEntry) {
95        self.pending
96            .entry((entry.kind.clone(), entry.input.clone()))
97            .or_default()
98            .push_back(entry.output.clone());
99        self.entries.push(entry);
100    }
101
102    fn next(&mut self, kind: &str, input: &str) -> Option<Result<Value, String>> {
103        self.pending
104            .get_mut(&(kind.to_string(), input.to_string()))?
105            .pop_front()
106    }
107}
108
109/// A tape held in memory.
110#[derive(Debug, Default)]
111pub struct MemoryTape {
112    queues: Mutex<Queues>,
113}
114
115impl MemoryTape {
116    /// An empty tape.
117    pub fn new() -> Self {
118        Self::default()
119    }
120
121    /// A tape holding `entries`, ready to replay.
122    pub fn from_entries(entries: impl IntoIterator<Item = TapeEntry>) -> Self {
123        let tape = Self::new();
124        for entry in entries {
125            tape.record(entry);
126        }
127        tape
128    }
129
130    /// Every call recorded so far, in order.
131    pub fn entries(&self) -> Vec<TapeEntry> {
132        self.queues.lock().entries.clone()
133    }
134}
135
136impl Tape for MemoryTape {
137    fn record(&self, entry: TapeEntry) {
138        self.queues.lock().push(entry);
139    }
140
141    fn next(&self, kind: &str, input: &str) -> Option<Result<Value, String>> {
142        self.queues.lock().next(kind, input)
143    }
144}
145
146/// A tape kept in a JSONL file, one [`TapeEntry`] per line.
147///
148/// [`FileTape::create`] starts an empty file to record into.
149/// [`FileTape::open`] loads an existing one for replay. Any calls recorded
150/// after that are appended to the same file.
151#[derive(Debug)]
152pub struct FileTape {
153    path: PathBuf,
154    queues: Mutex<Queues>,
155    writer: Mutex<BufWriter<File>>,
156}
157
158impl FileTape {
159    /// Create (or truncate) `path` and record into it.
160    pub fn create(path: impl AsRef<Path>) -> std::io::Result<Self> {
161        let path = path.as_ref().to_path_buf();
162        let file = File::create(&path)?;
163        Ok(Self {
164            path,
165            queues: Mutex::new(Queues::default()),
166            writer: Mutex::new(BufWriter::new(file)),
167        })
168    }
169
170    /// Load the calls recorded in `path`, ready to replay.
171    pub fn open(path: impl AsRef<Path>) -> std::io::Result<Self> {
172        let path = path.as_ref().to_path_buf();
173        let mut queues = Queues::default();
174        for (n, line) in BufReader::new(File::open(&path)?).lines().enumerate() {
175            let line = line?;
176            if line.trim().is_empty() {
177                continue;
178            }
179            let entry: TapeEntry = serde_json::from_str(&line).map_err(|e| {
180                std::io::Error::new(
181                    std::io::ErrorKind::InvalidData,
182                    format!("{}:{}: {e}", path.display(), n + 1),
183                )
184            })?;
185            queues.push(entry);
186        }
187        let file = OpenOptions::new().append(true).open(&path)?;
188        Ok(Self {
189            path,
190            queues: Mutex::new(queues),
191            writer: Mutex::new(BufWriter::new(file)),
192        })
193    }
194
195    /// The file this tape reads and writes.
196    pub fn path(&self) -> &Path {
197        &self.path
198    }
199}
200
201impl Tape for FileTape {
202    fn record(&self, entry: TapeEntry) {
203        match serde_json::to_string(&entry) {
204            Ok(line) => {
205                let mut writer = self.writer.lock();
206                if let Err(e) = writeln!(writer, "{line}").and_then(|()| writer.flush()) {
207                    tracing::warn!(path = %self.path.display(), "tape write failed: {e}");
208                }
209            }
210            Err(e) => tracing::warn!("tape entry not serializable: {e}"),
211        }
212        self.queues.lock().push(entry);
213    }
214
215    fn next(&self, kind: &str, input: &str) -> Option<Result<Value, String>> {
216        self.queues.lock().next(kind, input)
217    }
218}
219
220/// Canonical JSON for `value`: object keys sorted, no whitespace.
221///
222/// Values that fail to serialize fall back to their `Debug` form, so a key is
223/// always produced.
224pub fn canonical_json(value: &impl Serialize) -> String {
225    serde_json::to_value(value)
226        .map(|v| v.to_string())
227        .unwrap_or_else(|e| format!("<unserializable: {e}>"))
228}
229
230enum Mode<L> {
231    Recording(L),
232    Replaying { model_id: String },
233}
234
235/// A [`BaseLlm`] that records its calls to a [`Tape`] or answers them from
236/// one. See the [module docs](self).
237pub struct TapedLlm<L = Arc<dyn BaseLlm>> {
238    mode: Mode<L>,
239    tape: Arc<dyn Tape>,
240}
241
242impl<L: BaseLlm> TapedLlm<L> {
243    /// Pass every call through to `inner` and record it on `tape`.
244    pub fn recording(inner: L, tape: Arc<dyn Tape>) -> Self {
245        Self {
246            mode: Mode::Recording(inner),
247            tape,
248        }
249    }
250}
251
252impl TapedLlm {
253    /// Answer every call from `tape`. No model, network or credential is
254    /// used; a call the tape does not hold fails with [`LlmError::Config`].
255    pub fn replaying(model_id: impl Into<String>, tape: Arc<dyn Tape>) -> Self {
256        Self {
257            mode: Mode::Replaying {
258                model_id: model_id.into(),
259            },
260            tape,
261        }
262    }
263}
264
265#[async_trait]
266impl<L: BaseLlm> BaseLlm for TapedLlm<L> {
267    fn model_id(&self) -> &str {
268        match &self.mode {
269            Mode::Recording(inner) => inner.model_id(),
270            Mode::Replaying { model_id } => model_id,
271        }
272    }
273
274    fn capabilities(&self) -> ModelCapabilities {
275        match &self.mode {
276            Mode::Recording(inner) => inner.capabilities(),
277            Mode::Replaying { model_id } => ModelCapabilities::infer_from_id(model_id),
278        }
279    }
280
281    async fn generate(&self, request: LlmRequest) -> Result<LlmResponse, LlmError> {
282        let input = canonical_json(&request);
283        match &self.mode {
284            Mode::Recording(inner) => {
285                let result = inner.generate(request).await;
286                let output = match &result {
287                    Ok(response) => {
288                        serde_json::to_value(response).map_err(|e| format!("unserializable: {e}"))
289                    }
290                    Err(e) => Err(e.to_string()),
291                };
292                self.tape.record(TapeEntry {
293                    kind: LLM_CALL.into(),
294                    input,
295                    output,
296                });
297                result
298            }
299            Mode::Replaying { .. } => match self.tape.next(LLM_CALL, &input) {
300                Some(Ok(value)) => serde_json::from_value(value)
301                    .map_err(|e| LlmError::Other(format!("taped response unreadable: {e}"))),
302                Some(Err(message)) => Err(LlmError::Other(message)),
303                None => Err(LlmError::Config(format!(
304                    "the replay tape holds no (more) recorded call for this request: {}",
305                    truncate_chars(&input, 200)
306                ))),
307            },
308        }
309    }
310
311    async fn warm_up(&self) -> Result<(), LlmError> {
312        match &self.mode {
313            Mode::Recording(inner) => inner.warm_up().await,
314            Mode::Replaying { .. } => Ok(()),
315        }
316    }
317}
318
319/// Whether a [`taped_resolver`] records calls or answers them from the tape.
320#[derive(Debug, Clone, Copy, PartialEq, Eq)]
321pub enum TapeMode {
322    /// Call through and record.
323    Record,
324    /// Answer from the tape; never call through.
325    Replay,
326}
327
328/// Wrap a resolver's `fetch` so its calls are recorded on, or answered from,
329/// `tape`.
330///
331/// `name` scopes the recording (use the field or slot name), so two
332/// resolvers given the same arguments do not answer for each other. The
333/// result has the shape `Extract::field_resolve` and
334/// `Conversation::resolve_slot` take.
335pub fn taped_resolver<F, Fut>(
336    tape: Arc<dyn Tape>,
337    mode: TapeMode,
338    name: impl Into<String>,
339    fetch: F,
340) -> impl Fn(Value) -> std::pin::Pin<Box<dyn Future<Output = Result<Value, String>> + Send>>
341+ Send
342+ Sync
343+ 'static
344where
345    F: Fn(Value) -> Fut + Send + Sync + 'static,
346    Fut: Future<Output = Result<Value, String>> + Send + 'static,
347{
348    let kind = format!("resolver:{}", name.into());
349    let fetch = Arc::new(fetch);
350    move |args: Value| {
351        let tape = tape.clone();
352        let kind = kind.clone();
353        let fetch = fetch.clone();
354        Box::pin(async move {
355            let input = canonical_json(&args);
356            match mode {
357                TapeMode::Record => {
358                    let output = fetch(args).await;
359                    tape.record(TapeEntry {
360                        kind,
361                        input,
362                        output: output.clone(),
363                    });
364                    output
365                }
366                TapeMode::Replay => tape.next(&kind, &input).unwrap_or_else(|| {
367                    Err(format!(
368                        "the replay tape holds no (more) recorded {kind} call for {}",
369                        truncate_chars(&input, 200)
370                    ))
371                }),
372            }
373        })
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380    use crate::llm::MockLlm;
381    use serde_json::json;
382
383    #[tokio::test]
384    async fn a_replay_answers_in_recorded_order_without_the_model() {
385        let tape = Arc::new(MemoryTape::new());
386        let live = TapedLlm::recording(
387            MockLlm::script([LlmResponse::from_text("one"), LlmResponse::from_text("two")]),
388            tape.clone(),
389        );
390        let ask = || LlmRequest::from_text("again?");
391        assert_eq!(live.generate(ask()).await.unwrap().text(), "one");
392        assert_eq!(live.generate(ask()).await.unwrap().text(), "two");
393
394        let offline = TapedLlm::replaying("m", Arc::new(MemoryTape::from_entries(tape.entries())));
395        assert_eq!(offline.generate(ask()).await.unwrap().text(), "one");
396        assert_eq!(offline.generate(ask()).await.unwrap().text(), "two");
397        let exhausted = offline.generate(ask()).await.unwrap_err();
398        assert!(matches!(exhausted, LlmError::Config(_)), "{exhausted}");
399    }
400
401    #[tokio::test]
402    async fn a_replay_refuses_a_request_it_never_saw() {
403        let offline = TapedLlm::replaying("m", Arc::new(MemoryTape::new()));
404        let err = offline
405            .generate(LlmRequest::from_text("unseen"))
406            .await
407            .unwrap_err();
408        assert!(err.to_string().contains("no (more) recorded call"), "{err}");
409    }
410
411    #[tokio::test]
412    async fn a_recorded_failure_replays_as_a_failure() {
413        let tape = Arc::new(MemoryTape::new());
414        let failing = TapedLlm::recording(
415            MockLlm::from_fn(|_| Err(LlmError::RateLimited)),
416            tape.clone(),
417        );
418        assert!(failing.generate(LlmRequest::from_text("x")).await.is_err());
419
420        let offline = TapedLlm::replaying("m", tape);
421        let err = offline
422            .generate(LlmRequest::from_text("x"))
423            .await
424            .unwrap_err();
425        assert_eq!(err.to_string(), "Rate limited");
426    }
427
428    #[tokio::test]
429    async fn a_resolver_replays_per_name_and_arguments() {
430        let tape: Arc<dyn Tape> = Arc::new(MemoryTape::new());
431        let record = taped_resolver(
432            tape.clone(),
433            TapeMode::Record,
434            "balance",
435            |args| async move { Ok(json!({ "for": args["account"], "cents": 1200 })) },
436        );
437        let recorded = record(json!({ "account": "A1" })).await.unwrap();
438
439        let replay = taped_resolver(tape.clone(), TapeMode::Replay, "balance", |_| async {
440            Err::<Value, _>("must not be called".to_string())
441        });
442        assert_eq!(replay(json!({ "account": "A1" })).await.unwrap(), recorded);
443        assert!(replay(json!({ "account": "B2" })).await.is_err());
444
445        let other = taped_resolver(tape, TapeMode::Replay, "limit", |_| async {
446            Err::<Value, _>("must not be called".to_string())
447        });
448        assert!(other(json!({ "account": "A1" })).await.is_err());
449    }
450
451    #[test]
452    fn canonical_json_sorts_keys() {
453        assert_eq!(
454            canonical_json(&json!({ "b": 1, "a": { "d": 2, "c": 3 } })),
455            r#"{"a":{"c":3,"d":2},"b":1}"#
456        );
457    }
458
459    #[test]
460    fn a_file_tape_round_trips() {
461        let path = std::env::temp_dir().join(format!(
462            "gemini-adk-tape-{}-{}.jsonl",
463            std::process::id(),
464            std::time::SystemTime::now()
465                .duration_since(std::time::UNIX_EPOCH)
466                .unwrap()
467                .as_nanos()
468        ));
469        {
470            let tape = FileTape::create(&path).unwrap();
471            tape.record(TapeEntry {
472                kind: "resolver:x".into(),
473                input: "{}".into(),
474                output: Ok(json!(7)),
475            });
476        }
477        let tape = FileTape::open(&path).unwrap();
478        assert_eq!(tape.next("resolver:x", "{}"), Some(Ok(json!(7))));
479        assert_eq!(tape.next("resolver:x", "{}"), None);
480        std::fs::remove_file(path).unwrap();
481    }
482}