Skip to main content

troupekit_agent/
io.rs

1use crate::budget::{InMemoryLedger, UsageLedger};
2use crate::error::AgentError;
3use crate::eval::EvalRegistry;
4use async_trait::async_trait;
5use std::collections::HashMap;
6use std::sync::{Arc, Mutex};
7use troupekit_core::clock::{Clock, SystemClock};
8use troupekit_core::event::Event;
9use troupekit_providers::{Model, Price};
10use troupekit_tools::ToolRegistry;
11
12/// A model ready to call plus the price its replies are charged at,
13/// unless the model prices its own replies, as a routed one or one
14/// metered at this price does. The price travels with the model because
15/// a type-erased model hides it, and budgets need it before the call.
16#[derive(Clone)]
17pub struct ModelHandle {
18    pub model: Arc<dyn Model>,
19    pub price: Price,
20}
21
22/// Receives every event a run emits, in `seq` order.
23/// Synchronous so it can be called while a reply streams; hosts that
24/// write to a database queue the event and return.
25pub trait EventSink: Send + Sync {
26    fn emit(&self, event: Event);
27}
28
29/// An `EventSink` that keeps every event in memory.
30/// For tests and examples; `events` returns a copy.
31/// Safe to share across threads.
32#[derive(Debug, Default)]
33pub struct VecSink(Mutex<Vec<Event>>);
34
35impl VecSink {
36    /// Copies every event received so far.
37    /// Returns them oldest first, in `seq` order for a single run.
38    /// The sink keeps its own copy.
39    pub fn events(&self) -> Vec<Event> {
40        self.0.lock().unwrap_or_else(|p| p.into_inner()).clone()
41    }
42}
43
44impl EventSink for VecSink {
45    fn emit(&self, event: Event) {
46        self.0.lock().unwrap_or_else(|p| p.into_inner()).push(event);
47    }
48}
49
50/// Everything live a run needs, supplied by the host on every step:
51/// model resolution by persona selector (`vendor/model` or a role alias),
52/// tools, evals, the usage ledger, the event sink and the clock.
53#[async_trait]
54pub trait AgentIo: Send + Sync {
55    async fn model(&self, selector: &str) -> Result<ModelHandle, AgentError>;
56    fn tools(&self) -> &ToolRegistry;
57    fn evals(&self) -> &EvalRegistry;
58    fn ledger(&self) -> &dyn UsageLedger;
59    fn events(&self) -> &dyn EventSink;
60    fn clock(&self) -> &dyn Clock;
61}
62
63/// An `AgentIo` built from plain fields: models by exact selector, a tool
64/// registry, evals, a ledger, a sink and a clock. Good for tests, examples
65/// and single-user hosts; `new` starts with in-memory parts.
66pub struct SimpleIo {
67    pub models: HashMap<String, ModelHandle>,
68    pub tools: ToolRegistry,
69    pub evals: EvalRegistry,
70    pub ledger: Arc<dyn UsageLedger>,
71    pub events: Arc<dyn EventSink>,
72    pub clock: Arc<dyn Clock>,
73}
74
75impl SimpleIo {
76    /// Builds an io over `tools` with no models, the built-in evals, an
77    /// in-memory ledger, a `VecSink` and the system clock.
78    /// Returns the io; add models with `with_model`.
79    pub fn new(tools: ToolRegistry) -> Self {
80        Self {
81            models: HashMap::new(),
82            tools,
83            evals: EvalRegistry::new(),
84            ledger: Arc::new(InMemoryLedger::default()),
85            events: Arc::new(VecSink::default()),
86            clock: Arc::new(SystemClock),
87        }
88    }
89
90    /// Serves `model` at `price` for persona selector `selector`,
91    /// replacing any model already served for it.
92    /// Returns the io.
93    pub fn with_model(mut self, selector: &str, model: Arc<dyn Model>, price: Price) -> Self {
94        self.models
95            .insert(selector.to_string(), ModelHandle { model, price });
96        self
97    }
98}
99
100#[async_trait]
101impl AgentIo for SimpleIo {
102    async fn model(&self, selector: &str) -> Result<ModelHandle, AgentError> {
103        self.models
104            .get(selector)
105            .cloned()
106            .ok_or_else(|| AgentError::Setup(format!("no model for `{selector}`")))
107    }
108
109    fn tools(&self) -> &ToolRegistry {
110        &self.tools
111    }
112
113    fn evals(&self) -> &EvalRegistry {
114        &self.evals
115    }
116
117    fn ledger(&self) -> &dyn UsageLedger {
118        self.ledger.as_ref()
119    }
120
121    fn events(&self) -> &dyn EventSink {
122        self.events.as_ref()
123    }
124
125    fn clock(&self) -> &dyn Clock {
126        self.clock.as_ref()
127    }
128}