#![forbid(unsafe_code)]
use std::collections::HashMap;
use std::sync::Mutex;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use weirdnet_agent::ToolCall;
use weirdnet_agent::remote::infer::v2::{Input, Request, Usage};
use weirdnet_agent::remote::pool::Answer;
use weirdnet_agent::remote::{from_cbor, to_cbor};
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct CachedAnswer {
pub model: String,
pub text: String,
#[serde(default)]
pub reasoning: String,
#[serde(default)]
pub tool_calls: Vec<ToolCall>,
pub finish_reason: Option<String>,
pub usage: Option<Usage>,
}
impl CachedAnswer {
pub fn new(model: impl Into<String>, text: impl Into<String>, finish_reason: impl Into<String>) -> Self {
Self { model: model.into(), text: text.into(), finish_reason: Some(finish_reason.into()), ..Default::default() }
}
pub fn complete(&self) -> bool {
matches!(self.finish_reason.as_deref(), Some("stop" | "length"))
}
}
impl From<&Answer> for CachedAnswer {
fn from(a: &Answer) -> Self {
Self {
model: a.model.clone(),
text: a.text.clone(),
reasoning: a.reasoning.clone(),
tool_calls: a.tool_calls.clone(),
finish_reason: a.finish_reason.clone(),
usage: a.usage,
}
}
}
pub trait AnswerCache: Send + Sync {
fn get(&self, model: &str, request: &Request) -> Option<CachedAnswer>;
fn put(&self, model: &str, request: &Request, answer: &CachedAnswer);
}
#[derive(Debug, Clone, Copy, Default)]
pub struct NoCache;
impl AnswerCache for NoCache {
fn get(&self, _: &str, _: &Request) -> Option<CachedAnswer> {
None
}
fn put(&self, _: &str, _: &Request, _: &CachedAnswer) {}
}
pub type Key = [u8; 32];
pub trait AnswerStore: Send + Sync {
fn get(&self, key: &Key) -> Option<Vec<u8>>;
fn put(&self, key: &Key, value: Vec<u8>);
fn remove(&self, key: &Key);
fn len(&self) -> usize;
fn is_empty(&self) -> bool {
self.len() == 0
}
}
type Entries = (u64, HashMap<Key, (u64, Vec<u8>)>);
pub struct MemoryStore {
max_entries: usize,
inner: Mutex<Entries>,
}
impl MemoryStore {
pub fn new(max_entries: usize) -> Self {
Self { max_entries: max_entries.max(1), inner: Mutex::new((0, HashMap::new())) }
}
fn lock(&self) -> std::sync::MutexGuard<'_, Entries> {
self.inner.lock().unwrap_or_else(|e| e.into_inner())
}
}
impl AnswerStore for MemoryStore {
fn get(&self, key: &Key) -> Option<Vec<u8>> {
let mut g = self.lock();
g.0 += 1;
let tick = g.0;
let hit = g.1.get_mut(key)?;
hit.0 = tick;
Some(hit.1.clone())
}
fn put(&self, key: &Key, value: Vec<u8>) {
let mut g = self.lock();
g.0 += 1;
let tick = g.0;
if g.1.len() >= self.max_entries
&& !g.1.contains_key(key)
&& let Some(oldest) = g.1.iter().min_by_key(|(_, v)| v.0).map(|(k, _)| *k)
{
g.1.remove(&oldest);
}
g.1.insert(*key, (tick, value));
}
fn remove(&self, key: &Key) {
self.lock().1.remove(key);
}
fn len(&self) -> usize {
self.lock().1.len()
}
}
pub fn deterministic(request: &Request) -> bool {
request.sampling.temperature == Some(0.0) && request.tools.is_empty() && matches!(request.input, Input::Messages(_))
}
pub fn exact_key(model: &str, request: &Request) -> Option<Key> {
if !deterministic(request) {
return None;
}
#[derive(Serialize)]
struct Parts<'a> {
v: u8,
model: &'a str,
input: &'a Input,
sampling: &'a weirdnet_agent::remote::infer::v2::Sampling,
seed: Option<u64>,
response_format: &'a Option<weirdnet_agent::remote::infer::v2::ResponseFormat>,
raw: bool,
}
let parts = Parts {
v: 1,
model,
input: &request.input,
sampling: &request.sampling,
seed: request.seed,
response_format: &request.response_format,
raw: request.raw,
};
let bytes = to_cbor(&parts).ok()?;
Some(Sha256::digest(&bytes).into())
}
pub struct ExactCache<S: AnswerStore = MemoryStore> {
store: S,
}
impl ExactCache<MemoryStore> {
pub fn new(max_entries: usize) -> Self {
Self { store: MemoryStore::new(max_entries) }
}
}
impl<S: AnswerStore> ExactCache<S> {
pub fn with_store(store: S) -> Self {
Self { store }
}
pub fn store(&self) -> &S {
&self.store
}
pub fn len(&self) -> usize {
self.store.len()
}
pub fn is_empty(&self) -> bool {
self.store.is_empty()
}
}
impl<S: AnswerStore> AnswerCache for ExactCache<S> {
fn get(&self, model: &str, request: &Request) -> Option<CachedAnswer> {
let key = exact_key(model, request)?;
let bytes = self.store.get(&key)?;
match from_cbor::<CachedAnswer>(&bytes) {
Ok(a) => Some(a),
Err(_) => {
self.store.remove(&key);
None
}
}
}
fn put(&self, model: &str, request: &Request, answer: &CachedAnswer) {
if !answer.complete() {
return;
}
let Some(key) = exact_key(model, request) else { return };
if let Ok(bytes) = to_cbor(answer) {
self.store.put(&key, bytes);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use weirdnet_agent::remote::infer::v2::{ContextRef, Sampling};
use weirdnet_agent::{Message, ToolSpec};
fn req(temp: f32, text: &str) -> Request {
let mut s = Sampling::default();
s.temperature = Some(temp);
Request::messages(vec![Message::user(text)]).with_sampling(s)
}
fn answer() -> CachedAnswer {
CachedAnswer::new("m", "hi", "stop")
}
#[test]
fn only_deterministic_requests_hit() {
let c = ExactCache::new(2);
c.put("m", &req(0.7, "a"), &answer());
assert!(c.is_empty());
c.put("m", &req(0.0, "a"), &answer());
assert_eq!(c.get("m", &req(0.0, "a")), Some(answer()));
assert!(c.get("other", &req(0.0, "a")).is_none());
assert!(c.get("m", &req(0.0, "b")).is_none());
assert!(c.get("m", &req(0.0, "a").with_seed(7)).is_none(), "the seed is part of the key");
}
#[test]
fn tools_and_context_refs_are_never_cached() {
let tool = ToolSpec::new("t", "a tool");
let with_tools = req(0.0, "a").with_tools(vec![tool]);
assert!(!deterministic(&with_tools));
let mut ctx = Request::context(ContextRef::new("conv", Some("head".into())));
ctx.sampling.temperature = Some(0.0);
assert!(!deterministic(&ctx));
assert!(exact_key("m", &ctx).is_none());
}
#[test]
fn evicts_least_recently_used() {
let c = ExactCache::new(2);
c.put("m", &req(0.0, "a"), &answer());
c.put("m", &req(0.0, "b"), &answer());
c.get("m", &req(0.0, "a"));
c.put("m", &req(0.0, "c"), &answer());
assert!(c.get("m", &req(0.0, "a")).is_some());
assert!(c.get("m", &req(0.0, "b")).is_none());
assert_eq!(c.len(), 2);
}
#[test]
fn keeps_only_finished_answers() {
let c = ExactCache::new(2);
c.put("m", &req(0.0, "a"), &CachedAnswer::new("m", "h", "cancelled"));
let mut none = answer();
none.finish_reason = None;
c.put("m", &req(0.0, "a"), &none);
assert!(c.is_empty());
c.put("m", &req(0.0, "a"), &CachedAnswer::new("m", "h", "length"));
assert_eq!(c.len(), 1);
}
#[test]
fn unreadable_entries_are_dropped() {
let c = ExactCache::new(2);
let key = exact_key("m", &req(0.0, "a")).unwrap();
c.store().put(&key, vec![0xff, 0x00]);
assert!(c.get("m", &req(0.0, "a")).is_none());
assert!(c.is_empty());
}
#[test]
fn from_a_pool_answer() {
let mut a = Answer::default();
a.text = "x".into();
a.model = "m".into();
a.finish_reason = Some("stop".into());
let cached = CachedAnswer::from(&a);
assert!(cached.complete());
assert_eq!((cached.text.as_str(), cached.model.as_str()), ("x", "m"));
}
}