Files
leleka/control-plane/src/chat.rs
T
Pavlo RatushnyiandClaude Sonnet 5.5 81b907030f feat(vision): picture parts in the Chat, Messages and Responses dialects, the strata-vision encoder client and GENI embeddings
The three adapters reduce pictures to a Responses input_image, the prompt renderer writes the template's
picture items and returns their sources in prompt order, and the request path encodes them (in turn with the
engine), expands every image pad to its token count and sends GENI with the combined SVE1 file. The encoder
is configured by a top-level vision section, stops with the engine and starts before it. Goldens recorded from
the Python handlers cover fourteen Chat and Messages requests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-14 16:46:59 +02:00

654 lines
23 KiB
Rust

//! Stateless, one-choice Chat Completions adapter over native Responses.
use crate::{app::AppState, responses};
use axum::{
Json,
body::{Body, to_bytes},
extract::{State, rejection::JsonRejection},
http::StatusCode,
response::{IntoResponse, Response, Sse, sse::Event},
};
use futures_core::Stream;
use serde::Deserialize;
use serde_json::{Value, json};
use std::{
convert::Infallible,
pin::Pin,
task::{Context, Poll},
};
use tokio::sync::mpsc;
use crate::native_events::{MAX_EVENT, NativeEvents};
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Request {
model: String,
messages: Vec<Message>,
#[serde(default)]
stream: bool,
stream_options: Option<StreamOptions>,
n: Option<u32>,
max_tokens: Option<u32>,
max_completion_tokens: Option<u32>,
temperature: Option<f64>,
top_p: Option<f64>,
#[serde(default)]
tools: Vec<Tool>,
tool_choice: Option<Value>,
parallel_tool_calls: Option<bool>,
response_format: Option<Value>,
reasoning_effort: Option<String>,
store: Option<bool>,
stop: Option<Value>,
logprobs: Option<bool>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StreamOptions {
include_usage: Option<bool>,
include_obfuscation: Option<bool>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Message {
role: String,
content: Option<Value>,
tool_calls: Option<Vec<Call>>,
tool_call_id: Option<String>,
refusal: Option<String>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Call {
id: String,
#[serde(rename = "type")]
kind: String,
function: CallFunction,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CallFunction {
name: String,
arguments: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Tool {
#[serde(rename = "type")]
kind: String,
function: Function,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Function {
name: String,
description: Option<String>,
parameters: Option<Value>,
strict: Option<bool>,
}
type Invalid = (&'static str, &'static str);
fn invalid(param: &'static str, message: &'static str) -> Invalid {
(param, message)
}
/// A message's content: plain text, or (user messages only) the list of text and picture parts in the Responses
/// shape (`input_text` / `input_image`), whose order the template keeps.
enum Content {
Text(String),
Parts(Vec<Value>),
}
impl Content {
fn text(self) -> Option<String> {
match self {
Self::Text(text) => Some(text),
Self::Parts(_) => None,
}
}
fn into_value(self) -> Value {
match self {
Self::Text(text) => Value::String(text),
Self::Parts(parts) => Value::Array(parts),
}
}
}
/// An `image_url` part (`serve/frontend.py` `_image_source`): `"image_url": {"url": ..., "detail": ...}` or the bare
/// string. The source itself is checked when it is read, so an empty one fails there with the Python server's words.
fn image_part(part: &serde_json::Map<String, Value>) -> Result<Value, Invalid> {
let bad = || {
invalid(
"messages",
"image_url parts need an image_url of text or {url, detail}",
)
};
if part
.keys()
.any(|k| !matches!(k.as_str(), "type" | "image_url"))
{
return Err(bad());
}
let url = match part.get("image_url") {
None | Some(Value::Null) => String::new(),
Some(Value::String(url)) => url.clone(),
Some(Value::Object(object)) => {
if object
.keys()
.any(|k| !matches!(k.as_str(), "url" | "detail"))
{
return Err(bad());
}
match object.get("url") {
None | Some(Value::Null) => String::new(),
Some(Value::String(url)) => url.clone(),
_ => return Err(bad()),
}
}
_ => return Err(bad()),
};
Ok(json!({"type": "input_image", "image_url": url}))
}
fn content(value: Option<Value>, role: &str) -> Result<Option<Content>, Invalid> {
match value {
None | Some(Value::Null) => Ok(None),
Some(Value::String(s)) => Ok(Some(Content::Text(s))),
Some(Value::Array(parts)) => {
let mut text = String::new();
let mut listed = Vec::new();
let mut pictures = false;
for part in parts {
let object = part
.as_object()
.ok_or(invalid("messages", "content must contain text parts"))?;
if part["type"] == "image_url" {
if role != "user" {
return Err(invalid(
"messages",
"image content is only supported in user messages",
));
}
pictures = true;
listed.push(image_part(object)?);
continue;
}
if object.len() != 2 || part["type"] != "text" {
return Err(invalid(
"messages",
"only text and image_url content parts are supported",
));
}
let piece = part["text"]
.as_str()
.ok_or(invalid("messages", "text part needs a string"))?;
text.push_str(piece);
listed.push(json!({"type": "input_text", "text": piece}));
}
Ok(Some(if pictures {
Content::Parts(listed)
} else {
Content::Text(text)
}))
}
_ => Err(invalid("messages", "content must be text or text parts")),
}
}
impl Request {
fn into_responses(self) -> Result<(Value, bool, bool), Invalid> {
if self.n.is_some_and(|n| n != 1) {
return Err(invalid("n", "only n=1 is supported"));
}
if self.max_tokens.is_some() && self.max_completion_tokens.is_some() {
return Err(invalid(
"max_completion_tokens",
"specify only one output token limit",
));
}
if self
.reasoning_effort
.as_deref()
.is_some_and(|e| e != "none")
{
return Err(invalid(
"reasoning_effort",
"this Chat subset supports only reasoning_effort=none",
));
}
if self.store == Some(true) {
return Err(invalid(
"store",
"stored Chat completions are not supported",
));
}
if self.stop.is_some() {
return Err(invalid("stop", "custom stop sequences are not supported"));
}
if self.logprobs == Some(true) {
return Err(invalid("logprobs", "log probabilities are not supported"));
}
if !self.stream && self.stream_options.is_some() {
return Err(invalid(
"stream_options",
"stream_options requires stream=true",
));
}
if self
.stream_options
.as_ref()
.is_some_and(|s| s.include_obfuscation == Some(true))
{
return Err(invalid(
"stream_options",
"stream obfuscation is not supported",
));
}
let include_usage = self
.stream_options
.is_some_and(|s| s.include_usage == Some(true));
let mut input = Vec::new();
for message in self.messages {
if message.refusal.is_some() {
return Err(invalid("messages", "refusal content is not supported"));
}
let text = content(message.content, &message.role)?;
match message.role.as_str() {
"system" | "developer" | "user" | "assistant" => {
if message.tool_call_id.is_some()
|| (message.role != "assistant" && message.tool_calls.is_some())
{
return Err(invalid(
"messages",
"tool_calls belongs to assistant; tool_call_id belongs to tool",
));
}
let calls = message.tool_calls.unwrap_or_default();
if text.is_none() && calls.is_empty() {
return Err(invalid(
"messages",
"message needs text or assistant tool calls",
));
}
if let Some(text) = text {
input.push(json!({"role":message.role,"content":text.into_value()}));
}
for call in calls {
if call.kind != "function" {
return Err(invalid(
"messages",
"only function tool calls are supported",
));
}
input.push(json!({"type":"function_call","call_id":call.id,"name":call.function.name,"arguments":call.function.arguments}));
}
}
"tool" => {
if message.tool_calls.is_some() {
return Err(invalid("messages", "tool result cannot declare tool calls"));
}
input.push(json!({"type":"function_call_output", "call_id":message.tool_call_id.ok_or(invalid("messages", "tool result needs tool_call_id"))?, "output":text.and_then(Content::text).ok_or(invalid("messages", "tool result needs text"))?}));
}
_ => return Err(invalid("messages", "unsupported message role")),
}
}
let mut tools = Vec::new();
for tool in self.tools {
if tool.kind != "function" {
return Err(invalid("tools", "only function tools are supported"));
}
let f = tool.function;
let mut value = json!({"type":"function","name":f.name,"parameters":f.parameters.unwrap_or(json!({"type":"object","properties":{}}))});
if let Some(description) = f.description {
value["description"] = json!(description);
}
if let Some(strict) = f.strict {
value["strict"] = json!(strict);
}
tools.push(value);
}
let choice = match self.tool_choice {
Some(Value::Object(value)) => {
if value.len() != 2 || value.get("type") != Some(&json!("function")) {
return Err(invalid("tool_choice", "unsupported tool choice"));
}
let function = value
.get("function")
.and_then(Value::as_object)
.ok_or(invalid("tool_choice", "forced function needs a name"))?;
if function.len() != 1 {
return Err(invalid("tool_choice", "forced function accepts only name"));
}
Some(
json!({"type":"function","name":function.get("name").and_then(Value::as_str).ok_or(invalid("tool_choice", "forced function needs a name"))?}),
)
}
choice => choice,
};
let format = match self.response_format {
Some(Value::Object(mut format))
if format.get("type") == Some(&json!("json_schema")) =>
{
if format.len() != 2 {
return Err(invalid(
"response_format",
"json_schema format requires a json_schema object",
));
}
let mut schema = format
.remove("json_schema")
.and_then(|v| v.as_object().cloned())
.ok_or(invalid(
"response_format",
"json_schema format requires a json_schema object",
))?;
if schema
.keys()
.any(|k| !matches!(k.as_str(), "name" | "schema" | "strict"))
{
return Err(invalid(
"response_format",
"supported json_schema fields are name, schema and strict",
));
}
schema.insert("type".into(), json!("json_schema"));
Some(Value::Object(schema))
}
Some(value) => {
if !value.as_object().is_some_and(|o| o.len() == 1)
|| !matches!(value["type"].as_str(), Some("text" | "json_object"))
{
return Err(invalid("response_format", "unsupported response format"));
}
Some(value)
}
None => None,
};
let mut request = json!({"model":self.model,"input":input,"stream":self.stream,"store":false,
"reasoning":{"effort":"none"},"tools":tools});
for (key, value) in [
(
"max_output_tokens",
self.max_completion_tokens
.or(self.max_tokens)
.map(|v| json!(v)),
),
("temperature", self.temperature.map(|v| json!(v))),
("top_p", self.top_p.map(|v| json!(v))),
(
"parallel_tool_calls",
self.parallel_tool_calls.map(|v| json!(v)),
),
("tool_choice", choice),
] {
if let Some(value) = value {
request[key] = value;
}
}
if let Some(format) = format {
request["text"] = json!({"format":format});
}
Ok((request, self.stream, include_usage))
}
}
fn usage(response: &Value) -> Value {
let u = &response["usage"];
json!({"prompt_tokens":u["input_tokens"],"completion_tokens":u["output_tokens"],"total_tokens":u["total_tokens"],
"prompt_tokens_details":{"cached_tokens":u["input_tokens_details"]["cached_tokens"]},
"completion_tokens_details":{"reasoning_tokens":u["output_tokens_details"]["reasoning_tokens"]}})
}
fn call(item: &Value) -> Value {
json!({"id":item["call_id"],"type":"function","function":{"name":item["name"],"arguments":item["arguments"]}})
}
fn finish(response: &Value) -> &'static str {
if response["status"] == "incomplete" {
"length"
} else if response["output"]
.as_array()
.is_some_and(|items| items.iter().any(|i| i["type"] == "function_call"))
{
"tool_calls"
} else {
"stop"
}
}
fn identity(response: &Value, object: &str) -> Value {
json!({"id":format!("chatcmpl-{}",response["id"].as_str().unwrap_or("unknown")),"object":object,
"created":response["created_at"],"model":response["model"]})
}
fn completion(response: &Value) -> Value {
let mut text = String::new();
let mut calls = Vec::new();
if let Some(items) = response["output"].as_array() {
for item in items {
if item["type"] == "function_call" {
calls.push(call(item));
}
if item["type"] == "message"
&& let Some(parts) = item["content"].as_array()
{
for part in parts {
if part["type"] == "output_text" {
text.push_str(part["text"].as_str().unwrap_or(""));
}
}
}
}
}
let mut message = json!({"role":"assistant","content":if text.is_empty() && !calls.is_empty() {Value::Null} else {json!(text)},"refusal":null});
if !calls.is_empty() {
message["tool_calls"] = json!(calls);
}
let mut value = identity(response, "chat.completion");
value["choices"] =
json!([{"index":0,"message":message,"finish_reason":finish(response),"logprobs":null}]);
value["usage"] = usage(response);
value
}
fn error(status: StatusCode, code: &str, param: Option<&str>, message: &str) -> Response {
(status,Json(json!({"error":{"type":if status.is_server_error(){"server_error"}else{"invalid_request_error"},"code":code,"param":param,"message":message}}))).into_response()
}
pub async fn create(
State(state): State<AppState>,
body: Result<Json<Value>, JsonRejection>,
) -> Response {
let Json(body) = match body {
Ok(body) => body,
Err(e) => return error(e.status(), "invalid_json", None, &e.to_string()),
};
// Sampling extensions (top_k, min_p, penalties, seed, ...) are validated once, by the native request.
let (body, extensions) = crate::sampling::split_extensions(body);
let request: Request = match serde_json::from_value(body) {
Ok(r) => r,
Err(e) => {
return error(
StatusCode::BAD_REQUEST,
"invalid_request",
None,
&e.to_string(),
);
}
};
let (mut request, stream, include_usage) = match request.into_responses() {
Ok(r) => r,
Err((p, m)) => {
return error(
StatusCode::BAD_REQUEST,
"unsupported_chat_feature",
Some(p),
m,
);
}
};
for (key, value) in extensions {
request[key] = value;
}
let response = responses::create(State(state), Ok(Json(request))).await;
if stream && response.status().is_success() {
return stream_response(response.into_body(), include_usage);
}
let status = response.status();
let bytes = match to_bytes(response.into_body(), MAX_EVENT).await {
Ok(b) => b,
Err(_) => {
return error(
StatusCode::BAD_GATEWAY,
"response_too_large",
None,
"native response could not be read within the adapter limit",
);
}
};
let mut value: Value = match serde_json::from_slice(&bytes) {
Ok(v) => v,
Err(_) => {
return error(
StatusCode::BAD_GATEWAY,
"invalid_native_response",
None,
"native response was not JSON",
);
}
};
if !status.is_success() {
if let Some(param) = value["error"]["param"].as_str() {
let mapped = match param {
"input" => "messages",
"max_output_tokens" => "max_completion_tokens",
"text" => "response_format",
p => p,
};
value["error"]["param"] = json!(mapped);
}
return (status, Json(value)).into_response();
}
Json(completion(&value)).into_response()
}
struct Events(mpsc::Receiver<Event>);
impl Stream for Events {
type Item = Result<Event, Infallible>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.0.poll_recv(cx).map(|v| v.map(Ok))
}
}
async fn send(sender: &mpsc::Sender<Event>, value: Value) -> Result<(), &'static str> {
sender
.send(Event::default().data(value.to_string()))
.await
.map_err(|_| "client disconnected")
}
fn chunk(base: &Value, delta: Value, reason: Value, include_usage: bool) -> Value {
let mut v = base.clone();
v["choices"] = json!([{"index":0,"delta":delta,"finish_reason":reason,"logprobs":null}]);
if include_usage {
v["usage"] = Value::Null;
}
v
}
async fn adapt(
body: &mut Body,
sender: &mpsc::Sender<Event>,
include_usage: bool,
) -> Result<(), &'static str> {
let mut reader = NativeEvents::new(body);
let mut base = None;
let mut calls = 0;
loop {
let event =
tokio::select! { _=sender.closed()=>return Ok(()), event=reader.next()=>event? };
match event["type"].as_str() {
Some("response.created") => {
let value = identity(&event["response"], "chat.completion.chunk");
send(
sender,
chunk(
&value,
json!({"role":"assistant","content":""}),
Value::Null,
include_usage,
),
)
.await?;
base = Some(value);
}
Some("response.output_text.delta") => {
send(
sender,
chunk(
base.as_ref().ok_or("missing stream identity")?,
json!({"content":event["delta"]}),
Value::Null,
include_usage,
),
)
.await?;
}
Some("response.output_item.done") if event["item"]["type"] == "function_call" => {
let mut item = call(&event["item"]);
item["index"] = json!(calls);
calls += 1;
send(
sender,
chunk(
base.as_ref().ok_or("missing stream identity")?,
json!({"tool_calls":[item]}),
Value::Null,
include_usage,
),
)
.await?;
}
Some("response.completed" | "response.incomplete") => {
let base = base.as_ref().ok_or("missing stream identity")?;
send(
sender,
chunk(
base,
json!({}),
json!(finish(&event["response"])),
include_usage,
),
)
.await?;
if include_usage {
let mut v = base.clone();
v["choices"] = json!([]);
v["usage"] = usage(&event["response"]);
send(sender, v).await?;
}
sender
.send(Event::default().data("[DONE]"))
.await
.map_err(|_| "client disconnected")?;
return Ok(());
}
Some("response.failed") => {
send(sender, json!({"error":event["response"]["error"]})).await?;
sender
.send(Event::default().data("[DONE]"))
.await
.map_err(|_| "client disconnected")?;
return Ok(());
}
_ => {}
}
}
}
fn stream_response(mut body: Body, include_usage: bool) -> Response {
let (sender, received) = mpsc::channel(8);
tokio::spawn(async move {
let outcome = adapt(&mut body, &sender, include_usage).await;
drop(body); // Release the native receiver before reporting an adapter failure.
if let Err(message) = outcome {
let _=send(&sender,json!({"error":{"type":"server_error","code":"chat_stream_failed","message":message}})).await;
let _ = sender.send(Event::default().data("[DONE]")).await;
}
});
Sse::new(Events(received))
.keep_alive(crate::native_events::keep_alive())
.into_response()
}