Skip to main content

troupekit_kit/
trace.rs

1use crate::agent::Agent;
2use crate::error::KitError;
3use crate::graph::Graph;
4use std::future::Future;
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7use troupekit_core::ids::RunId;
8use troupekit_core::secret::Secret;
9use troupekit_trace::{
10    default_trace_path, trace_span, JsonlSink, Trace, TraceSet, TraceSink, Tracer,
11};
12
13#[derive(Clone, Default)]
14pub(crate) struct TraceConfig {
15    categories: Option<TraceSet>,
16    content: bool,
17    sink: Option<Arc<dyn TraceSink>>,
18    file: Option<PathBuf>,
19}
20
21#[derive(Clone)]
22pub(crate) struct Traced {
23    pub tracer: Tracer,
24    pub path: Option<PathBuf>,
25}
26
27impl TraceConfig {
28    pub(crate) fn is_on(&self) -> bool {
29        self.categories.is_some_and(|c| !c.is_empty())
30    }
31
32    fn set_categories(&mut self, categories: TraceSet) {
33        self.categories = Some(categories);
34    }
35
36    pub(crate) fn open(
37        &self,
38        owner: &str,
39        name: &str,
40        secrets: &[Secret],
41    ) -> Result<Option<Traced>, KitError> {
42        let Some(categories) = self.categories.filter(|c| !c.is_empty()) else {
43            return Ok(None);
44        };
45        let mut builder = Tracer::builder()
46            .name(name)
47            .categories(categories)
48            .content(self.content);
49        for secret in secrets {
50            builder = builder.scrub(secret.expose());
51        }
52        let (sink, path): (Arc<dyn TraceSink>, Option<PathBuf>) = match &self.sink {
53            Some(sink) => (sink.clone(), None),
54            None => {
55                let path = self
56                    .file
57                    .clone()
58                    .unwrap_or_else(|| default_trace_path(name, builder.trace_id()));
59                let sink = JsonlSink::create(&path).map_err(|e| {
60                    KitError::config(owner, format!("trace file `{}`: {e}", path.display()))
61                })?;
62                (Arc::new(sink), Some(path))
63            }
64        };
65        let tracer = builder
66            .sink(sink)
67            .build()
68            .map_err(|e| KitError::config(owner, format!("tracer: {e}")))?;
69        assert_eq!(
70            tracer.categories(),
71            categories,
72            "the tracer keeps the categories"
73        );
74        Ok(Some(Traced { tracer, path }))
75    }
76}
77
78/// Runs `work` as one root span `span_name` in `traced`, or untraced when
79/// tracing is off. `run_id` is known for a resume; otherwise it is read
80/// from the result. Output: the result of `work`, unchanged.
81pub(crate) async fn root_span<T>(
82    traced: Option<&Traced>,
83    cat: Trace,
84    span_name: &'static str,
85    owner: &str,
86    run_id: Option<RunId>,
87    work: impl Future<Output = Result<T, KitError>>,
88    id_of: impl Fn(&T) -> RunId,
89) -> Result<T, KitError> {
90    let Some(traced) = traced else {
91        return work.await;
92    };
93    let scoped = async {
94        let mut span = trace_span!(cat, span_name, name = owner);
95        if let Some(id) = run_id {
96            span.record("resumed", true);
97            span.record("run_id", id.to_string());
98        }
99        let result = span.instrument(work).await;
100        let found = match &result {
101            Ok(value) => Some(id_of(value)),
102            Err(err) => err.run_id(),
103        };
104        if let (None, Some(id)) = (run_id, found) {
105            span.record("run_id", id.to_string());
106        }
107        if result.is_err() {
108            span.fail("run did not finish");
109        }
110        result
111    };
112    traced.tracer.in_scope(scoped).await
113}
114
115pub(crate) fn path_of(traced: &Option<Traced>) -> Option<&Path> {
116    traced.as_ref().and_then(|t| t.path.as_deref())
117}
118
119impl Agent {
120    /// Turns tracing on with every category, or off. Default off.
121    /// Covers `build` and every run; spans go to `trace_to`, `trace_file`
122    /// or `./traces/<name>-<trace id>.jsonl` (`$TROUPEKIT_TRACE_DIR`).
123    pub fn tracing(mut self, on: bool) -> Self {
124        self.trace.categories = on.then(TraceSet::all);
125        self
126    }
127
128    /// Turns tracing on for the listed categories only.
129    /// An empty list turns tracing off.
130    /// Returns the builder.
131    pub fn trace(mut self, categories: impl IntoIterator<Item = Trace>) -> Self {
132        self.trace.set_categories(categories.into_iter().collect());
133        self
134    }
135
136    /// Keeps prompt, reply, tool argument, query and document text in
137    /// spans. Default off: spans then hold only byte counts. Secrets are
138    /// scrubbed either way.
139    pub fn trace_content(mut self, on: bool) -> Self {
140        self.trace.content = on;
141        self
142    }
143
144    /// Sends trace records to `sink` instead of a file.
145    /// Takes effect only with tracing on; replaces `trace_file`.
146    /// Returns the builder.
147    pub fn trace_to(mut self, sink: Arc<dyn TraceSink>) -> Self {
148        self.trace.sink = Some(sink);
149        self.trace.file = None;
150        self
151    }
152
153    /// Writes trace records to the new file `path`; an existing file is
154    /// refused at `build`. Takes effect only with tracing on; replaces
155    /// `trace_to`.
156    pub fn trace_file(mut self, path: impl AsRef<Path>) -> Self {
157        self.trace.file = Some(path.as_ref().to_path_buf());
158        self.trace.sink = None;
159        self
160    }
161}
162
163impl Graph {
164    /// Turns tracing on with every category, or off. Default off.
165    /// Covers `build`, every run and every agent node; spans go to
166    /// `trace_to`, `trace_file` or `./traces/<name>-<trace id>.jsonl`.
167    pub fn tracing(mut self, on: bool) -> Self {
168        self.trace.categories = on.then(TraceSet::all);
169        self
170    }
171
172    /// Turns tracing on for the listed categories only.
173    /// An empty list turns tracing off.
174    /// Returns the builder.
175    pub fn trace(mut self, categories: impl IntoIterator<Item = Trace>) -> Self {
176        self.trace.set_categories(categories.into_iter().collect());
177        self
178    }
179
180    /// Keeps prompt, reply, tool argument, query and document text in
181    /// spans. Default off: spans then hold only byte counts. Secrets are
182    /// scrubbed either way.
183    pub fn trace_content(mut self, on: bool) -> Self {
184        self.trace.content = on;
185        self
186    }
187
188    /// Sends trace records to `sink` instead of a file.
189    /// Takes effect only with tracing on; replaces `trace_file`.
190    /// Returns the builder.
191    pub fn trace_to(mut self, sink: Arc<dyn TraceSink>) -> Self {
192        self.trace.sink = Some(sink);
193        self.trace.file = None;
194        self
195    }
196
197    /// Writes trace records to the new file `path`; an existing file is
198    /// refused at `build`. Takes effect only with tracing on; replaces
199    /// `trace_to`.
200    pub fn trace_file(mut self, path: impl AsRef<Path>) -> Self {
201        self.trace.file = Some(path.as_ref().to_path_buf());
202        self.trace.sink = None;
203        self
204    }
205}