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::collections::BTreeMap;
use std::error::Error;
use troupekit::agent::Limits;
use troupekit::prelude::*;

const MODEL: &str = "anthropic/claude-haiku-5-5";

/// Returns how many units of `sku` are in the warehouse.
#[tool]
fn stock_level(sku: String) -> Result<u32, String> {
    match sku.trim() {
        "SKU-7" => Ok(12),
        "SKU-9" => Ok(0),
        other => Err(format!("unknown sku {other}")),
    }
}

/// Counts the spans of each name in the JSONL trace `text`.
/// Input: the file's text. Output: span name to count.
fn span_counts(text: &str) -> BTreeMap<String, usize> {
    let mut counts = BTreeMap::new();
    for line in text.lines() {
        let Ok(record) = serde_json::from_str::<serde_json::Value>(line) else {
            continue;
        };
        if record["t"] == "start" {
            if let Some(name) = record["name"].as_str() {
                *counts.entry(name.to_string()).or_insert(0) += 1;
            }
        }
    }
    counts
}

/// Runs a traced agent with one tool, then prints where the trace is and
/// how many spans of each kind it holds. Input: ANTHROPIC_API_KEY.
/// Output: the answer, the trace path and the span counts.
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let path = std::env::temp_dir().join(format!("course-tracing-{}.jsonl", std::process::id()));
    let agent = Agent::new("stock")
        .model(MODEL)
        .instructions("Answer stock questions with the stock_level tool, in one sentence.")
        .tool(stock_level)
        .max_turns(4)
        .limits(Limits {
            run: Some(20_000),
            ..Limits::default()
        })
        .tracing(true)
        .trace_file(&path)
        .build()
        .await?;
    let outcome = agent
        .run_with("Do you have SKU-7 and SKU-9 in stock?")
        .await?;
    println!("{}\n", outcome.text());
    println!("trace: {}", path.display());
    for (name, n) in span_counts(&std::fs::read_to_string(&path)?) {
        println!("{n:>3}  {name}");
    }
    Ok(())
}