troupekit 0.4.0

Rust framework for LLM agents that run inside your own program: #[agent] functions or persona TOML files, tools, memory, document search and graph workflows that survive a restart.
Documentation
use std::error::Error;
use std::path::{Path, PathBuf};
use std::process::Command;
use troupekit::agent::Limits;
use troupekit::core::ids::RunId;
use troupekit::prelude::*;
use troupekit::ToolContext;

const MODEL: &str = "anthropic/claude-haiku-5-5";
const MODE: &str = "COURSE_RESEARCH_MODE";
const DIR: &str = "COURSE_RESEARCH_DIR";
const RUN: &str = "COURSE_RESEARCH_RUN";
const TOPIC: &str = "why LLM agent runs should survive a process restart";

/// Returns the folder the parent process made for this run.
/// Input: COURSE_RESEARCH_DIR. Output: its path.
fn dir() -> PathBuf {
    PathBuf::from(std::env::var_os(DIR).expect("COURSE_RESEARCH_DIR is set by the parent"))
}

/// Returns the mode this process runs in: crash, resume or the parent.
fn mode() -> String {
    std::env::var(MODE).unwrap_or_default()
}

/// The first agent: turns a topic into three questions.
/// Input: none. Output: the unbuilt agent for the graph.
fn outliner() -> Agent {
    Agent::new("outliner")
        .model(MODEL)
        .instructions("List three short questions a report on the user's topic must answer, one per line, and nothing else.")
        .max_turns(2)
        .max_tokens(300)
}

/// The second agent: answers the questions as a short report.
/// Input: none. Output: the unbuilt agent for the graph.
fn drafter() -> Agent {
    Agent::new("drafter")
        .model(MODEL)
        .instructions(
            "Answer each question in two sentences, with the question as a Markdown heading.",
        )
        .max_turns(2)
        .max_tokens(900)
}

/// Keeps a copy of the outline for this process, then passes it on. In
/// the crash process it saves the run id and kills its own process here,
/// after the outline agent's step was checkpointed.
#[tool]
fn hold(outline: String, ctx: ToolContext) -> String {
    std::fs::write(dir().join(format!("outline-{}.txt", mode())), &outline)
        .expect("write outline copy");
    if mode() == "crash" {
        let run_id = ctx.run_id.expect("graph steps carry their run id");
        std::fs::write(dir().join("run-id"), run_id.to_string()).expect("write run-id");
        std::process::abort();
    }
    outline
}

/// Saves the drafted report as report.md in the run folder.
#[tool]
fn save(draft: String) -> Result<String, String> {
    std::fs::write(dir().join("report.md"), &draft)
        .map_err(|e| format!("could not save the report: {e}"))?;
    Ok(format!("saved {} bytes to report.md", draft.len()))
}

/// Builds the pipeline: outline agent, hold, draft agent, save, with
/// checkpoints in the SQLite file `db` and one spend cap for the whole run.
/// Input: the file. Output: the built graph.
async fn pipeline(db: &Path) -> Result<BuiltGraph, KitError> {
    Graph::new("research")
        .agent("outline", outliner())
        .step("hold", hold)
        .agent("draft", drafter())
        .step("save", save)
        .checkpoints(Storage::sqlite(db))
        .limits(Limits {
            run: Some(30_000),
            ..Limits::default()
        })
        .build()
        .await
}

/// Runs this program again as a child in `mode`, with the run folder and
/// an optional run id. Input: mode, folder, run id. Output: whether the
/// child exited successfully.
fn child(mode: &str, folder: &Path, run: Option<&str>) -> Result<bool, Box<dyn Error>> {
    let mut command = Command::new(std::env::current_exe()?);
    command.env(MODE, mode).env(DIR, folder);
    if let Some(run) = run {
        command.env(RUN, run);
    }
    Ok(command.status()?.success())
}

/// Parent: a first child dies after the outline step, a second child
/// resumes the run; the two outline copies are compared to show the
/// outline agent was not asked again. Input: ANTHROPIC_API_KEY. Output:
/// the comparison and the report on stdout.
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    match mode().as_str() {
        "crash" => {
            pipeline(&dir().join("runs.db")).await?.run(TOPIC).await?;
            Err("the crash child was meant to die in hold".into())
        }
        "resume" => {
            let run_id: RunId =
                serde_json::from_value(serde_json::Value::String(std::env::var(RUN)?))?;
            let output = pipeline(&dir().join("runs.db"))
                .await?
                .resume(run_id)
                .await?;
            println!("resumed: {}", output.as_str().unwrap_or_default());
            Ok(())
        }
        _ => {
            let folder = tempfile::tempdir()?;
            println!(
                "first process finished cleanly: {}",
                child("crash", folder.path(), None)?
            );
            let run = std::fs::read_to_string(folder.path().join("run-id"))?;
            if !child("resume", folder.path(), Some(&run))? {
                return Err("the resume child failed".into());
            }
            let before = std::fs::read_to_string(folder.path().join("outline-crash.txt"))?;
            let after = std::fs::read_to_string(folder.path().join("outline-resume.txt"))?;
            println!("outline identical in both processes: {}", before == after);
            println!(
                "\n{}",
                std::fs::read_to_string(folder.path().join("report.md"))?
            );
            Ok(())
        }
    }
}