Skip to main content

troupekit_kit/graph/
run_api.rs

1use super::{input_state, BuiltGraph, Graph, GraphReport};
2use crate::built::{detached, Cancel, Progress, Queue, RunStream, StreamIo, StreamSettings, MAX_STEPS_PER_WINDOW};
3use crate::error::KitError;
4use async_trait::async_trait;
5use serde_json::Value;
6use std::sync::Arc;
7use std::time::Duration;
8use troupekit_agent::{AgentError, AgentIo, EventSink, Persona};
9use troupekit_core::ids::RunId;
10use troupekit_core::inmem::InMemCheckpoints;
11use troupekit_core::store::CheckpointStore;
12use troupekit_graph::{Conditions, GraphIo};
13use troupekit_graph::{GraphOutcome, GraphRun, GraphStatus};
14
15impl Graph {
16    /// Sends every event of the graph and of its agent nodes to `sink`.
17    /// Agent nodes run under their own run ids, so order by `seq` only
18    /// within one run id. Defaults to a sink that drops events.
19    pub fn events(mut self, sink: Arc<dyn EventSink>) -> Self {
20        self.events = Some(sink);
21        self
22    }
23
24    /// Builds the graph and starts a streamed run on `input`.
25    /// Output: the stream once the run id is known, or the first build
26    /// or setup error. Keep a `BuiltGraph` to run many times.
27    pub async fn stream(
28        self,
29        input: impl Into<String>,
30    ) -> Result<RunStream<GraphReport>, KitError> {
31        self.build().await?.stream(input).await
32    }
33}
34
35impl BuiltGraph {
36    /// Starts a graph run on `input`: saves the first checkpoint and
37    /// returns the run id, with no node run yet. Continue it with
38    /// `resume` or `resume_for`. Needs durable storage.
39    pub async fn start(&self, input: impl Into<String>) -> Result<RunId, KitError> {
40        let inner = &self.inner;
41        let store = self.durable("start")?;
42        let state = input_state(&input.into());
43        let run = GraphRun::new(
44            inner.workflow.clone(),
45            state,
46            inner.limits.clone(),
47            &inner.io,
48        )
49        .await?;
50        let checkpoint = run.checkpoint();
51        assert_eq!(checkpoint.step, 0);
52        store.save(checkpoint).await?;
53        Ok(run.run_id())
54    }
55
56    /// Continues graph run `run_id` for about `budget` on the io clock,
57    /// saving after every step. A node in flight finishes, so leave one
58    /// model call of slack. Returns the last node's output as text when
59    /// done, whatever the budget; a retry wait that would pass the budget
60    /// is `Pending`.
61    pub async fn resume_for(&self, run_id: RunId, budget: Duration) -> Result<Progress, KitError> {
62        let budget_ms = i64::try_from(budget.as_millis()).unwrap_or(i64::MAX);
63        let deadline_ms = self.inner.io.agent.clock().now_ms().saturating_add(budget_ms);
64        let run = self.load(run_id).await?;
65        let store = self.durable("resume_for")?;
66        let graph = self.clone();
67        detached(run_id, move |stop| async move {
68            graph.window(run, store, deadline_ms, &stop).await
69        })
70        .await
71    }
72
73    /// Steps `run` until it ends, the io clock reaches `deadline_ms`,
74    /// `MAX_STEPS_PER_WINDOW` steps ran or `cancel` is set after a step,
75    /// saving after each step. Input: the restored run, its store, the
76    /// deadline and the stop flag. Output: the progress or the error.
77    async fn window(
78        &self,
79        mut run: GraphRun,
80        store: Arc<dyn CheckpointStore>,
81        deadline_ms: i64,
82        cancel: &Cancel,
83    ) -> Result<Progress, KitError> {
84        let inner = &self.inner;
85        let run_id = run.run_id();
86        let clock = inner.io.agent.clock();
87        let settled = !matches!(
88            run.status(),
89            GraphStatus::Queued | GraphStatus::Checkpointed
90        );
91        let mut steps = 0u32;
92        while steps < MAX_STEPS_PER_WINDOW && (settled || clock.now_ms() < deadline_ms) {
93            if cancel.is_set() {
94                return Err(KitError::Cancelled { run_id });
95            }
96            let before = run.steps();
97            let outcome = run.step(&inner.io).await;
98            if run.steps() != before {
99                assert_eq!(run.steps(), before + 1);
100                store
101                    .save(run.checkpoint())
102                    .await
103                    .map_err(|e| KitError::in_run(run_id, e.into()))?;
104            }
105            steps += 1;
106            if cancel.is_set() {
107                return Err(KitError::Cancelled { run_id });
108            }
109            match outcome {
110                GraphOutcome::Continue => {}
111                GraphOutcome::RetryAt { at_ms, .. } if at_ms >= deadline_ms => {
112                    return Ok(Progress::Pending { run_id });
113                }
114                GraphOutcome::RetryAt { at_ms, .. } => {
115                    if super::wait_until(clock, at_ms, super::RETRY_WAIT_CHUNK_MS, cancel).await {
116                        return Err(KitError::Cancelled { run_id });
117                    }
118                }
119                GraphOutcome::Waiting(reason) => return Err(KitError::Paused { run_id, reason }),
120                GraphOutcome::Failed(reason) => {
121                    return Err(KitError::failed(run_id, reason, run.host_failed()))
122                }
123                GraphOutcome::Done(state) => {
124                    let output = state
125                        .get(&inner.last)
126                        .expect("a finished chain run wrote its last node");
127                    return Ok(Progress::Done(text_of(output)));
128                }
129            }
130        }
131        assert!(steps <= MAX_STEPS_PER_WINDOW);
132        Ok(Progress::Pending { run_id })
133    }
134
135    /// Starts a graph run on `input` and returns the stream of its events
136    /// and its agent nodes' events, with the default buffer. Fails at the
137    /// call on a bad setup. Needs no durable storage.
138    pub async fn stream(
139        &self,
140        input: impl Into<String>,
141    ) -> Result<RunStream<GraphReport>, KitError> {
142        self.stream_with(input, StreamSettings::default()).await
143    }
144
145    /// Starts a streamed graph run on `input` with `settings`. Events also
146    /// reach the graph's own `.events(..)` sink. Fails with `Config` when
147    /// the capacity is out of range, else as `stream`.
148    pub async fn stream_with(
149        &self,
150        input: impl Into<String>,
151        settings: StreamSettings,
152    ) -> Result<RunStream<GraphReport>, KitError> {
153        let inner = &self.inner;
154        settings.check(&inner.owner)?;
155        let queue = Arc::new(Queue::new(settings.capacity));
156        let io = StreamGraphIo {
157            graph: self.clone(),
158            agent: StreamIo {
159                base: inner.io.agent.clone(),
160                queue: queue.clone(),
161            },
162        };
163        let state = input_state(&input.into());
164        let mut run =
165            GraphRun::new(inner.workflow.clone(), state, inner.limits.clone(), &io).await?;
166        let run_id = run.run_id();
167        let store: Arc<dyn CheckpointStore> = match &inner.store {
168            Some(store) => store.clone(),
169            None => Arc::new(InMemCheckpoints::default()),
170        };
171        store.save(run.checkpoint()).await?;
172        let graph = self.clone();
173        let cancel = Cancel::default();
174        let stop = cancel.clone();
175        let task = async move { graph.finish(&io, &mut run, store.as_ref(), &stop).await };
176        assert_eq!(queue.dropped(), 0);
177        Ok(RunStream::spawn(run_id, queue, cancel, task))
178    }
179
180    async fn load(&self, run_id: RunId) -> Result<GraphRun, KitError> {
181        let inner = &self.inner;
182        let store = self.durable("resume_for")?;
183        let Some(checkpoint) = store.latest(run_id).await? else {
184            return Err(KitError::config(
185                &inner.owner,
186                format!("no checkpoint for run {run_id}"),
187            ));
188        };
189        let mut run = GraphRun::from_checkpoint(&checkpoint)?;
190        if run.workflow() != &inner.workflow {
191            return Err(KitError::config(
192                &inner.owner,
193                format!(
194                    "run {run_id} was started by a different workflow; resume it with the graph that started it"
195                ),
196            ));
197        }
198        run.tighten(&self.inner.limits);
199        assert_eq!(run.run_id(), run_id);
200        Ok(run)
201    }
202
203    fn durable(&self, what: &str) -> Result<Arc<dyn CheckpointStore>, KitError> {
204        match &self.inner.store {
205            Some(store) => Ok(store.clone()),
206            None => Err(KitError::config(
207                &self.inner.owner,
208                format!("{what} needs Storage::sqlite(..) or Storage::custom(..) checkpoints"),
209            )),
210        }
211    }
212}
213
214fn text_of(output: &Value) -> String {
215    match output {
216        Value::String(text) => text.clone(),
217        other => other.to_string(),
218    }
219}
220
221struct StreamGraphIo {
222    graph: BuiltGraph,
223    agent: StreamIo<Arc<dyn AgentIo>>,
224}
225
226#[async_trait]
227impl GraphIo for StreamGraphIo {
228    fn agent(&self) -> &dyn AgentIo {
229        &self.agent
230    }
231
232    async fn persona(&self, name: &str) -> Result<Persona, AgentError> {
233        self.graph.inner.io.persona(name).await
234    }
235
236    fn conditions(&self) -> &Conditions {
237        self.graph.inner.io.conditions()
238    }
239}