use std::io;
use aither_core::llm::tool::ToolDefinition;
use aither_core::llm::{Message, Role};
use sha2::{Digest, Sha256};
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum PrefixBlock {
Tools,
Message {
index: usize,
role: Role,
},
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PrefixChain {
blocks: Vec<PrefixBlock>,
links: Vec<u64>,
cached: usize,
}
impl PrefixChain {
#[must_use]
pub fn of(definitions: &[ToolDefinition], messages: &[Message]) -> Self {
let mut hasher = HashWriter(Sha256::new());
let mut blocks = Vec::with_capacity(messages.len() + 1);
let mut links = Vec::with_capacity(messages.len() + 1);
serde_json::to_writer(&mut hasher, definitions).expect("tool definitions serialize");
blocks.push(PrefixBlock::Tools);
links.push(hasher.link());
for (index, message) in messages.iter().enumerate() {
serde_json::to_writer(&mut hasher, message).expect("messages serialize");
blocks.push(PrefixBlock::Message {
index,
role: message.role(),
});
links.push(hasher.link());
}
let cached = 1 + super::cache::stable_conversation_end(messages).map_or(0, |end| end + 1);
Self {
blocks,
links,
cached,
}
}
#[must_use]
pub fn first_divergence(&self, previous: &Self) -> Option<PrefixBlock> {
(0..previous.cached)
.find(|&index| self.links.get(index) != previous.links.get(index))
.map(|index| {
self.blocks
.get(index)
.copied()
.unwrap_or(previous.blocks[index])
})
}
#[must_use]
pub const fn len(&self) -> usize {
self.links.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.links.is_empty()
}
#[must_use]
pub const fn cached_blocks(&self) -> usize {
self.cached
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct PrefixRewrites {
pub compacted: bool,
pub reassembled: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PromptPrefix {
pub chain: PrefixChain,
pub rewrites: PrefixRewrites,
pub first_request: bool,
}
struct HashWriter(Sha256);
impl HashWriter {
fn link(&self) -> u64 {
let digest = self.0.clone().finalize();
let head = digest
.first_chunk::<8>()
.expect("a SHA-256 digest is 32 bytes");
u64::from_le_bytes(*head)
}
}
impl io::Write for HashWriter {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
self.0.update(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn conversation() -> Vec<Message> {
vec![
Message::system("prefix"),
Message::user("hello"),
Message::assistant("hi"),
Message::system("live tail"),
]
}
fn tool(name: &'static str) -> ToolDefinition {
ToolDefinition::from_parts(
name.into(),
"runs a command".into(),
serde_json::json!({"type": "object"}),
)
.expect("an object schema is valid")
}
#[test]
fn an_unchanged_prefix_with_a_new_tail_does_not_diverge() {
let tools = [tool("terminal")];
let first = PrefixChain::of(&tools, &conversation());
let mut next = conversation();
next.pop();
next.extend([Message::user("again"), Message::system("new tail")]);
let second = PrefixChain::of(&tools, &next);
assert_eq!(second.first_divergence(&first), None);
assert_eq!(
first.cached_blocks(),
4,
"tools plus every message but the tail"
);
}
#[test]
fn a_changed_tool_set_diverges_at_the_tools() {
let first = PrefixChain::of(&[tool("terminal")], &conversation());
let second = PrefixChain::of(&[tool("terminal"), tool("monitor")], &conversation());
assert_eq!(second.first_divergence(&first), Some(PrefixBlock::Tools));
}
#[test]
fn a_changed_message_names_its_index_and_role() {
let tools = [tool("terminal")];
let first = PrefixChain::of(&tools, &conversation());
let mut edited = conversation();
edited[1] = Message::user("hello there");
let second = PrefixChain::of(&tools, &edited);
assert_eq!(
second.first_divergence(&first),
Some(PrefixBlock::Message {
index: 1,
role: Role::User
})
);
}
#[test]
fn a_shorter_request_diverges_at_the_first_missing_block() {
let tools = [tool("terminal")];
let first = PrefixChain::of(&tools, &conversation());
let second = PrefixChain::of(&tools, &[Message::system("prefix")]);
assert_eq!(
second.first_divergence(&first),
Some(PrefixBlock::Message {
index: 1,
role: Role::User
})
);
}
#[test]
fn a_chain_survives_serialization() {
let chain = PrefixChain::of(&[tool("terminal")], &conversation());
let text = serde_json::to_string(&chain).expect("serializes");
let back: PrefixChain = serde_json::from_str(&text).expect("deserializes");
assert_eq!(back, chain);
assert_eq!(back.len(), 5);
}
}