Skip to main content

troupekit/
lib.rs

1//! Troupekit is an open-source Rust framework for LLM agents that run inside
2//! your own program. Write an agent as a Rust function with `#[agent]` or as a
3//! persona TOML file, give it tools, memory and documents, and run it in graph
4//! workflows that survive a restart. Guide: <https://chaoticqubit.github.io/troupekit/>.
5//!
6//! This is the entry crate. `use troupekit::prelude::*;` gives the `#[agent]`
7//! and `#[tool]` macros and the `Agent` and `Graph` builders (feature `kit`,
8//! on by default). `Troupe::builder()` wires the five stores, in memory by
9//! default or in one SQLite file with `sqlite(path)`, and hands out a
10//! `Runner` over them. The engines are re-exported as modules.
11
12#![doc(
13    html_logo_url = "https://raw.githubusercontent.com/ChaoticQubit/troupekit/main/assets/brand/logo-mark.svg",
14    html_favicon_url = "https://raw.githubusercontent.com/ChaoticQubit/troupekit/main/assets/brand/favicon.svg"
15)]
16
17pub use troupekit_agent as agent;
18pub use troupekit_core as core;
19pub use troupekit_graph as graph;
20pub use troupekit_host as host;
21pub use troupekit_providers as providers;
22pub use troupekit_tools as tools;
23pub use troupekit_trace as trace;
24#[cfg(feature = "local")]
25pub use troupekit_local as local;
26#[cfg(feature = "kit")]
27#[doc(hidden)]
28pub use troupekit_kit::__private;
29#[cfg(feature = "kit")]
30pub use troupekit_kit::{
31    agent, prelude, tool, Agent, AsTool, BuiltAgent, BuiltGraph, Graph, GraphReport, Input,
32    IntoToolOutput, Json, KitError, Laws, Progress, RunOutcome, RunStream, Storage, StreamSettings,
33    Tool, ToolContext, ToolOutput, MAX_PERSONA_BYTES, MAX_STEPS_PER_WINDOW,
34};
35#[cfg(feature = "local")]
36pub use troupekit_kit::LocalChoice;
37#[cfg(feature = "knowledge")]
38pub use troupekit_kit::{knowledge, AgentMemory, Knowledge};
39
40#[cfg(feature = "sqlite")]
41pub use troupekit_store_sqlite::{Durability, SqliteStore, SqliteStoreBuilder};
42#[cfg(feature = "knowledge")]
43pub use troupekit_context as context;
44#[cfg(feature = "knowledge")]
45pub use troupekit_store_sqlite::{HnswParams, IndexKind, OpenReport, Quantization, SqliteVectors, VectorSettings};
46
47use std::sync::Arc;
48use troupekit_agent::InMemoryLedger;
49use troupekit_core::clock::{Clock, SystemClock};
50use troupekit_core::error::CoreError;
51use troupekit_core::inmem::{InMemBlobs, InMemCheckpoints, InMemMemory};
52use troupekit_core::store::{BlobStore, CheckpointStore, JobQueue, MemoryLog, UsageLedger};
53use troupekit_graph::GraphIo;
54use troupekit_host::{InMemQueue, Runner};
55
56enum Store {
57    Memory,
58    #[cfg(feature = "sqlite")]
59    Sqlite(Box<SqliteStoreBuilder>),
60}
61
62/// Settings for a `Troupe`. With no store chosen the five stores live in
63/// memory and nothing survives a restart. `sqlite` and `sqlite_with` put
64/// all five in one file. `clock` sets the job queue's time source.
65pub struct TroupeBuilder {
66    store: Store,
67    clock: Option<Arc<dyn Clock>>,
68}
69
70impl TroupeBuilder {
71    /// Keeps every store in one SQLite file at `path` with every store
72    /// setting at its default. Input: the file path. Output: the builder.
73    #[cfg(feature = "sqlite")]
74    pub fn sqlite(self, path: impl AsRef<std::path::Path>) -> Self {
75        self.sqlite_with(SqliteStore::builder(path))
76    }
77
78    /// Keeps every store in one SQLite file opened from `store`, so any
79    /// store setting (durability, caps, busy timeout, key) applies.
80    /// Input: the store builder. Output: the builder.
81    #[cfg(feature = "sqlite")]
82    pub fn sqlite_with(mut self, store: SqliteStoreBuilder) -> Self {
83        self.store = Store::Sqlite(Box::new(store));
84        self
85    }
86
87    /// Sets the job queue's clock, in memory or SQLite. It replaces the
88    /// clock of a builder given to `sqlite_with`. Use the clock of the
89    /// runner's io. Input: the clock. Output: the builder.
90    pub fn clock(mut self, clock: Arc<dyn Clock>) -> Self {
91        self.clock = Some(clock);
92        self
93    }
94
95    /// Opens the chosen stores. Needs a tokio runtime for SQLite.
96    /// Output: the troupe, or `CoreError::Store` when the file cannot be
97    /// created, is foreign or newer, or a setting is out of range.
98    pub async fn build(self) -> Result<Troupe, CoreError> {
99        match self.store {
100            Store::Memory => {
101                let clock = self.clock.unwrap_or_else(|| Arc::new(SystemClock));
102                Ok(Troupe {
103                    checkpoints: Arc::new(InMemCheckpoints::default()),
104                    memory: Arc::new(InMemMemory::default()),
105                    blobs: Arc::new(InMemBlobs::default()),
106                    queue: Arc::new(InMemQueue::new(clock)),
107                    ledger: Arc::new(InMemoryLedger::default()),
108                })
109            }
110            #[cfg(feature = "sqlite")]
111            Store::Sqlite(builder) => {
112                let builder = match self.clock {
113                    Some(clock) => builder.clock(clock),
114                    None => *builder,
115                };
116                let store = Arc::new(builder.open().await?);
117                Ok(Troupe {
118                    checkpoints: store.clone(),
119                    memory: store.clone(),
120                    blobs: store.clone(),
121                    queue: store.clone(),
122                    ledger: store,
123                })
124            }
125        }
126    }
127}
128
129/// The five stores of one Troupekit host, shared by every runner built
130/// from it. Cheap to clone. Build it with `Troupe::builder()`.
131#[derive(Clone)]
132pub struct Troupe {
133    checkpoints: Arc<dyn CheckpointStore>,
134    memory: Arc<dyn MemoryLog>,
135    blobs: Arc<dyn BlobStore>,
136    queue: Arc<dyn JobQueue>,
137    ledger: Arc<dyn UsageLedger>,
138}
139
140impl Troupe {
141    /// Starts a builder with in-memory stores and the system clock.
142    /// Output: the builder; nothing opens until `build`.
143    pub fn builder() -> TroupeBuilder {
144        TroupeBuilder {
145            store: Store::Memory,
146            clock: None,
147        }
148    }
149
150    /// Returns the checkpoint store runs are saved to.
151    pub fn checkpoints(&self) -> Arc<dyn CheckpointStore> {
152        self.checkpoints.clone()
153    }
154
155    /// Returns the message log store.
156    pub fn memory(&self) -> Arc<dyn MemoryLog> {
157        self.memory.clone()
158    }
159
160    /// Returns the blob store.
161    pub fn blobs(&self) -> Arc<dyn BlobStore> {
162        self.blobs.clone()
163    }
164
165    /// Returns the job queue runners claim work from.
166    pub fn queue(&self) -> Arc<dyn JobQueue> {
167        self.queue.clone()
168    }
169
170    /// Returns the usage ledger. The builder does not plug it in: set
171    /// `io.ledger = troupe.ledger()` on the `SimpleIo` given to the runner,
172    /// or spend totals stay in memory and reset on restart.
173    pub fn ledger(&self) -> Arc<dyn UsageLedger> {
174        self.ledger.clone()
175    }
176
177    /// Builds a runner over this troupe's queue and checkpoints with `io`.
178    /// Call it again for another worker on the same stores.
179    /// Output: the runner with the default lease.
180    pub fn runner(&self, io: Arc<dyn GraphIo>) -> Runner {
181        Runner::new(self.queue.clone(), self.checkpoints.clone(), io)
182    }
183}
184