314 lines
12 KiB
Rust
314 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};
|
|
|
|
const OUTPUT_LIMIT: usize = 8 * 1024 * 1024;
|
|
const SEGMENT_LIMIT: usize = 1024;
|
|
const CALL_LIMIT: usize = 128;
|
|
const DELTA_BYTES: usize = 8192;
|
|
|
|
pub struct ToolResponse {
|
|
id: String,
|
|
model: String,
|
|
created_at: u64,
|
|
sequence: u64,
|
|
begun: bool,
|
|
terminal: Option<Value>,
|
|
}
|
|
|
|
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 = match reason {
|
|
"stop" => "completed",
|
|
"length" => "incomplete",
|
|
_ => return Err("invalid_terminal_reason"),
|
|
};
|
|
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");
|
|
}
|
|
preflight(&segments)?;
|
|
let mut events = self.beginning();
|
|
let mut output = Vec::new();
|
|
for segment in segments {
|
|
let index = output.len();
|
|
match segment {
|
|
ValidatedSegment::Text(text) if text.is_empty() => {}
|
|
ValidatedSegment::Text(text) => {
|
|
let id = format!("msg_{}", uuid::Uuid::new_v4());
|
|
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("")})));
|
|
self.deltas(
|
|
&mut events,
|
|
"response.output_text.delta",
|
|
&id,
|
|
index,
|
|
&text,
|
|
true,
|
|
);
|
|
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}),
|
|
));
|
|
output.push(item);
|
|
}
|
|
ValidatedSegment::Call(mut item) => {
|
|
// All calls, including later segments, passed preflight
|
|
// before the first public item/call identity is minted.
|
|
let custom = item["type"] == "custom_tool_call";
|
|
let (field, delta, done) = if custom {
|
|
(
|
|
"input",
|
|
"response.custom_tool_call_input.delta",
|
|
"response.custom_tool_call_input.done",
|
|
)
|
|
} else {
|
|
(
|
|
"arguments",
|
|
"response.function_call_arguments.delta",
|
|
"response.function_call_arguments.done",
|
|
)
|
|
};
|
|
let id = format!(
|
|
"{}{}",
|
|
if custom { "ctc_" } else { "fc_" },
|
|
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[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[field].as_str().expect("preflight call string");
|
|
self.deltas(&mut events, delta, &id, index, content, false);
|
|
let mut done_value = json!({"item_id":id,"output_index":index});
|
|
done_value[field] = item[field].clone();
|
|
events.push(self.event(done, done_value));
|
|
events.push(self.event(
|
|
"response.output_item.done",
|
|
json!({"output_index":index,"item":item}),
|
|
));
|
|
output.push(item);
|
|
}
|
|
}
|
|
}
|
|
let usage = json!({"input_tokens":usage.input_tokens,"output_tokens":usage.output_tokens,"total_tokens":total,"input_tokens_details":{"cached_tokens":usage.reused_input_tokens}});
|
|
let response = self.response(status, output, usage);
|
|
events.push(self.event(
|
|
if reason == "length" {
|
|
"response.incomplete"
|
|
} else {
|
|
"response.completed"
|
|
},
|
|
json!({"response":response}),
|
|
));
|
|
self.terminal = Some(response.clone());
|
|
Ok((events, response))
|
|
}
|
|
|
|
/// 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 = 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",
|
|
};
|
|
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 {
|
|
json!({"id":self.id,"object":"response","created_at":self.created_at,"model":self.model,"status":status,"output":output,"usage":usage,"error":null,"incomplete_details":if status=="incomplete" {json!({"reason":"max_output_tokens"})} else {Value::Null}})
|
|
}
|
|
|
|
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>,
|
|
kind: &str,
|
|
id: &str,
|
|
index: usize,
|
|
text: &str,
|
|
content: bool,
|
|
) {
|
|
let mut rest = text;
|
|
if rest.is_empty() && !content {
|
|
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 content {
|
|
value["content_index"] = json!(0);
|
|
value["logprobs"] = json!([]);
|
|
}
|
|
events.push(self.event(kind, value));
|
|
rest = &rest[end..];
|
|
}
|
|
}
|
|
}
|
|
|
|
fn text_part(text: &str) -> Value {
|
|
json!({"type":"output_text","text":text,"annotations":[],"logprobs":[]})
|
|
}
|
|
|
|
fn valid_name(value: &Value) -> bool {
|
|
value.as_str().is_some_and(|name| {
|
|
!name.is_empty()
|
|
&& name.len() <= 64
|
|
&& name
|
|
.bytes()
|
|
.all(|b| b.is_ascii_alphanumeric() || b"_-".contains(&b))
|
|
})
|
|
}
|
|
|
|
fn preflight(segments: &[ValidatedSegment]) -> Result<(), &'static str> {
|
|
if segments.len() > SEGMENT_LIMIT {
|
|
return Err("response_limit");
|
|
}
|
|
let mut bytes = 0usize;
|
|
let mut calls = 0usize;
|
|
for segment in segments {
|
|
let size = match segment {
|
|
ValidatedSegment::Text(text) => {
|
|
if text.len() > OUTPUT_LIMIT {
|
|
return Err("response_limit");
|
|
}
|
|
text.len()
|
|
}
|
|
ValidatedSegment::Call(item) => {
|
|
calls += 1;
|
|
if calls > CALL_LIMIT {
|
|
return Err("response_limit");
|
|
}
|
|
let fields = item.as_object().ok_or("invalid_tool_item")?;
|
|
let field = match item["type"].as_str() {
|
|
Some("function_call") => "arguments",
|
|
Some("custom_tool_call") => "input",
|
|
_ => return Err("invalid_tool_item"),
|
|
};
|
|
if fields.keys().any(|key| {
|
|
!matches!(key.as_str(), "type" | "name" | "namespace") && key != field
|
|
}) || !valid_name(&item["name"])
|
|
|| item.get("namespace").is_some_and(|v| !valid_name(v))
|
|
{
|
|
return Err("invalid_tool_item");
|
|
}
|
|
let value = item[field].as_str().ok_or("invalid_tool_item")?;
|
|
if value.len() > OUTPUT_LIMIT {
|
|
return Err("response_limit");
|
|
}
|
|
if field == "arguments"
|
|
&& !serde_json::from_str::<Value>(value).is_ok_and(|v| v.is_object())
|
|
{
|
|
return Err("invalid_tool_item");
|
|
}
|
|
value
|
|
.len()
|
|
.checked_add(item["name"].as_str().map_or(0, str::len))
|
|
.and_then(|size| {
|
|
size.checked_add(
|
|
item.get("namespace")
|
|
.and_then(Value::as_str)
|
|
.map_or(0, str::len),
|
|
)
|
|
})
|
|
.ok_or("response_limit")?
|
|
}
|
|
};
|
|
bytes = bytes.checked_add(size).ok_or("response_limit")?;
|
|
if bytes > OUTPUT_LIMIT {
|
|
return Err("response_limit");
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|