Skip to main content

troupekit_ffi_core/
graph.rs

1use crate::agent::{parse_run_id, refuse_law, AgentBuilder};
2use crate::error::{ErrorCode, FfiError};
3use crate::host::{guarded, host_tool, trace_categories, trace_sink, HostTool, TraceListener};
4use crate::records::{GraphResult, Progress};
5use crate::runtime::{check_input, spawn};
6use crate::stream::RunStream;
7use std::sync::{Arc, Mutex, PoisonError};
8use std::time::Duration;
9use troupekit_kit::{BuiltGraph, Graph, GraphReport, StreamSettings};
10
11/// Builds a graph of agent and step nodes in steps from the host
12/// language. Every setter returns the same builder; nothing is checked
13/// until `build`, which consumes the settings.
14#[derive(Debug)]
15pub struct GraphBuilder {
16    state: Mutex<State>,
17}
18
19#[derive(Debug)]
20enum State {
21    Open(Box<Graph>),
22    Broken(FfiError),
23    Built,
24}
25
26impl GraphBuilder {
27    /// Starts a builder for a graph named `name`.
28    /// Input: the name, shown in events and errors.
29    /// Output: a new builder.
30    pub fn new(name: String) -> Arc<Self> {
31        let state = match check_input("name", &name) {
32            Ok(()) => State::Open(Box::new(Graph::new(name))),
33            Err(err) => State::Broken(err),
34        };
35        Arc::new(GraphBuilder {
36            state: Mutex::new(state),
37        })
38    }
39
40    /// Reports whether the builder still takes nodes, so host code runs
41    /// only for a builder that is neither built nor broken. The lock is
42    /// released before the caller runs host code. Output: the flag.
43    fn is_open(&self) -> bool {
44        let state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
45        matches!(*state, State::Open(_))
46    }
47
48    fn update(
49        self: &Arc<Self>,
50        change: impl FnOnce(Graph) -> Result<Graph, FfiError>,
51    ) -> Arc<Self> {
52        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
53        let next = match std::mem::replace(&mut *state, State::Built) {
54            State::Open(graph) => match change(*graph) {
55                Ok(graph) => State::Open(Box::new(graph)),
56                Err(err) => State::Broken(err),
57            },
58            other => other,
59        };
60        *state = next;
61        self.clone()
62    }
63
64    /// Adds node `id` that runs `agent` on the text its feeder wrote.
65    /// The agent builder's settings are taken now, so it cannot be built
66    /// on its own afterwards. Output: the same builder, for chaining.
67    pub fn agent(self: &Arc<Self>, id: String, agent: Arc<AgentBuilder>) -> Arc<Self> {
68        let taken = agent.take();
69        self.update(|graph| {
70            check_input("node id", &id)?;
71            Ok(graph.agent(id, taken?))
72        })
73    }
74
75    /// Adds node `id` that calls host tool `tool`; its argument names
76    /// must be the ids of the nodes that feed it (`input` for the first).
77    /// Output: the same builder, for chaining.
78    pub fn step(self: &Arc<Self>, id: String, tool: Arc<dyn HostTool>) -> Arc<Self> {
79        if !self.is_open() {
80            return self.clone();
81        }
82        let wrapped = guarded("tool", || host_tool(tool));
83        self.update(|graph| {
84            check_input("node id", &id)?;
85            Ok(graph.step(id, wrapped?))
86        })
87    }
88
89    /// Connects node `from` to node `to`. Without edges the nodes run in
90    /// the order they were added.
91    /// Output: the same builder, for chaining.
92    pub fn edge(self: &Arc<Self>, from: String, to: String) -> Arc<Self> {
93        self.update(|graph| {
94            check_input("edge from", &from)?;
95            check_input("edge to", &to)?;
96            Ok(graph.edge(from, to))
97        })
98    }
99
100    /// Keeps graph checkpoints in the SQLite file at `path`, so runs
101    /// survive a restart. Needed by `start` and `resume_for`.
102    /// Output: the same builder, for chaining.
103    pub fn sqlite(self: &Arc<Self>, path: String) -> Arc<Self> {
104        self.update(|graph| {
105            check_input("sqlite", &path)?;
106            sqlite_storage(graph, path)
107        })
108    }
109
110    /// Caps the steps of one graph run.
111    /// Zero is refused at build.
112    /// Output: the same builder, for chaining.
113    pub fn max_steps(self: &Arc<Self>, steps: u32) -> Arc<Self> {
114        self.update(|graph| Ok(graph.max_steps(steps)))
115    }
116
117    /// Sets how often a failed node is retried.
118    /// Bounded by the graph engine; checked at build.
119    /// Output: the same builder, for chaining.
120    pub fn retries(self: &Arc<Self>, retries: u32) -> Arc<Self> {
121        self.update(|graph| Ok(graph.retries(retries)))
122    }
123
124    /// Refuses a law file: no run enforces explicit laws yet, so `build`
125    /// returns `Unsupported`. An over-cap path is `InvalidArgument` and a
126    /// path with `..` is `Config`, both checked first.
127    /// Output: the same builder, for chaining.
128    pub fn laws(self: &Arc<Self>, path: String) -> Arc<Self> {
129        self.update(|_| Err(refuse_law("laws", &path, true)))
130    }
131
132    /// Refuses a law given as text: no run enforces explicit laws yet,
133    /// so `build` returns `Unsupported`. Over-cap text is
134    /// `InvalidArgument`, checked first.
135    /// Output: the same builder, for chaining.
136    pub fn law(self: &Arc<Self>, text: String) -> Arc<Self> {
137        self.update(|_| Err(refuse_law("law", &text, false)))
138    }
139
140    /// Turns the built-in laws on or off.
141    /// On by default.
142    /// Output: the same builder, for chaining.
143    pub fn auto_laws(self: &Arc<Self>, on: bool) -> Arc<Self> {
144        self.update(|graph| Ok(graph.auto_laws(on)))
145    }
146
147    /// Turns tracing on with every category, or off. Default off.
148    /// Spans go to `trace_listener`, `trace_jsonl` or the default file.
149    /// Output: the same builder, for chaining.
150    pub fn tracing(self: &Arc<Self>, on: bool) -> Arc<Self> {
151        self.update(|graph| Ok(graph.tracing(on)))
152    }
153
154    /// Turns tracing on for the named categories only, such as `tools`
155    /// or `models`; an empty list turns it off. An unknown name fails
156    /// the build with `InvalidArgument`. Output: the same builder.
157    pub fn trace(self: &Arc<Self>, categories: Vec<String>) -> Arc<Self> {
158        self.update(|graph| Ok(graph.trace(trace_categories(&categories)?)))
159    }
160
161    /// Keeps prompt, reply and tool text in spans. Default off: spans
162    /// then hold byte counts only. Keys are scrubbed either way.
163    /// Output: the same builder, for chaining.
164    pub fn trace_content(self: &Arc<Self>, on: bool) -> Arc<Self> {
165        self.update(|graph| Ok(graph.trace_content(on)))
166    }
167
168    /// Writes trace records to the new JSON Lines file `path`; an
169    /// existing file is refused at build. Replaces `trace_listener`.
170    /// Output: the same builder, for chaining.
171    pub fn trace_jsonl(self: &Arc<Self>, path: String) -> Arc<Self> {
172        self.update(|graph| {
173            check_input("trace_jsonl", &path)?;
174            Ok(graph.trace_file(path))
175        })
176    }
177
178    /// Sends each trace record to `listener` instead of a file.
179    /// Replaces `trace_jsonl`; takes effect only with tracing on.
180    /// Output: the same builder, for chaining.
181    pub fn trace_listener(self: &Arc<Self>, listener: Arc<dyn TraceListener>) -> Arc<Self> {
182        self.update(|graph| Ok(graph.trace_to(trace_sink(listener))))
183    }
184
185    /// Checks the nodes, edges, agents, tools and storage and returns a
186    /// ready graph. Makes no model call. Output: the graph handle, or
187    /// the first problem found with its code.
188    pub async fn build(self: &Arc<Self>) -> Result<Arc<GraphHandle>, FfiError> {
189        let graph = {
190            let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
191            match std::mem::replace(&mut *state, State::Built) {
192                State::Open(graph) => *graph,
193                State::Broken(err) => return Err(err),
194                State::Built => {
195                    return Err(FfiError::new(
196                        ErrorCode::InvalidArgument,
197                        "builder already built",
198                    ))
199                }
200            }
201        };
202        let built = spawn(async move { graph.build().await.map_err(FfiError::from) }).await?;
203        Ok(Arc::new(GraphHandle { graph: built }))
204    }
205}
206
207#[cfg(feature = "sqlite")]
208fn sqlite_storage(graph: Graph, path: String) -> Result<Graph, FfiError> {
209    Ok(graph.checkpoints(troupekit_kit::Storage::sqlite(path)))
210}
211
212#[cfg(not(feature = "sqlite"))]
213fn sqlite_storage(_graph: Graph, _path: String) -> Result<Graph, FfiError> {
214    Err(FfiError::new(
215        ErrorCode::Unsupported,
216        "sqlite needs troupekit built with the sqlite feature",
217    ))
218}
219
220/// A built graph, ready to run many times.
221/// Outputs cross as JSON text; run ids as text.
222/// Agent nodes report events under their own run ids.
223#[derive(Debug)]
224pub struct GraphHandle {
225    graph: BuiltGraph,
226}
227
228impl GraphHandle {
229    /// Runs the graph on `input` to the end.
230    /// Output: the last node's output as JSON text, or the error with
231    /// its code and run id.
232    pub async fn run(&self, input: String) -> Result<String, FfiError> {
233        check_input("input", &input)?;
234        let graph = self.graph.clone();
235        let output = spawn(async move { graph.run(input).await.map_err(FfiError::from) }).await?;
236        Ok(output.to_string())
237    }
238
239    /// Runs the graph on `input` to the end.
240    /// Output: the whole result: output and state as JSON text, usage,
241    /// steps and run id.
242    pub async fn run_result(&self, input: String) -> Result<GraphResult, FfiError> {
243        check_input("input", &input)?;
244        let graph = self.graph.clone();
245        let report =
246            spawn(async move { graph.run_with(input).await.map_err(FfiError::from) }).await?;
247        Ok(GraphResult::from_report(&report))
248    }
249
250    /// Starts a graph run on `input` with no node run yet and saves its
251    /// first checkpoint. Needs `sqlite`.
252    /// Output: the run id text, to continue with `resume` or `resume_for`.
253    pub async fn start(&self, input: String) -> Result<String, FfiError> {
254        check_input("input", &input)?;
255        let graph = self.graph.clone();
256        let run_id = spawn(async move { graph.start(input).await.map_err(FfiError::from) }).await?;
257        Ok(run_id.to_string())
258    }
259
260    /// Continues graph run `run_id` from its last checkpoint to the end.
261    /// Output: the last node's output as JSON text, or the error.
262    /// The run must have been started by the same workflow.
263    pub async fn resume(&self, run_id: String) -> Result<String, FfiError> {
264        let run_id = parse_run_id(&run_id)?;
265        let graph = self.graph.clone();
266        let output =
267            spawn(async move { graph.resume(run_id).await.map_err(FfiError::from) }).await?;
268        Ok(output.to_string())
269    }
270
271    /// Continues graph run `run_id` for about `budget_ms` milliseconds,
272    /// saving after every step. Output: `Done` with the last output as
273    /// text, or `Pending` when time ran out.
274    pub async fn resume_for(&self, run_id: String, budget_ms: u64) -> Result<Progress, FfiError> {
275        let run_id = parse_run_id(&run_id)?;
276        let graph = self.graph.clone();
277        let budget = Duration::from_millis(budget_ms);
278        let progress = spawn(async move {
279            graph
280                .resume_for(run_id, budget)
281                .await
282                .map_err(FfiError::from)
283        })
284        .await?;
285        Progress::from_kit(progress)
286    }
287
288    /// Starts a graph run on `input` and returns its event stream once the
289    /// run id is known. Its `result` holds the last output as text (a
290    /// string as is, else JSON) and as JSON; `model_calls` is 0.
291    pub async fn stream(&self, input: String) -> Result<Arc<RunStream>, FfiError> {
292        check_input("input", &input)?;
293        let graph = self.graph.clone();
294        let mut settings = StreamSettings::default();
295        settings.capacity = crate::runtime::settings().event_buffer;
296        let stream = spawn(async move {
297            graph
298                .stream_with(input, settings)
299                .await
300                .map_err(FfiError::from)
301        })
302        .await?;
303        Ok(RunStream::graph(stream))
304    }
305}
306
307impl GraphResult {
308    pub(crate) fn from_report(report: &GraphReport) -> GraphResult {
309        let state = serde_json::Value::Object(report.state().clone());
310        GraphResult {
311            output_json: report.output().to_string(),
312            state_json: state.to_string(),
313            usage: crate::stream::usage_of(report.usage()),
314            steps: report.steps(),
315            run_id: report.run_id().to_string(),
316        }
317    }
318}