1use 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
62pub const LLM_CALL: &str = "llm";
64
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
67pub struct TapeEntry {
68 pub kind: String,
70 pub input: String,
72 pub output: Result<Value, String>,
74}
75
76pub trait Tape: Send + Sync {
78 fn record(&self, entry: TapeEntry);
80
81 fn next(&self, kind: &str, input: &str) -> Option<Result<Value, String>>;
84}
85
86#[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#[derive(Debug, Default)]
111pub struct MemoryTape {
112 queues: Mutex<Queues>,
113}
114
115impl MemoryTape {
116 pub fn new() -> Self {
118 Self::default()
119 }
120
121 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 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#[derive(Debug)]
152pub struct FileTape {
153 path: PathBuf,
154 queues: Mutex<Queues>,
155 writer: Mutex<BufWriter<File>>,
156}
157
158impl FileTape {
159 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 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 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
220pub 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
235pub struct TapedLlm<L = Arc<dyn BaseLlm>> {
238 mode: Mode<L>,
239 tape: Arc<dyn Tape>,
240}
241
242impl<L: BaseLlm> TapedLlm<L> {
243 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
321pub enum TapeMode {
322 Record,
324 Replay,
326}
327
328pub 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}