llm: anchor the cache breakpoint on every request of a turn #143

Open
JakeHillion wants to merge 1 commits from jj/pzuonmvspsol into main
pull from: jj/pzuonmvspsol
2 changed files with 124 additions and 66 deletions

No files matched your search

+17 -2
View File
@@ -376,9 +376,16 @@ impl LlmClient {
};
let cache_key = ctx.room_id.as_ref().map(|r| room_cache_key(r.as_str()));
// Where committed conversation ends and this turn begins. The caller's
// last message is the turn's opening message, and the loop below only
// ever appends to `all_messages`, so this boundary holds for every
// request the turn makes. It is what the cache breakpoint anchors
// behind — see `anchor_cache_breakpoint`.
let committed = messages.len().saturating_sub(1);
for _ in 0..MAX_TOOL_ITERATIONS {
let (response, prompt_tokens) = self
.complete_once(&all_messages, &tools_param, cache_key.as_deref())
.complete_once(&all_messages, committed, &tools_param, cache_key.as_deref())
.await?;
if let Some(tool_calls) = &response.tool_calls
@@ -487,9 +494,14 @@ impl LlmClient {
/// [`ResponseMessage`] so the tool-calling loop — and everything
/// downstream that persists [`ChatMessage`]s — is identical regardless of
/// which endpoint served the turn.
/// `committed` counts the leading `messages` that are durable conversation
/// rather than part of the turn in flight. Only the Responses arm uses it,
/// to place its cache breakpoint; chat completions leaves caching to the
/// provider.
async fn complete_once(
&self,
messages: &[ChatMessage],
committed: usize,
tools: &Option<Vec<ToolDefinition>>,
prompt_cache_key: Option<&str>,
) -> Result<(ResponseMessage, Option<usize>)> {
@@ -498,7 +510,10 @@ impl LlmClient {
self.send_chat_completion(messages, tools, prompt_cache_key)
.await
}
ApiKind::Responses => self.send_responses(messages, tools, prompt_cache_key).await,
ApiKind::Responses => {
self.send_responses(messages, committed, tools, prompt_cache_key)
.await
}
}
}
+107 -64
View File
@@ -7,9 +7,10 @@
//! statelessly — the full `input` is resent each turn, `previous_response_id`
//! is never used, and `store` is false so nothing is retained server-side. To
//! get prefix caching across turns we pin an explicit cache breakpoint at the
//! end of the stable prefix (see [`build_responses_input`]); the API's implicit
//! breakpoint placement only reliably caches the head of a multi-item `input`,
//! leaving the bulk of the history recomputed on every turn.
//! end of committed history, on every request (see
//! [`anchor_cache_breakpoint`]); the API's implicit breakpoint placement only
//! reliably caches the head of a multi-item `input`, leaving the bulk of the
//! history recomputed on every turn.
//!
//! Both directions translate to/from the shared [`ChatMessage`] model and
//! normalise into the same [`ResponseMessage`]/[`Usage`] the chat path yields,
@@ -235,13 +236,21 @@ impl From<ResponsesUsage> for Usage {
/// results become `function_call_output` items; everything else is a plain
/// role-tagged input message.
///
/// A single explicit cache breakpoint is then pinned to the end of the stable
/// prefix — see [`anchor_cache_breakpoint`].
fn build_responses_input(messages: &[ChatMessage]) -> (String, Vec<InputItem>) {
/// `committed` is how many leading `messages` are durable conversation, with
/// everything after them belonging to the turn being run right now. Messages do
/// not map one-to-one onto input items — system messages vanish into
/// `instructions`, an assistant message with tool calls expands into several
/// items — so the boundary is translated into an item index as the items are
/// built, and handed to [`anchor_cache_breakpoint`].
fn build_responses_input(messages: &[ChatMessage], committed: usize) -> (String, Vec<InputItem>) {
let mut instructions = String::new();
let mut input = Vec::new();
let mut committed_items = 0;
for m in messages {
for (index, m) in messages.iter().enumerate() {
if index == committed {
committed_items = input.len();
}
match m.role.as_str() {
"system" => {
if let Some(content) = &m.content {
@@ -285,36 +294,46 @@ fn build_responses_input(messages: &[ChatMessage]) -> (String, Vec<InputItem>) {
}
}
anchor_cache_breakpoint(&mut input);
if committed >= messages.len() {
committed_items = input.len();
}
anchor_cache_breakpoint(&mut input, committed_items);
(instructions, input)
}
/// Pin an explicit cache breakpoint at the end of the stable prefix: the last
/// non-empty text message *before* the final input item (the newly-appended
/// turn). Everything up to and including it — `instructions`, `tools`, and all
/// prior history — becomes the cached prefix, so only the new turn is
/// recomputed each request.
/// Pin our cache breakpoint at the end of committed history: the last item at
/// or before `committed_items` that can carry a content block. Everything up to
/// and including it — `instructions`, `tools`, and all prior history — becomes
/// the cached prefix.
///
/// We place it explicitly because the API's implicit breakpoint placement only
/// reliably caches the head of a multi-item `input`; measured against
/// production-shaped requests it left the ~50k-token history recomputed every
/// turn, capping cache reads at the `instructions`+`tools` head.
/// We place it ourselves because the API's implicit placement only reliably
/// caches the head of a multi-item `input`; measured against production-shaped
/// requests it left the ~50k-token history recomputed every turn, capping cache
/// reads at the `instructions`+`tools` head.
///
/// Only anchored when the final item is itself a fresh message turn. A tool
/// loop makes several requests within one turn, and every request after the
/// first ends in a `function_call_output`; that trailing tool traffic is
/// ephemeral — a silent tick discards the whole turn — so a breakpoint over it
/// could never be reused on a later turn and would only cost a cache write. We
/// leave those to the API's implicit placement, which already covers reuse
/// between the loop's own back-to-back calls. Likewise an opening turn with no
/// history has no message before the final item and anchors nothing — there is
/// no meaningful prefix to reuse yet.
fn anchor_cache_breakpoint(input: &mut [InputItem]) {
if !matches!(input.last(), Some(InputItem::Message { .. })) {
return;
}
let stable = input.len().saturating_sub(1);
let anchor = (0..stable).rev().find(|&i| {
/// The anchor sits *behind* the current turn, and that is the whole point. A
/// turn's own traffic is not durable: a tick that decides to stay silent throws
/// away its prompt, its tool calls and their results, so history is unchanged
/// when the next tick arrives. The last committed message is therefore the
/// furthest point guaranteed to repeat, and anchoring there puts the breakpoint
/// in the same place on every request — a turn's opening request and each pass
/// of its tool loop alike. One write is followed by reads, and a read refreshes
/// the prefix's lifetime for free.
///
/// The API's own implicit breakpoint, which lands after the newest message, is
/// left where it is. A write only bills what is new beyond the longest prefix
/// already cached, and this anchor is read on the same request, so all it ever
/// writes is the turn's own tail: cheap if the turn is discarded, already paid
/// for if it is kept, and enough for each pass of a tool loop to read the pass
/// before it.
///
/// A request with no committed history anchors nothing — the opening turn of a
/// conversation, or a one-shot prompt from the memory pipeline. There is no
/// prefix for a later request to reuse, and top-level `instructions` cannot
/// carry a breakpoint of its own.
fn anchor_cache_breakpoint(input: &mut [InputItem], committed_items: usize) {
let anchor = (0..committed_items.min(input.len())).rev().find(|&i| {
matches!(&input[i], InputItem::Message { content: MsgContent::Text(t), .. } if !t.is_empty())
});
if let Some(i) = anchor
@@ -329,6 +348,7 @@ fn anchor_cache_breakpoint(input: &mut [InputItem]) {
}
}
}
/// Collapse the Responses API's `output` item list into the same
/// [`ResponseMessage`] the chat-completions path produces: `output_text` parts
/// are concatenated into the reply and `function_call` items become
@@ -373,6 +393,7 @@ impl LlmClient {
pub(super) async fn send_responses(
&self,
messages: &[ChatMessage],
committed: usize,
tools: &Option<Vec<ToolDefinition>>,
prompt_cache_key: Option<&str>,
) -> Result<(ResponseMessage, Option<usize>)> {
@@ -381,7 +402,7 @@ impl LlmClient {
self.default_model.base_url.trim_end_matches('/')
);
let (instructions, input) = build_responses_input(messages);
let (instructions, input) = build_responses_input(messages, committed);
let request = ResponsesRequest {
model: self.default_model.model_id.clone(),
input,
@@ -440,7 +461,8 @@ mod tests {
ChatMessage::user("thanks, anything else?"),
];
let (instructions, items) = build_responses_input(&messages);
let committed = messages.len() - 1;
let (instructions, items) = build_responses_input(&messages, committed);
// System messages are concatenated into instructions, not input.
assert_eq!(instructions, "you are helpful\n\nbe terse");
@@ -496,7 +518,7 @@ mod tests {
ChatMessage::assistant("an answer"),
ChatMessage::user("second question"),
];
let (_, items) = build_responses_input(&messages);
let (_, items) = build_responses_input(&messages, messages.len() - 1);
let input = serde_json::to_value(&items).unwrap();
// Anchor is the assistant reply before the new user turn.
assert_eq!(input[1]["content"][0]["type"], "output_text");
@@ -508,7 +530,7 @@ mod tests {
// A user turn used as an anchor renders as `input_text`.
let two = vec![ChatMessage::user("only history"), ChatMessage::user("new")];
let (_, items) = build_responses_input(&two);
let (_, items) = build_responses_input(&two, two.len() - 1);
let input = serde_json::to_value(&items).unwrap();
assert_eq!(input[0]["content"][0]["type"], "input_text");
assert_eq!(input[0]["content"][0]["text"], "only history");
@@ -516,41 +538,62 @@ mod tests {
// An opening turn with nothing before it anchors nothing.
let one = vec![ChatMessage::system("sys"), ChatMessage::user("hello")];
let (_, items) = build_responses_input(&one);
let (_, items) = build_responses_input(&one, one.len() - 1);
let input = serde_json::to_value(&items).unwrap();
assert_eq!(input[0]["content"], "hello");
}
#[test]
fn cache_breakpoint_skips_mid_tool_loop_requests() {
// A request captured mid tool loop ends in a function_call_output, not
// a fresh message turn. That trailing tool traffic is ephemeral (a
// silent tick discards the whole turn), so nothing is anchored — the
// earlier user message stays a plain string with no breakpoint.
let messages = vec![
fn cache_breakpoint_holds_still_across_a_tool_loop() {
// Every request a turn makes must put the breakpoint on the same item.
// The turn's own traffic grows request by request and a silent tick
// discards all of it, so an anchor that drifted onto it would write a
// prefix nothing can read back — which is the whole cost we are trying
// to avoid.
let history = vec![
ChatMessage::system("sys"),
ChatMessage::user("what time is it?"),
ChatMessage {
role: "assistant".to_owned(),
content: None,
tool_calls: Some(vec![ToolCall {
id: "call_1".to_owned(),
call_type: "function".to_owned(),
function: FunctionCall {
name: "now".to_owned(),
arguments: "{}".to_owned(),
},
}]),
tool_call_id: None,
timestamp: None,
},
ChatMessage::tool_result("call_1", "12:00"),
ChatMessage::user("earlier question"),
ChatMessage::assistant("earlier answer"),
];
let (_, items) = build_responses_input(&messages);
let input = serde_json::to_value(&items).unwrap();
assert_eq!(input[2]["type"], "function_call_output");
assert_eq!(input[0]["type"], "message");
assert_eq!(input[0]["content"], "what time is it?");
let committed = history.len();
// Request one: history plus the tick that opened the turn.
let mut messages = history.clone();
messages.push(ChatMessage::user("[12:00] System Tick"));
let (_, opening) = build_responses_input(&messages, committed);
// Request two: the model called a tool, so the request now ends in a
// function_call_output rather than a message.
messages.push(ChatMessage {
role: "assistant".to_owned(),
content: None,
tool_calls: Some(vec![ToolCall {
id: "call_1".to_owned(),
call_type: "function".to_owned(),
function: FunctionCall {
name: "now".to_owned(),
arguments: "{}".to_owned(),
},
}]),
tool_call_id: None,
timestamp: None,
});
messages.push(ChatMessage::tool_result("call_1", "12:00"));
let (_, mid_loop) = build_responses_input(&messages, committed);
for items in [&opening, &mid_loop] {
let input = serde_json::to_value(items).unwrap();
assert_eq!(
input[1]["content"][0]["prompt_cache_breakpoint"]["mode"],
"explicit"
);
assert_eq!(input[1]["content"][0]["text"], "earlier answer");
// Nothing from the turn in flight carries one.
assert_eq!(input[2]["content"], "[12:00] System Tick");
}
let mid_loop = serde_json::to_value(&mid_loop).unwrap();
assert_eq!(mid_loop[3]["type"], "function_call");
assert_eq!(mid_loop[4]["type"], "function_call_output");
}
#[test]