Skip to main content

troupekit_kit/
built.rs

1use crate::error::KitError;
2use crate::laws::Laws;
3use serde_json::Value;
4use crate::trace::{path_of, root_span, Traced};
5use std::fmt;
6use std::future::Future;
7use std::path::{Path, PathBuf};
8use std::sync::Arc;
9use std::time::Duration;
10use troupekit_agent::{
11    drive, AgentIo, AgentRun, EventSink, Limits, Persona, RunState, SimpleIo, StepOutcome,
12};
13use troupekit_core::event::{Event, Usage};
14use troupekit_core::ids::RunId;
15use troupekit_core::inmem::InMemCheckpoints;
16use troupekit_core::message::{Message, Role};
17use troupekit_core::store::CheckpointStore;
18use troupekit_trace::Trace;
19
20const BASE_RETRY_MS: u64 = 500;
21const MAX_RETRY_MS: u64 = 30_000;
22
23pub(crate) struct Discard;
24
25impl EventSink for Discard {
26    fn emit(&self, _event: Event) {}
27}
28
29/// What an agent runs on: one user text, or a prepared conversation.
30/// Built from `&str`, `String`, one `Message` or a `Vec<Message>`.
31/// An empty conversation fails when the run starts.
32#[derive(Debug, Clone, PartialEq)]
33pub struct Input(Vec<Message>);
34
35impl From<&str> for Input {
36    fn from(text: &str) -> Self {
37        Input(vec![Message::text(Role::User, text)])
38    }
39}
40
41impl From<String> for Input {
42    fn from(text: String) -> Self {
43        Input(vec![Message::text(Role::User, text)])
44    }
45}
46
47impl From<Message> for Input {
48    fn from(message: Message) -> Self {
49        Input(vec![message])
50    }
51}
52
53impl From<Vec<Message>> for Input {
54    fn from(messages: Vec<Message>) -> Self {
55        Input(messages)
56    }
57}
58
59/// The result of one finished run: the answer and how it was reached.
60/// `text` is the answer as text; `output` is the raw final value.
61/// Read it through the getters.
62#[derive(Debug, Clone, PartialEq)]
63#[non_exhaustive]
64pub struct RunOutcome {
65    text: String,
66    output: Value,
67    usage: Usage,
68    model_calls: u32,
69    run_id: RunId,
70    messages: Vec<Message>,
71    trace_path: Option<PathBuf>,
72}
73
74impl RunOutcome {
75    /// Returns the answer as text: a string output as is, any other
76    /// output as JSON text.
77    /// The same text `run` returns.
78    pub fn text(&self) -> &str {
79        &self.text
80    }
81
82    /// Returns the final output value of the run.
83    /// A string for plain agents, a JSON value for typed output.
84    /// Never null for a finished run.
85    pub fn output(&self) -> &Value {
86        &self.output
87    }
88
89    /// Returns the tokens and cost the run used, summed over calls.
90    /// Cost is in millionths of a US dollar.
91    /// Includes eval and repair calls.
92    pub fn usage(&self) -> Usage {
93        self.usage
94    }
95
96    /// Returns how many model calls the run made.
97    /// Retried calls count once per attempt that reached the model.
98    /// At least one for a finished run.
99    pub fn model_calls(&self) -> u32 {
100        self.model_calls
101    }
102
103    /// Returns the id of the run, for `resume` and logs.
104    /// Unique per run.
105    /// Stable across checkpoints.
106    pub fn run_id(&self) -> RunId {
107        self.run_id
108    }
109
110    /// Returns the whole conversation, input first.
111    /// Includes tool calls and tool results.
112    /// The last message is the answer.
113    pub fn messages(&self) -> &[Message] {
114        &self.messages
115    }
116
117    /// Returns the trace file this run was written to.
118    /// `None` when tracing is off or goes to a custom sink.
119    /// Every run of one built agent shares the file.
120    pub fn trace_path(&self) -> Option<&Path> {
121        self.trace_path.as_deref()
122    }
123}
124
125/// An agent that passed every `build` check, ready to run many times.
126/// Cheap to clone and safe to share across tasks; each run gets its own
127/// state, and in-memory checkpoints are dropped after the run.
128#[derive(Clone)]
129pub struct BuiltAgent {
130    inner: Arc<Inner>,
131}
132
133struct Inner {
134    persona: Persona,
135    io: SimpleIo,
136    limits: Limits,
137    store: Option<Arc<dyn CheckpointStore>>,
138    retries: u32,
139    laws: Laws,
140    trace: Option<Traced>,
141    #[cfg(feature = "knowledge")]
142    preamble: Option<troupekit_context::tools::KnowledgeKit>,
143}
144
145impl BuiltAgent {
146    pub(crate) fn new(
147        persona: Persona,
148        io: SimpleIo,
149        limits: Limits,
150        store: Option<Arc<dyn CheckpointStore>>,
151        retries: u32,
152        laws: Laws,
153    ) -> Self {
154        BuiltAgent {
155            inner: Arc::new(Inner {
156                persona,
157                io,
158                limits,
159                store,
160                retries,
161                laws,
162                trace: None,
163                #[cfg(feature = "knowledge")]
164                preamble: None,
165            }),
166        }
167    }
168
169    pub(crate) fn with_trace(mut self, trace: Option<Traced>) -> Self {
170        let inner = Arc::get_mut(&mut self.inner).expect("a fresh BuiltAgent is not shared");
171        inner.trace = trace;
172        self
173    }
174
175    /// Returns the trace file this agent writes, one root span per run.
176    /// `None` when tracing is off or goes to a custom sink.
177    /// The file is created at `build`.
178    pub fn trace_path(&self) -> Option<&Path> {
179        path_of(&self.inner.trace)
180    }
181
182    async fn traced<T>(
183        &self,
184        run_id: Option<RunId>,
185        work: impl Future<Output = Result<T, KitError>>,
186        id_of: impl Fn(&T) -> RunId,
187    ) -> Result<T, KitError> {
188        let owner = self.inner.persona.name.as_str();
189        let traced = self.inner.trace.as_ref();
190        root_span(traced, Trace::Agents, "agent.run", owner, run_id, work, id_of).await
191    }
192
193    #[cfg(feature = "knowledge")]
194    pub(crate) fn with_preamble(
195        mut self,
196        preamble: Option<troupekit_context::tools::KnowledgeKit>,
197    ) -> Self {
198        let inner = Arc::get_mut(&mut self.inner).expect("a fresh BuiltAgent is not shared");
199        inner.preamble = preamble;
200        self
201    }
202
203    #[cfg(feature = "knowledge")]
204    async fn messages(&self, input: Input) -> Result<Vec<Message>, KitError> {
205        match &self.inner.preamble {
206            Some(kit) => crate::memory::prepend(kit, input.0).await,
207            None => Ok(input.0),
208        }
209    }
210
211    #[cfg(not(feature = "knowledge"))]
212    async fn messages(&self, input: Input) -> Result<Vec<Message>, KitError> {
213        Ok(input.0)
214    }
215
216    /// Runs the agent once on `input` and returns the answer as text.
217    /// Retries transient provider failures; fails with `Failed`,
218    /// `Paused` or `Retries` when the run ends without an answer.
219    pub async fn run(&self, input: impl Into<Input>) -> Result<String, KitError> {
220        Ok(self.run_with(input).await?.text)
221    }
222
223    /// Runs the agent once on `input` and returns the full outcome.
224    /// Same failures as `run`.
225    /// The run id in the outcome works with `resume`.
226    pub async fn run_with(&self, input: impl Into<Input>) -> Result<RunOutcome, KitError> {
227        let input = input.into();
228        self.traced(None, self.run_untraced(input), RunOutcome::run_id)
229            .await
230    }
231
232    async fn run_untraced(&self, input: Input) -> Result<RunOutcome, KitError> {
233        let inner = &self.inner;
234        let messages = self.messages(input).await?;
235        let mut run =
236            AgentRun::new(&inner.persona, messages, inner.limits.clone(), &inner.io).await?;
237        let store: Arc<dyn CheckpointStore> = match &inner.store {
238            Some(store) => store.clone(),
239            None => Arc::new(InMemCheckpoints::default()),
240        };
241        self.finish(&mut run, store.as_ref()).await
242    }
243
244    /// Continues run `run_id` from its latest checkpoint, after a crash
245    /// or restart, and returns the answer. A finished run returns its
246    /// answer again. Needs `Storage::sqlite(..)` or `Storage::custom(..)`.
247    pub async fn resume(&self, run_id: RunId) -> Result<String, KitError> {
248        self.traced(Some(run_id), self.resume_untraced(run_id), |_| run_id)
249            .await
250    }
251
252    async fn resume_untraced(&self, run_id: RunId) -> Result<String, KitError> {
253        let name = self.inner.persona.name.as_str();
254        let Some(store) = &self.inner.store else {
255            return Err(KitError::config(
256                name,
257                "resume needs Storage::sqlite(..) or Storage::custom(..) checkpoints",
258            ));
259        };
260        let Some(checkpoint) = store.latest(run_id).await? else {
261            return Err(KitError::config(
262                name,
263                format!("no checkpoint for run {run_id}"),
264            ));
265        };
266        let mut run = AgentRun::from_checkpoint(&checkpoint)?;
267        Ok(self.finish(&mut run, store.as_ref()).await?.text)
268    }
269
270    /// Returns the validated persona this agent runs.
271    /// Built from the builder settings by `Persona::parse`.
272    /// Read only.
273    pub fn persona(&self) -> &Persona {
274        &self.inner.persona
275    }
276
277    /// Returns the laws checked at `build`.
278    /// 0.2 stores them; runs do not prove them yet.
279    /// Read only.
280    pub fn laws(&self) -> &Laws {
281        &self.inner.laws
282    }
283
284    async fn finish(
285        &self,
286        run: &mut AgentRun,
287        store: &dyn CheckpointStore,
288    ) -> Result<RunOutcome, KitError> {
289        let io: &dyn AgentIo = &self.inner.io;
290        match run.state().clone() {
291            RunState::Done { output } => return Ok(self.outcome(run, output)),
292            RunState::Failed { error } => {
293                return Err(KitError::Failed {
294                    run_id: run.run_id(),
295                    reason: error,
296                })
297            }
298            RunState::Paused { reason, .. } => {
299                return Err(KitError::Paused {
300                    run_id: run.run_id(),
301                    reason,
302                })
303            }
304            _ => {}
305        }
306        let mut attempts = 0u32;
307        loop {
308            match drive(run, io, store).await? {
309                StepOutcome::Done(output) => return Ok(self.outcome(run, output)),
310                StepOutcome::Retry {
311                    error,
312                    retry_after_ms,
313                } => {
314                    if attempts >= self.inner.retries {
315                        return Err(KitError::Retries {
316                            run_id: run.run_id(),
317                            attempts,
318                            last_error: error,
319                        });
320                    }
321                    tokio::time::sleep(retry_delay(attempts, retry_after_ms)).await;
322                    attempts += 1;
323                }
324                StepOutcome::Paused(reason) => {
325                    return Err(KitError::Paused {
326                        run_id: run.run_id(),
327                        reason,
328                    })
329                }
330                StepOutcome::Failed(reason) => {
331                    return Err(KitError::Failed {
332                        run_id: run.run_id(),
333                        reason,
334                    })
335                }
336                StepOutcome::Continue => {
337                    unreachable!("drive returns only a final, paused or retry outcome")
338                }
339            }
340            assert!(attempts <= self.inner.retries);
341        }
342    }
343
344    fn outcome(&self, run: &AgentRun, output: Value) -> RunOutcome {
345        let mut outcome = outcome(run, output);
346        outcome.trace_path = self.trace_path().map(Path::to_path_buf);
347        outcome
348    }
349}
350
351impl fmt::Debug for BuiltAgent {
352    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
353        let inner = &self.inner;
354        f.debug_struct("BuiltAgent")
355            .field("name", &inner.persona.name)
356            .field("model", &inner.persona.model)
357            .field("tools", &inner.persona.tools)
358            .field("retries", &inner.retries)
359            .field("durable", &inner.store.is_some())
360            .field("laws", &inner.laws)
361            .finish_non_exhaustive()
362    }
363}
364
365fn outcome(run: &AgentRun, output: Value) -> RunOutcome {
366    let text = match &output {
367        Value::String(text) => text.clone(),
368        other => other.to_string(),
369    };
370    RunOutcome {
371        text,
372        output,
373        usage: run.usage(),
374        model_calls: run.model_calls(),
375        run_id: run.run_id(),
376        messages: run.messages().to_vec(),
377        trace_path: None,
378    }
379}
380
381fn retry_delay(attempt: u32, retry_after_ms: Option<u64>) -> Duration {
382    let backoff = BASE_RETRY_MS.saturating_mul(1u64 << attempt.min(16));
383    Duration::from_millis(retry_after_ms.unwrap_or(backoff).min(MAX_RETRY_MS))
384}
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389
390    #[test]
391    fn retry_delay_backs_off_and_caps() {
392        assert_eq!(retry_delay(0, None), Duration::from_millis(500));
393        assert_eq!(retry_delay(2, None), Duration::from_millis(2000));
394        assert_eq!(retry_delay(20, None), Duration::from_millis(30_000));
395        assert_eq!(retry_delay(0, Some(7)), Duration::from_millis(7));
396        assert_eq!(retry_delay(0, Some(90_000)), Duration::from_millis(30_000));
397    }
398}