|
| 1 | +//! What the AI answered for one transcript chunk, saved in the task workspace so a retry does not ask the AI again. |
| 2 | +
|
| 3 | +use std::collections::BTreeMap; |
| 4 | +use std::io::{BufReader, BufWriter}; |
| 5 | +use std::time::Duration; |
| 6 | + |
| 7 | +use anyhow::Context as _; |
| 8 | +use camino::{Utf8Path, Utf8PathBuf}; |
| 9 | +use devolutions_gateway_ai::Usage; |
| 10 | +use devolutions_gateway_ai::session_actions::Action; |
| 11 | + |
| 12 | +/// Tokens counted by the AI provider, as kept in checkpoints and Task results. |
| 13 | +/// |
| 14 | +/// It mirrors [`Usage`], so a change in the AI crate never changes what we store. |
| 15 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 16 | +#[serde(rename_all = "camelCase")] |
| 17 | +pub(super) struct TokenUsage { |
| 18 | + pub(super) input_tokens: u64, |
| 19 | + pub(super) output_tokens: u64, |
| 20 | +} |
| 21 | + |
| 22 | +impl From<Usage> for TokenUsage { |
| 23 | + fn from(usage: Usage) -> Self { |
| 24 | + Self { |
| 25 | + input_tokens: usage.input_tokens, |
| 26 | + output_tokens: usage.output_tokens, |
| 27 | + } |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +impl From<TokenUsage> for Usage { |
| 32 | + fn from(usage: TokenUsage) -> Self { |
| 33 | + Self { |
| 34 | + input_tokens: usage.input_tokens, |
| 35 | + output_tokens: usage.output_tokens, |
| 36 | + } |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +pub(super) fn path(workspace: &Utf8Path, index: usize) -> Utf8PathBuf { |
| 41 | + workspace.join(format!("chunk-{index:04}.json")) |
| 42 | +} |
| 43 | + |
| 44 | +/// Actions found in one chunk, with what the AI provider reported for the requests about it. |
| 45 | +#[derive(Debug, Clone, PartialEq)] |
| 46 | +pub(super) struct DescribedChunk { |
| 47 | + pub(super) actions: Vec<Action>, |
| 48 | + /// Model that answered, as reported by the provider. |
| 49 | + pub(super) model: Option<String>, |
| 50 | + /// Tokens of every request about the chunk, answers cut and asked again included; `None` when one was not reported. |
| 51 | + pub(super) usage: Option<Usage>, |
| 52 | +} |
| 53 | + |
| 54 | +#[derive(Serialize, Deserialize)] |
| 55 | +#[serde(rename_all = "camelCase")] |
| 56 | +struct SavedChunk { |
| 57 | + #[serde(default, skip_serializing_if = "Option::is_none")] |
| 58 | + model: Option<String>, |
| 59 | + #[serde(default, skip_serializing_if = "Option::is_none")] |
| 60 | + usage: Option<TokenUsage>, |
| 61 | + actions: Vec<SavedAction>, |
| 62 | +} |
| 63 | + |
| 64 | +#[derive(Serialize, Deserialize)] |
| 65 | +#[serde(rename_all = "camelCase")] |
| 66 | +struct SavedAction { |
| 67 | + offset_seconds: f64, |
| 68 | + description: String, |
| 69 | + #[serde(default, skip_serializing_if = "Option::is_none")] |
| 70 | + object: Option<String>, |
| 71 | + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] |
| 72 | + parameters: BTreeMap<String, String>, |
| 73 | +} |
| 74 | + |
| 75 | +/// Writes the checkpoint through a temporary file, so a crash never leaves a partial one. |
| 76 | +pub(super) fn write(path: &Utf8Path, chunk: &DescribedChunk) -> anyhow::Result<()> { |
| 77 | + let partial = path.with_extension("partial"); |
| 78 | + |
| 79 | + let saved = SavedChunk { |
| 80 | + model: chunk.model.clone(), |
| 81 | + usage: chunk.usage.map(TokenUsage::from), |
| 82 | + actions: chunk |
| 83 | + .actions |
| 84 | + .iter() |
| 85 | + .map(|action| SavedAction { |
| 86 | + offset_seconds: action.offset.as_secs_f64(), |
| 87 | + description: action.description.clone(), |
| 88 | + object: action.object.clone(), |
| 89 | + parameters: action.parameters.clone(), |
| 90 | + }) |
| 91 | + .collect(), |
| 92 | + }; |
| 93 | + |
| 94 | + let mut out = BufWriter::new(std::fs::File::create(&partial).with_context(|| format!("create {partial}"))?); |
| 95 | + serde_json::to_writer(&mut out, &saved)?; |
| 96 | + out.into_inner()?.sync_all()?; |
| 97 | + std::fs::rename(&partial, path).with_context(|| format!("rename {partial}"))?; |
| 98 | + |
| 99 | + Ok(()) |
| 100 | +} |
| 101 | + |
| 102 | +pub(super) fn read(path: &Utf8Path) -> anyhow::Result<DescribedChunk> { |
| 103 | + let file = BufReader::new(std::fs::File::open(path).with_context(|| format!("open {path}"))?); |
| 104 | + let saved: SavedChunk = serde_json::from_reader(file).with_context(|| format!("read {path}"))?; |
| 105 | + |
| 106 | + let actions = saved |
| 107 | + .actions |
| 108 | + .into_iter() |
| 109 | + .map(|saved| { |
| 110 | + Ok(Action { |
| 111 | + offset: Duration::try_from_secs_f64(saved.offset_seconds)?, |
| 112 | + description: saved.description, |
| 113 | + object: saved.object, |
| 114 | + parameters: saved.parameters, |
| 115 | + }) |
| 116 | + }) |
| 117 | + .collect::<anyhow::Result<_>>()?; |
| 118 | + |
| 119 | + Ok(DescribedChunk { |
| 120 | + actions, |
| 121 | + model: saved.model, |
| 122 | + usage: saved.usage.map(Usage::from), |
| 123 | + }) |
| 124 | +} |
| 125 | + |
| 126 | +#[cfg(test)] |
| 127 | +mod tests { |
| 128 | + use super::*; |
| 129 | + |
| 130 | + #[test] |
| 131 | + fn described_chunk_round_trips() { |
| 132 | + let dir = tempfile::tempdir().expect("temp dir"); |
| 133 | + let path = path(Utf8Path::from_path(dir.path()).expect("UTF-8"), 3); |
| 134 | + let chunk = DescribedChunk { |
| 135 | + actions: vec![ |
| 136 | + Action { |
| 137 | + offset: Duration::from_millis(1500), |
| 138 | + description: "Listed files".to_owned(), |
| 139 | + object: Some("/var/log".to_owned()), |
| 140 | + parameters: BTreeMap::from([("Command".to_owned(), "ls".to_owned())]), |
| 141 | + }, |
| 142 | + Action { |
| 143 | + offset: Duration::from_secs(62), |
| 144 | + description: "Closed the shell".to_owned(), |
| 145 | + object: None, |
| 146 | + parameters: BTreeMap::new(), |
| 147 | + }, |
| 148 | + ], |
| 149 | + model: Some("gpt-test-2026-09-30".to_owned()), |
| 150 | + usage: Some(Usage { |
| 151 | + input_tokens: 10, |
| 152 | + output_tokens: 20, |
| 153 | + }), |
| 154 | + }; |
| 155 | + |
| 156 | + write(&path, &chunk).expect("written"); |
| 157 | + |
| 158 | + assert!(path.as_str().ends_with("chunk-0003.json")); |
| 159 | + assert_eq!(read(&path).expect("read"), chunk); |
| 160 | + assert!(!path.with_extension("partial").exists()); |
| 161 | + } |
| 162 | + |
| 163 | + #[test] |
| 164 | + fn unreported_model_and_usage_stay_unknown() { |
| 165 | + let dir = tempfile::tempdir().expect("temp dir"); |
| 166 | + let path = path(Utf8Path::from_path(dir.path()).expect("UTF-8"), 0); |
| 167 | + let chunk = DescribedChunk { |
| 168 | + actions: Vec::new(), |
| 169 | + model: None, |
| 170 | + usage: None, |
| 171 | + }; |
| 172 | + |
| 173 | + write(&path, &chunk).expect("written"); |
| 174 | + |
| 175 | + assert_eq!(std::fs::read_to_string(&path).expect("checkpoint"), r#"{"actions":[]}"#); |
| 176 | + assert_eq!(read(&path).expect("read"), chunk); |
| 177 | + } |
| 178 | +} |
0 commit comments