troupekit-kit 0.4.0

Ergonomic API for the Troupekit LLM agent framework: one builder or one macro per agent, tool and graph.
Documentation
use super::{detached, note_retry, outcome, retry_left, BuiltAgent, Cancel, Input};
use crate::error::KitError;
use std::sync::Arc;
use std::time::{Duration, Instant};
use troupekit_agent::{AgentIo, AgentRun, RunState, StepOutcome};
use troupekit_core::ids::RunId;
use troupekit_core::store::CheckpointStore;

/// Most steps one `resume_for` call takes before it returns `Pending`,
/// whatever the budget. Bounds a window even when steps are instant.
/// Fixed at 10 000.
pub const MAX_STEPS_PER_WINDOW: u32 = 10_000;

/// Where a run stands after one `resume_for` window.
/// `Done` holds the answer as text; `Pending` means the budget or the
/// step bound ran out first, and the run resumes from its last save.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Progress {
    Done(String),
    Pending { run_id: RunId },
}

impl BuiltAgent {
    /// Starts a run on `input`: checks it, saves the first checkpoint and
    /// returns the run id, with no model call. Continue it with `resume`
    /// or `resume_for`. Needs `Storage::sqlite(..)` or `Storage::custom(..)`.
    pub async fn start(&self, input: impl Into<Input>) -> Result<RunId, KitError> {
        let store = self.durable("start")?;
        let messages = self.messages(input.into()).await?;
        let inner = &self.inner;
        let run = AgentRun::new(&inner.persona, messages, inner.limits.clone(), &inner.io).await?;
        store.save(run.checkpoint()).await?;
        Ok(run.run_id())
    }

    /// Continues run `run_id` for about `budget`, saving after every step.
    /// A step in flight finishes, so leave one model call of slack in a
    /// background window. Fails with `Failed`, `Paused` or `Retries` as
    /// `resume` does; a retry wait that would pass the budget is `Pending`
    /// and is saved, so the next window waits out what is left of it.
    pub async fn resume_for(&self, run_id: RunId, budget: Duration) -> Result<Progress, KitError> {
        let store = self.durable("resume_for")?;
        let Some(checkpoint) = store.latest(run_id).await? else {
            return Err(KitError::config(
                &self.inner.persona.name,
                format!("no checkpoint for run {run_id}"),
            ));
        };
        let deadline = Instant::now().checked_add(budget);
        let mut run = AgentRun::from_checkpoint(&checkpoint)?;
        let name = self.inner.persona.name.as_str();
        if run.persona() != name {
            return Err(KitError::config(
                name,
                format!(
                    "run {run_id} was started by agent `{}`; resume it with that agent",
                    run.persona()
                ),
            ));
        }
        let current = self.inner.limits.clone().with_budget(&self.inner.persona.budget);
        run.tighten(&current);
        match run.state().clone() {
            RunState::Done { output } => return Ok(Progress::Done(outcome(&run, output).text)),
            RunState::Failed { error } => {
                return Err(KitError::failed(run_id, error, run.host_failed()))
            }
            RunState::Paused { reason, .. } => return Err(KitError::Paused { run_id, reason }),
            _ => {}
        }
        self.refuse_exhausted(&run)?;
        let agent = self.clone();
        detached(run_id, move |stop| async move {
            agent.window(run, store, deadline, &stop).await
        })
        .await
    }

    /// Steps `run` until it ends, `deadline` passes, `MAX_STEPS_PER_WINDOW`
    /// steps ran or `cancel` is set after a step, saving after each step.
    /// Input: the restored run, its store, the deadline and the stop flag.
    /// Output: the window's progress, or the run's error.
    async fn window(
        &self,
        mut run: AgentRun,
        store: Arc<dyn CheckpointStore>,
        deadline: Option<Instant>,
        cancel: &Cancel,
    ) -> Result<Progress, KitError> {
        let run_id = run.run_id();
        let spent = |extra: Duration| match deadline {
            Some(deadline) => Instant::now() + extra >= deadline,
            None => false,
        };
        let io: &dyn AgentIo = &self.inner.io;
        let saved_wait = retry_left(&run, io.clock().now_ms());
        if !saved_wait.is_zero() {
            if spent(saved_wait) {
                return Ok(Progress::Pending { run_id });
            }
            if cancel.sleep(saved_wait).await {
                return Err(KitError::Cancelled { run_id });
            }
        }
        let mut steps = 0u32;
        while steps < MAX_STEPS_PER_WINDOW && !spent(Duration::ZERO) {
            if cancel.is_set() {
                return Err(KitError::Cancelled { run_id });
            }
            let step = run.step(io).await;
            let wait = note_retry(&mut run, &step, io.clock().now_ms());
            store
                .save(run.checkpoint())
                .await
                .map_err(|e| KitError::in_run(run_id, e.into()))?;
            steps += 1;
            if cancel.is_set() {
                return Err(KitError::Cancelled { run_id });
            }
            match step {
                StepOutcome::Continue => {}
                StepOutcome::Done(output) => return Ok(Progress::Done(outcome(&run, output).text)),
                StepOutcome::Retry { error, .. } => {
                    assert!(run.retries() > 0);
                    let attempts = run.retries() - 1;
                    if attempts >= self.inner.retries {
                        return Err(KitError::Retries {
                            run_id,
                            attempts,
                            last_error: error,
                        });
                    }
                    let wait = wait.expect("a retry step has a wait");
                    if spent(wait) {
                        return Ok(Progress::Pending { run_id });
                    }
                    if cancel.sleep(wait).await {
                        return Err(KitError::Cancelled { run_id });
                    }
                }
                StepOutcome::Paused(reason) => return Err(KitError::Paused { run_id, reason }),
                StepOutcome::Failed(reason) => {
                    return Err(KitError::failed(run_id, reason, run.host_failed()))
                }
            }
            assert!(run.retries() <= self.inner.retries);
        }
        assert!(steps <= MAX_STEPS_PER_WINDOW);
        Ok(Progress::Pending { run_id })
    }

    fn durable(&self, what: &str) -> Result<Arc<dyn CheckpointStore>, KitError> {
        match &self.inner.store {
            Some(store) => Ok(store.clone()),
            None => Err(KitError::config(
                &self.inner.persona.name,
                format!("{what} needs Storage::sqlite(..) or Storage::custom(..) checkpoints"),
            )),
        }
    }
}