STRA-338 S21: leleka-gateway-domain (layer L2): the pure gateway domain leaves strata-control
New crate crates/gateway-domain, the first member of layer L2 in architecture.json (L2 is now a pure layer: tokio, axum, reqwest, libc and the other adapter crates are forbidden dependencies there). It depends on serde, serde_json, leleka-sampler-ref and leleka-tokenizer only. Moved out of control-plane/src with git mv, content unchanged apart from paths: sampling (request sampling extensions, validation) and EngineTune (was in wire.rs), reasoning_budget (the budget driver and its tests), codec (Family, TextCodec, TokenDecoder, QwenCodec), json_order, and the Chat Completions translation (chat_completions: Request -> Responses request, reply fields; the axum handlers stay in chat.rs). strata-control re-exports codec, json_order, reasoning_budget and sampling under their old paths, and wire.rs re-exports EngineTune, so no caller and no test outside the moved modules changed. 4 new tests cover the chat translation. Architecture gate: layer entry added; dyn-trait:leleka-gateway-domain = 5 appears because the five dyn in the moved code (Box<dyn TokenDecoder>, Box<dyn Iterator> in the budget driver, &dyn Fn, ...) change crate; dyn-trait:strata-control fell 21 -> 16 in the same step, so the total is unchanged (--allow-increase was needed for the new per-crate key only). Test outcomes: 597 ok / 2 ignored before, 615 ok / 2 ignored after (18 new tests); the 13 moved tests keep their ids in the new crate and their outcome.
This commit is contained in:
Generated
+11
@@ -1320,6 +1320,16 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "leleka-gateway-domain"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"leleka-sampler-ref",
|
||||
"leleka-tokenizer",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "leleka-gateway-text"
|
||||
version = "0.1.0"
|
||||
@@ -2793,6 +2803,7 @@ dependencies = [
|
||||
"http-body-util",
|
||||
"jsonschema",
|
||||
"leleka-backend-api",
|
||||
"leleka-gateway-domain",
|
||||
"leleka-gateway-text",
|
||||
"leleka-gguf",
|
||||
"leleka-harmony",
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "control-plane", "desktop-core", "crates/libc-shim", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/leleka-memory", "crates/deploy", "crates/obs", "crates/native-cpu-expert", "crates/native-parity-bench", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy"]
|
||||
default-members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "control-plane", "desktop-core", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/leleka-memory", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "crates/deploy", "crates/obs"]
|
||||
members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "crates/gateway-domain", "control-plane", "desktop-core", "crates/libc-shim", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/cuda-driver", "crates/leleka-runtime", "crates/leleka-memory", "crates/deploy", "crates/obs", "crates/native-cpu-expert", "crates/native-parity-bench", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy"]
|
||||
default-members = ["crates/backend-api", "crates/worker-protocol", "crates/cpu-kernels", "crates/cpu-sys", "crates/cpu-worker", "crates/gguf", "crates/gptoss", "crates/gptoss-igpu", "crates/harmony", "crates/igpu", "crates/kar-codec", "crates/igpu-worker", "crates/shm", "crates/openvino", "crates/npu-service", "crates/gptoss-npu", "crates/npu-worker", "crates/gpu-npu-worker", "crates/tokenizer", "crates/gateway-text", "crates/gateway-domain", "control-plane", "desktop-core", "crates/runtime-client", "crates/model-format", "crates/offline-tools", "crates/quant-core", "crates/context", "crates/leleka-memory", "crates/sampler-ref", "crates/experimental-ref", "crates/serving-policy", "crates/deploy", "crates/obs"]
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
|
||||
@@ -133,6 +133,7 @@
|
||||
"dyn-trait:leleka-cuda-driver": 51,
|
||||
"dyn-trait:leleka-deploy": 17,
|
||||
"dyn-trait:leleka-experimental-ref": 3,
|
||||
"dyn-trait:leleka-gateway-domain": 5,
|
||||
"dyn-trait:leleka-gptoss": 10,
|
||||
"dyn-trait:leleka-gptoss-igpu": 4,
|
||||
"dyn-trait:leleka-gptoss-npu": 4,
|
||||
@@ -141,7 +142,7 @@
|
||||
"dyn-trait:leleka-model-format": 8,
|
||||
"dyn-trait:leleka-runtime": 70,
|
||||
"dyn-trait:leleka-tokenizer": 2,
|
||||
"dyn-trait:strata-control": 21,
|
||||
"dyn-trait:strata-control": 16,
|
||||
"dyn-trait:strata-desktop-core": 2,
|
||||
"env-read:leleka-cpu-kernels": 1,
|
||||
"env-read:leleka-cpu-worker": 2,
|
||||
|
||||
+3
-3
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"_comment": "Policy read by scripts/check-architecture.py (STRA-338 ADR). Layers are ordered low to high; a normal dependency must point to the same or a lower layer. L2 (core) is reserved: it is empty until the engine/gateway domain crates are extracted (steps S19, S21). Every workspace package appears in exactly one layer.",
|
||||
"_comment": "Policy read by scripts/check-architecture.py (STRA-338 ADR). Layers are ordered low to high; a normal dependency must point to the same or a lower layer. L2 (core) holds the extracted domain crates: leleka-gateway-domain (S21); the engine domain crates follow (S19). Every workspace package appears in exactly one layer.",
|
||||
"max_lines": 400,
|
||||
"adapter_layer": "L3",
|
||||
"pure_layers": ["L0", "L1"],
|
||||
"pure_layers": ["L0", "L1", "L2"],
|
||||
"forbidden_in_pure": ["tokio", "axum", "tonic", "tonic-prost", "reqwest", "hyper", "libc", "rustix", "windows-sys", "sysinfo", "wgpu"],
|
||||
"layers": {
|
||||
"L0": ["leleka-backend-api", "leleka-worker-protocol"],
|
||||
@@ -11,7 +11,7 @@
|
||||
"leleka-tokenizer", "leleka-gguf", "leleka-kar-codec", "leleka-experimental-ref", "leleka-cpu-sys", "leleka-cpu-kernels",
|
||||
"leleka-shm", "leleka-openvino", "leleka-memory", "leleka-gateway-text"
|
||||
],
|
||||
"L2": [],
|
||||
"L2": ["leleka-gateway-domain"],
|
||||
"L3": [
|
||||
"leleka-libc-shim", "leleka-model-format", "leleka-cuda-driver", "leleka-native-cpu-expert", "leleka-gptoss", "leleka-igpu",
|
||||
"leleka-gptoss-igpu", "leleka-gptoss-npu", "leleka-npu-service", "leleka-cpu-worker", "leleka-igpu-worker", "leleka-npu-worker",
|
||||
|
||||
@@ -15,6 +15,7 @@ axum = "0.8"
|
||||
futures-core = "0.3"
|
||||
hex = "0.4"
|
||||
leleka-gguf = { path = "../crates/gguf" }
|
||||
leleka-gateway-domain = { path = "../crates/gateway-domain" }
|
||||
leleka-gateway-text = { path = "../crates/gateway-text" }
|
||||
leleka-worker-protocol = { path = "../crates/worker-protocol" }
|
||||
leleka-obs = { path = "../crates/obs" }
|
||||
|
||||
@@ -8,7 +8,6 @@ use axum::{
|
||||
response::{IntoResponse, Response, Sse, sse::Event},
|
||||
};
|
||||
use futures_core::Stream;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
convert::Infallible,
|
||||
@@ -18,91 +17,10 @@ use std::{
|
||||
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);
|
||||
/// 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>),
|
||||
}
|
||||
use leleka_gateway_domain::chat_completions::{Request, call, finish, identity, usage};
|
||||
|
||||
struct Events(mpsc::Receiver<Event>);
|
||||
|
||||
mod invalid;
|
||||
#[allow(unused_imports)]
|
||||
pub use invalid::*;
|
||||
mod impl_request;
|
||||
#[allow(unused_imports)]
|
||||
pub use impl_request::*;
|
||||
mod completion;
|
||||
#[allow(unused_imports)]
|
||||
pub use completion::*;
|
||||
|
||||
@@ -25,12 +25,13 @@ macro_rules! wlog {
|
||||
/// The boxed error the command-line and offline-tool functions return.
|
||||
pub type BoxError = Box<dyn std::error::Error>;
|
||||
|
||||
pub use leleka_gateway_domain::{codec, json_order, reasoning_budget, sampling};
|
||||
|
||||
pub mod adapters;
|
||||
pub mod app;
|
||||
pub mod asset_bundle;
|
||||
pub mod auth;
|
||||
pub mod backend_worker;
|
||||
pub mod codec;
|
||||
pub mod config;
|
||||
pub mod derived_iq3;
|
||||
pub mod derived_mixed;
|
||||
@@ -48,7 +49,6 @@ mod history_store;
|
||||
mod immutable_directory;
|
||||
pub use leleka_quant_core::iq3_s;
|
||||
pub mod hardware_view;
|
||||
pub mod json_order;
|
||||
pub mod kar;
|
||||
pub mod kar_codec;
|
||||
pub mod kar_fixture;
|
||||
@@ -104,8 +104,6 @@ pub mod service_switch;
|
||||
pub mod queue;
|
||||
pub mod request_log;
|
||||
|
||||
pub mod sampling;
|
||||
|
||||
pub mod server_api;
|
||||
|
||||
pub mod stage_trace;
|
||||
@@ -113,5 +111,4 @@ pub mod stage_trace;
|
||||
pub mod settings;
|
||||
|
||||
pub mod mcp;
|
||||
pub mod reasoning_budget;
|
||||
pub mod vision;
|
||||
|
||||
@@ -2,13 +2,7 @@
|
||||
|
||||
use leleka_sampler_ref::RequestSampling;
|
||||
|
||||
/// Per-request engine tuning (`strata_tune` in the Python server): the PCIe share of
|
||||
/// missed experts and the draft-probability floor, both in `0..=1`.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct EngineTune {
|
||||
pub pcie_frac: Option<f64>,
|
||||
pub spec_min_p: Option<f64>,
|
||||
}
|
||||
pub use leleka_gateway_domain::EngineTune;
|
||||
|
||||
/// Reasoning-budget wrap-up (`reasoning_budget_tokens`, issue #123 of the Original): once the model
|
||||
/// has thought for `budget` tokens, at a clean point the worker stops the pass, appends `wrap_up`
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "leleka-gateway-domain"
|
||||
version = "0.1.0"
|
||||
description = "Pure domain of the HTTP/Responses gateway: request sampling, reasoning budget, model-family codec, JSON ordering. No async runtime, no HTTP, no OS."
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
leleka-sampler-ref = { path = "../sampler-ref" }
|
||||
leleka-tokenizer = { path = "../tokenizer" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
# `preserve_order` and `float_roundtrip` as in leleka-gateway-text and strata-control: tool-call arguments and schemas keep
|
||||
# the order the client wrote them (json_order.rs builds the sorted forms explicitly).
|
||||
serde_json = { version = "1", features = ["float_roundtrip", "preserve_order"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Chat Completions requests as Responses requests (STRA-338 S21): the wire types, the translation, and the response fields a
|
||||
//! chat reply takes from the native Responses object. Pure JSON in, JSON out; the HTTP adapter is `strata-control`'s `chat`.
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub 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)]
|
||||
pub struct StreamOptions {
|
||||
include_usage: Option<bool>,
|
||||
include_obfuscation: Option<bool>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub 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)]
|
||||
pub struct Call {
|
||||
id: String,
|
||||
#[serde(rename = "type")]
|
||||
kind: String,
|
||||
function: CallFunction,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CallFunction {
|
||||
name: String,
|
||||
arguments: String,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Tool {
|
||||
#[serde(rename = "type")]
|
||||
kind: String,
|
||||
function: Function,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Function {
|
||||
name: String,
|
||||
description: Option<String>,
|
||||
parameters: Option<Value>,
|
||||
strict: Option<bool>,
|
||||
}
|
||||
|
||||
pub type Invalid = (&'static str, &'static str);
|
||||
/// 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.
|
||||
pub enum Content {
|
||||
Text(String),
|
||||
Parts(Vec<Value>),
|
||||
}
|
||||
|
||||
mod content;
|
||||
mod request;
|
||||
mod response;
|
||||
|
||||
use content::*;
|
||||
|
||||
pub use response::{call, finish, identity, usage};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
+6
-7
@@ -1,21 +1,20 @@
|
||||
//! Moved out of the parent module by STRA-338: fn invalid, impl Content, fn image_part, fn content.
|
||||
//! Message content and picture parts of a chat request.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
pub(super) fn invalid(param: &'static str, message: &'static str) -> Invalid {
|
||||
pub(crate) fn invalid(param: &'static str, message: &'static str) -> Invalid {
|
||||
(param, message)
|
||||
}
|
||||
|
||||
impl Content {
|
||||
pub(super) fn text(self) -> Option<String> {
|
||||
pub(crate) fn text(self) -> Option<String> {
|
||||
match self {
|
||||
Self::Text(text) => Some(text),
|
||||
Self::Parts(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn into_value(self) -> Value {
|
||||
pub(crate) fn into_value(self) -> Value {
|
||||
match self {
|
||||
Self::Text(text) => Value::String(text),
|
||||
Self::Parts(parts) => Value::Array(parts),
|
||||
@@ -25,7 +24,7 @@ impl Content {
|
||||
|
||||
/// 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.
|
||||
pub(super) fn image_part(part: &serde_json::Map<String, Value>) -> Result<Value, Invalid> {
|
||||
pub(crate) fn image_part(part: &serde_json::Map<String, Value>) -> Result<Value, Invalid> {
|
||||
let bad = || {
|
||||
invalid(
|
||||
"messages",
|
||||
@@ -59,7 +58,7 @@ pub(super) fn image_part(part: &serde_json::Map<String, Value>) -> Result<Value,
|
||||
Ok(json!({"type": "input_image", "image_url": url}))
|
||||
}
|
||||
|
||||
pub(super) fn content(value: Option<Value>, role: &str) -> Result<Option<Content>, Invalid> {
|
||||
pub(crate) 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))),
|
||||
+2
-29
@@ -1,10 +1,9 @@
|
||||
//! Moved out of the parent module by STRA-338: impl Request, fn usage, fn call, fn finish, fn identity.
|
||||
//! `Request::into_responses`: the checks of the supported Chat subset and the native request it becomes.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
impl Request {
|
||||
pub(super) fn into_responses(self) -> Result<(Value, bool, bool), Invalid> {
|
||||
pub 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"));
|
||||
}
|
||||
@@ -199,29 +198,3 @@ impl Request {
|
||||
Ok((request, self.stream, include_usage))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) 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"]}})
|
||||
}
|
||||
pub(super) fn call(item: &Value) -> Value {
|
||||
json!({"id":item["call_id"],"type":"function","function":{"name":item["name"],"arguments":item["arguments"]}})
|
||||
}
|
||||
pub(super) 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"
|
||||
}
|
||||
}
|
||||
pub(super) 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"]})
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//! The fields of a chat reply that come from the native Responses object.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub 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"]}})
|
||||
}
|
||||
pub fn call(item: &Value) -> Value {
|
||||
json!({"id":item["call_id"],"type":"function","function":{"name":item["name"],"arguments":item["arguments"]}})
|
||||
}
|
||||
pub 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"
|
||||
}
|
||||
}
|
||||
pub 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"]})
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//! Tests of the Chat Completions to Responses translation (new in STRA-338 S21; the HTTP behaviour is covered by the
|
||||
//! gateway's own tests).
|
||||
|
||||
use super::*;
|
||||
|
||||
fn translate(body: Value) -> Result<(Value, bool, bool), Invalid> {
|
||||
serde_json::from_value::<Request>(body)
|
||||
.expect("a well-formed chat request")
|
||||
.into_responses()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_plain_chat_becomes_a_stateless_responses_request_without_reasoning() {
|
||||
let (request, stream, usage) = translate(json!({
|
||||
"model": "m",
|
||||
"messages": [{"role": "system", "content": "be brief"}, {"role": "user", "content": "hi"}],
|
||||
"max_tokens": 7, "temperature": 0.5
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!((stream, usage), (false, false));
|
||||
assert_eq!(request["store"], false);
|
||||
assert_eq!(request["reasoning"]["effort"], "none");
|
||||
assert_eq!(request["max_output_tokens"], 7);
|
||||
assert_eq!(
|
||||
request["input"][1],
|
||||
json!({"role": "user", "content": "hi"})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tool_calls_and_results_become_function_items() {
|
||||
let (request, ..) = translate(json!({
|
||||
"model": "m",
|
||||
"messages": [
|
||||
{"role": "user", "content": "weather?"},
|
||||
{"role": "assistant", "tool_calls": [{"id": "c1", "type": "function",
|
||||
"function": {"name": "lookup", "arguments": "{}"}}]},
|
||||
{"role": "tool", "tool_call_id": "c1", "content": "3C"}
|
||||
],
|
||||
"tools": [{"type": "function", "function": {"name": "lookup", "description": "d"}}]
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(request["input"][1]["type"], "function_call");
|
||||
assert_eq!(
|
||||
request["input"][2],
|
||||
json!({"type": "function_call_output", "call_id": "c1", "output": "3C"})
|
||||
);
|
||||
assert_eq!(request["tools"][0]["name"], "lookup");
|
||||
assert_eq!(request["tools"][0]["description"], "d");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_features_name_the_parameter() {
|
||||
for (extra, param) in [
|
||||
(json!({"n": 2}), "n"),
|
||||
(json!({"logprobs": true}), "logprobs"),
|
||||
(json!({"stop": ["x"]}), "stop"),
|
||||
(json!({"reasoning_effort": "high"}), "reasoning_effort"),
|
||||
(
|
||||
json!({"stream_options": {"include_usage": true}}),
|
||||
"stream_options",
|
||||
),
|
||||
] {
|
||||
let mut body = json!({"model": "m", "messages": [{"role": "user", "content": "hi"}]});
|
||||
body.as_object_mut()
|
||||
.unwrap()
|
||||
.extend(extra.as_object().unwrap().clone());
|
||||
assert_eq!(translate(body).unwrap_err().0, param);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reply_fields_come_from_the_native_response() {
|
||||
let response = json!({"id": "resp_1", "created_at": 5, "model": "m", "status": "incomplete",
|
||||
"output": [], "usage": {"input_tokens": 3, "output_tokens": 4, "total_tokens": 7}});
|
||||
assert_eq!(finish(&response), "length");
|
||||
assert_eq!(
|
||||
identity(&response, "chat.completion")["id"],
|
||||
"chatcmpl-resp_1"
|
||||
);
|
||||
assert_eq!(usage(&response)["total_tokens"], 7);
|
||||
let calling = json!({"status": "completed", "output": [{"type": "function_call"}]});
|
||||
assert_eq!(finish(&calling), "tool_calls");
|
||||
assert_eq!(
|
||||
call(&json!({"call_id": "c", "name": "n", "arguments": "{}"}))["id"],
|
||||
"c"
|
||||
);
|
||||
}
|
||||
@@ -41,7 +41,7 @@ pub trait TextCodec: Send + Sync {
|
||||
}
|
||||
/// The Qwen tokenizer behind this codec, for what only that family has (control-token marks, pictures, the
|
||||
/// reasoning budget, the runtime backend); `None` for the other families.
|
||||
fn qwen(&self) -> Option<&Arc<crate::tokenizer::Tokenizer>> {
|
||||
fn qwen(&self) -> Option<&Arc<leleka_tokenizer::Tokenizer>> {
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -58,7 +58,7 @@ pub fn decode_all(codec: &dyn TextCodec, ids: &[u32]) -> Result<Vec<u8>, String>
|
||||
}
|
||||
|
||||
/// Qwen3.5 decodes token by token with no state.
|
||||
struct QwenDecoder(Arc<crate::tokenizer::Tokenizer>);
|
||||
struct QwenDecoder(Arc<leleka_tokenizer::Tokenizer>);
|
||||
|
||||
impl TokenDecoder for QwenDecoder {
|
||||
fn push(&mut self, id: u32) -> Result<Vec<u8>, String> {
|
||||
@@ -71,16 +71,16 @@ impl TokenDecoder for QwenDecoder {
|
||||
}
|
||||
|
||||
/// The Qwen tokenizer as a codec; hold it in an `Arc` and call [`qwen_codec`].
|
||||
pub struct QwenCodec(Arc<crate::tokenizer::Tokenizer>);
|
||||
pub struct QwenCodec(Arc<leleka_tokenizer::Tokenizer>);
|
||||
|
||||
pub fn qwen_codec(tokenizer: crate::tokenizer::Tokenizer) -> QwenCodec {
|
||||
pub fn qwen_codec(tokenizer: leleka_tokenizer::Tokenizer) -> QwenCodec {
|
||||
QwenCodec(Arc::new(tokenizer))
|
||||
}
|
||||
|
||||
/// The codec is the tokenizer plus the family's grammar; the Qwen-only code (control-token marks, pictures) reaches the
|
||||
/// tokenizer through it.
|
||||
impl std::ops::Deref for QwenCodec {
|
||||
type Target = crate::tokenizer::Tokenizer;
|
||||
type Target = leleka_tokenizer::Tokenizer;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
@@ -88,7 +88,7 @@ impl std::ops::Deref for QwenCodec {
|
||||
}
|
||||
|
||||
/// The codec over a tokenizer that is shared with other code (the runtime backend counts with the same one).
|
||||
pub fn qwen_codec_shared(tokenizer: Arc<crate::tokenizer::Tokenizer>) -> QwenCodec {
|
||||
pub fn qwen_codec_shared(tokenizer: Arc<leleka_tokenizer::Tokenizer>) -> QwenCodec {
|
||||
QwenCodec(tokenizer)
|
||||
}
|
||||
|
||||
@@ -115,12 +115,12 @@ impl TextCodec for QwenCodec {
|
||||
}
|
||||
|
||||
/// Control-token text inside the messages is marked by the renderer and encoded as ordinary text
|
||||
/// ([`crate::tokenizer::Tokenizer::encode_marked`]).
|
||||
/// ([`leleka_tokenizer::Tokenizer::encode_marked`]).
|
||||
fn encode_prompt(&self, prompt: &str) -> Result<Vec<u32>, String> {
|
||||
self.0.encode_marked(prompt).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn qwen(&self) -> Option<&Arc<crate::tokenizer::Tokenizer>> {
|
||||
fn qwen(&self) -> Option<&Arc<leleka_tokenizer::Tokenizer>> {
|
||||
Some(&self.0)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
//! Pure domain of the HTTP/Responses gateway (`strata-control`), layer L2 of `architecture.json`.
|
||||
//!
|
||||
//! * `sampling`: the sampling extensions a client may send and their validation, `EngineTune`.
|
||||
//! * `reasoning_budget`: the thinking budget driver (generic over the engine and the tokenizer).
|
||||
//! * `codec`: the model family (`TextCodec`, `Family`, `TokenDecoder`) as the Responses code sees it.
|
||||
//! * `chat_completions`: a Chat Completions request as a Responses request, and the chat reply fields.
|
||||
//! * `json_order`: tool results and schemas in the order the client wrote them, or sorted where wanted.
|
||||
//!
|
||||
//! Nothing here starts a thread, opens a socket or reads the environment, so the gateway rules can be tested without
|
||||
//! tokio, axum or an engine. The HTTP layer, the ports and their adapters stay in `strata-control`.
|
||||
|
||||
pub mod chat_completions;
|
||||
pub mod codec;
|
||||
pub mod json_order;
|
||||
pub mod reasoning_budget;
|
||||
pub mod sampling;
|
||||
|
||||
pub use sampling::EngineTune;
|
||||
@@ -12,7 +12,13 @@ use leleka_sampler_ref::RequestSampling;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::wire::EngineTune;
|
||||
/// Per-request engine tuning (`strata_tune` in the Python server): the PCIe share of
|
||||
/// missed experts and the draft-probability floor, both in `0..=1`.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct EngineTune {
|
||||
pub pcie_frac: Option<f64>,
|
||||
pub spec_min_p: Option<f64>,
|
||||
}
|
||||
|
||||
/// Top-level body keys that the Chat and Messages adapters pass through to the native request
|
||||
/// unchanged. Removed before their own `deny_unknown_fields` parse.
|
||||
@@ -68,11 +68,18 @@ def main(argv):
|
||||
moved.append((key, new_same[0]))
|
||||
only_before.remove(key)
|
||||
only_after.remove(new_same[0])
|
||||
# A test that moved to another crate keeps its full module path: pair those when unique too.
|
||||
for key in list(only_before):
|
||||
same = [k for k in only_after if k[1] == key[1]]
|
||||
if len([k for k in only_before if k[1] == key[1]]) == 1 and len(same) == 1:
|
||||
moved.append((key, same[0]))
|
||||
only_before.remove(key)
|
||||
only_after.remove(same[0])
|
||||
for old_key, new_key in moved:
|
||||
if before[old_key] != after[new_key]:
|
||||
changed.append((old_key, before[old_key], after[new_key]))
|
||||
else:
|
||||
print(f"MOVED {old_key[0]} :: {old_key[1]} -> {new_key[1]} ({after[new_key]})")
|
||||
print(f"MOVED {old_key[0]} :: {old_key[1]} -> {new_key[0]} :: {new_key[1]} ({after[new_key]})")
|
||||
for key, was, now in changed:
|
||||
print(f"CHANGED {key[0]} :: {key[1]}: {was} -> {now}")
|
||||
for key in only_before:
|
||||
|
||||
Reference in New Issue
Block a user