Files
leleka/desktop-core/src/runtime_tool_response.rs
T

362 lines
12 KiB
Rust

//! Buffered publication of an entirely validated tool-bearing completion.
//! This module performs no inference, retry, tool execution or schema lookup.
use crate::{runtime_rpc::proto::Usage, runtime_tools::ValidatedSegment};
use axum::body::Bytes;
use serde_json::{Value, json};
mod preflight;
use preflight::preflight;
const DELTA_BYTES: usize = 8192;
pub struct ToolResponse {
id: String,
model: String,
created_at: u64,
sequence: u64,
begun: bool,
terminal: Option<Value>,
}
/// The JSON field and the two delta events that carry the text of one kind of call.
struct CallEvents {
field: &'static str,
delta: &'static str,
done: &'static str,
id_prefix: &'static str,
}
/// An output item of the response: its id and its position in the output.
#[derive(Clone, Copy)]
struct ItemRef<'a> {
id: &'a str,
index: usize,
}
/// The event that carries a text delta and whether it is a content-part delta (with `content_index` and `logprobs`).
#[derive(Clone, Copy)]
struct DeltaKind<'a> {
event: &'a str,
is_content_part: bool,
}
impl<'a> DeltaKind<'a> {
/// The delta of an assistant message's text.
const TEXT: DeltaKind<'static> = DeltaKind {
event: "response.output_text.delta",
is_content_part: true,
};
/// The delta of a tool call's arguments or input.
fn call(event: &'a str) -> Self {
Self {
event,
is_content_part: false,
}
}
}
impl ToolResponse {
pub fn new(id: String, model: String) -> Self {
Self {
id,
model,
created_at: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |value| value.as_secs()),
sequence: 0,
begun: false,
terminal: None,
}
}
/// Metadata only: no speculative empty message or callable item.
pub fn beginning(&mut self) -> Vec<Bytes> {
if self.begun || self.terminal.is_some() {
return Vec::new();
}
self.begun = true;
let response = self.response("in_progress", Vec::new(), Value::Null);
vec![
self.event("response.created", json!({"response":response})),
self.event("response.in_progress", json!({"response":response})),
]
}
/// The caller supplies only a successful runtime terminal followed by true
/// EOF and complete choice/schema/grammar validation. Preflight is atomic:
/// an error leaves this publisher untouched, including IDs and sequence.
pub fn complete(
&mut self,
segments: Vec<ValidatedSegment>,
usage: &Usage,
reason: &str,
) -> Result<(Vec<Bytes>, Value), &'static str> {
if self.terminal.is_some() {
return Err("response_already_terminal");
}
let status = status_for_finish_reason(reason)?;
let total = sum_usage_tokens(usage)?;
preflight(&segments)?;
let mut events = self.beginning();
let output = self.publish_segments(&mut events, segments, status);
let response = self.response(status, output, build_usage_json(usage, total));
events.push(self.event(
event_kind_for_finish_reason(reason),
json!({"response":response}),
));
self.terminal = Some(response.clone());
Ok((events, response))
}
/// One output item per non-empty segment; returns the finished items in order.
fn publish_segments(
&mut self,
events: &mut Vec<Bytes>,
segments: Vec<ValidatedSegment>,
status: &str,
) -> Vec<Value> {
let mut output = Vec::new();
for segment in segments {
let index = output.len();
let item = match segment {
ValidatedSegment::Text(text) if text.is_empty() => continue,
ValidatedSegment::Text(text) => self.publish_text(events, index, &text, status),
ValidatedSegment::Call(item) => self.publish_call(events, index, item),
};
output.push(item);
}
output
}
/// The events of one assistant message: opened, text deltas, closed.
fn publish_text(
&mut self,
events: &mut Vec<Bytes>,
index: usize,
text: &str,
status: &str,
) -> Value {
let id = format!("msg_{}", uuid::Uuid::new_v4());
self.open_text_item(events, index, &id);
self.deltas(events, DeltaKind::TEXT, ItemRef { id: &id, index }, text);
self.close_text_item(events, ItemRef { id: &id, index }, text, status)
}
/// Item added and the still empty content part added.
fn open_text_item(&mut self, events: &mut Vec<Bytes>, index: usize, id: &str) {
let pending = json!({
"id":id,"type":"message","role":"assistant","status":"in_progress","content":[]
});
events.push(self.event(
"response.output_item.added",
json!({"output_index":index,"item":pending}),
));
events.push(self.event(
"response.content_part.added",
json!({"item_id":id,"output_index":index,"content_index":0,"part":text_part("")}),
));
}
/// Text done, part done, item done; returns the finished item.
fn close_text_item(
&mut self,
events: &mut Vec<Bytes>,
item: ItemRef<'_>,
text: &str,
status: &str,
) -> Value {
let ItemRef { id, index } = item;
events.push(self.event(
"response.output_text.done",
json!({"item_id":id,"output_index":index,"content_index":0,"text":text,"logprobs":[]}),
));
let part = text_part(text);
events.push(self.event(
"response.content_part.done",
json!({"item_id":id,"output_index":index,"content_index":0,"part":part}),
));
let item = json!({
"id":id,"type":"message","role":"assistant","status":status,"content":[part]
});
events.push(self.event(
"response.output_item.done",
json!({"output_index":index,"item":item}),
));
item
}
/// The events of one tool call: added, argument deltas, done, item done.
fn publish_call(&mut self, events: &mut Vec<Bytes>, index: usize, mut item: Value) -> Value {
// All calls, including later segments, passed preflight
// before the first public item/call identity is minted.
let kind = events_for_call_kind(item["type"] == "custom_tool_call");
let id = format!("{}{}", kind.id_prefix, uuid::Uuid::new_v4());
item["id"] = json!(id);
item["call_id"] = json!(format!("call_{}", uuid::Uuid::new_v4()));
item["status"] = json!("completed");
let mut pending = item.clone();
pending["status"] = json!("in_progress");
pending[kind.field] = json!("");
events.push(self.event(
"response.output_item.added",
json!({"output_index":index,"item":pending}),
));
// The string type was checked before publication.
let content = item[kind.field].as_str().expect("preflight call string");
let delta = DeltaKind::call(kind.delta);
self.deltas(events, delta, ItemRef { id: &id, index }, content);
let mut done_value = json!({"item_id":id,"output_index":index});
done_value[kind.field] = item[kind.field].clone();
events.push(self.event(kind.done, done_value));
events.push(self.event(
"response.output_item.done",
json!({"output_index":index,"item":item}),
));
item
}
/// A second terminal never produces another event or changes final state.
pub fn failed(&mut self, code: &str) -> (Vec<Bytes>, Value) {
if let Some(response) = &self.terminal {
return (Vec::new(), response.clone());
}
let mut events = self.beginning();
let mut response = self.response("failed", Vec::new(), Value::Null);
let code = public_failure_code(code);
response["error"] = json!({"code":code,"message":code});
events.push(self.event("response.failed", json!({"response":response})));
self.terminal = Some(response.clone());
(events, response)
}
fn response(&self, status: &str, output: Vec<Value>, usage: Value) -> Value {
let incomplete = if status == "incomplete" {
json!({"reason":"max_output_tokens"})
} else {
Value::Null
};
json!({
"id":self.id,"object":"response","created_at":self.created_at,"model":self.model,
"status":status,"output":output,"usage":usage,"error":null,
"incomplete_details":incomplete
})
}
fn event(&mut self, kind: &str, mut value: Value) -> Bytes {
value["type"] = json!(kind);
value["sequence_number"] = json!(self.sequence);
value["response_id"] = json!(self.id);
// Private sequence starts at zero and can only advance through this
// bounded one-completion lifecycle; callers cannot set it.
self.sequence += 1;
Bytes::from(format!("event: {kind}\ndata: {value}\n\n"))
}
fn deltas(
&mut self,
events: &mut Vec<Bytes>,
delta: DeltaKind<'_>,
item: ItemRef<'_>,
text: &str,
) {
let DeltaKind {
event: kind,
is_content_part,
} = delta;
let ItemRef { id, index } = item;
let mut rest = text;
if rest.is_empty() && !is_content_part {
events.push(self.event(kind, json!({"item_id":id,"output_index":index,"delta":""})));
}
while !rest.is_empty() {
let mut end = rest.len().min(DELTA_BYTES);
while !rest.is_char_boundary(end) {
end -= 1;
}
let mut value = json!({"item_id":id,"output_index":index,"delta":&rest[..end]});
if is_content_part {
value["content_index"] = json!(0);
value["logprobs"] = json!([]);
}
events.push(self.event(kind, value));
rest = &rest[end..];
}
}
}
fn status_for_finish_reason(reason: &str) -> Result<&'static str, &'static str> {
match reason {
"stop" => Ok("completed"),
"length" => Ok("incomplete"),
_ => Err("invalid_terminal_reason"),
}
}
fn event_kind_for_finish_reason(reason: &str) -> &'static str {
if reason == "length" {
"response.incomplete"
} else {
"response.completed"
}
}
fn sum_usage_tokens(usage: &Usage) -> Result<u64, &'static str> {
let total = usage
.input_tokens
.checked_add(usage.output_tokens)
.ok_or("invalid_usage")?;
if usage.reused_input_tokens > usage.input_tokens {
return Err("invalid_usage");
}
Ok(total)
}
fn build_usage_json(usage: &Usage, total: u64) -> Value {
json!({
"input_tokens":usage.input_tokens,"output_tokens":usage.output_tokens,"total_tokens":total,
"input_tokens_details":{"cached_tokens":usage.reused_input_tokens}
})
}
fn events_for_call_kind(custom: bool) -> CallEvents {
if custom {
CallEvents {
field: "input",
delta: "response.custom_tool_call_input.delta",
done: "response.custom_tool_call_input.done",
id_prefix: "ctc_",
}
} else {
CallEvents {
field: "arguments",
delta: "response.function_call_arguments.delta",
done: "response.function_call_arguments.done",
id_prefix: "fc_",
}
}
}
/// The failure codes a client may see; every other code is reported as a generation failure.
fn public_failure_code(code: &str) -> &str {
match code {
"runtime_interrupted"
| "runtime_protocol_failed"
| "runtime_missing_terminal"
| "runtime_generation_failed"
| "runtime_cancelled"
| "invalid_tool_output"
| "tool_output_invalid"
| "tool_validation_failed"
| "tool_output_limit"
| "response_limit"
| "runtime_tool_output_invalid"
| "tool_retry_exhausted" => code,
_ => "runtime_generation_failed",
}
}
fn text_part(text: &str) -> Value {
json!({"type":"output_text","text":text,"annotations":[],"logprobs":[]})
}