transcript_persistence/
transcript_persistence.rs

1// Example: Persisting and restoring session transcripts
2//
3// This example demonstrates how to save a session's transcript to disk
4// and restore it later to continue a conversation with full context.
5//
6// Usage: cargo run --example transcript_persistence
7
8use fm_bindings::LanguageModelSession;
9use std::fs;
10use std::path::Path;
11
12const TRANSCRIPT_FILE: &str = "session_transcript.json";
13
14fn main() -> Result<(), Box<dyn std::error::Error>> {
15    println!("=== Foundation Models - Transcript Persistence Example ===\n");
16
17    // Check if we have a saved session to restore
18    if Path::new(TRANSCRIPT_FILE).exists() {
19        println!("Found saved session, restoring...\n");
20        restore_and_continue()?;
21    } else {
22        println!("No saved session found, starting fresh...\n");
23        create_and_save()?;
24    }
25
26    Ok(())
27}
28
29fn create_and_save() -> Result<(), Box<dyn std::error::Error>> {
30    // Create a new session with instructions
31    let session = LanguageModelSession::with_instructions(
32        "You are a knowledgeable travel guide specializing in Japanese culture and tourism.",
33    )?;
34    println!("Created new session with travel guide persona.\n");
35
36    // Have a conversation
37    println!("User: Tell me about Tokyo.");
38    let response1 = session.response("Tell me about Tokyo.")?;
39    println!("Assistant: {}\n", response1);
40
41    println!("User: What's the best time to visit?");
42    let response2 = session.response("What's the best time to visit?")?;
43    println!("Assistant: {}\n", response2);
44
45    // Save the transcript
46    let transcript_json = session.transcript_json()?;
47    fs::write(TRANSCRIPT_FILE, &transcript_json)?;
48    println!("--- Session saved to {} ---", TRANSCRIPT_FILE);
49    println!("Run this example again to restore and continue the conversation.\n");
50
51    Ok(())
52}
53
54fn restore_and_continue() -> Result<(), Box<dyn std::error::Error>> {
55    // Load the saved transcript
56    let transcript_json = fs::read_to_string(TRANSCRIPT_FILE)?;
57
58    // Restore the session
59    let session = LanguageModelSession::from_transcript_json(&transcript_json)?;
60    println!("Session restored with previous conversation context.\n");
61
62    // Continue the conversation - the model remembers the previous context
63    println!("User: What about the food there?");
64    let response = session.response("What about the food there?")?;
65    println!("Assistant: {}\n", response);
66
67    println!("User: Any restaurant recommendations?");
68    let response2 = session.response("Any restaurant recommendations?")?;
69    println!("Assistant: {}\n", response2);
70
71    // Clean up the saved file
72    fs::remove_file(TRANSCRIPT_FILE)?;
73    println!("--- Cleaned up saved session ---\n");
74
75    Ok(())
76}