feat(prompt): render the pinned chat template with minijinja instead of a hand-written Qwen format
minijinja =2.24.0 (+ minijinja-contrib pycompat for str methods), configured like serve/frontend.py ChatTemplate: trim/lstrip blocks, no autoescape, raise_exception, Python tojson (json.dumps ensure_ascii=False) and str.strip trim. All 10 chat_golden.json cases render byte for byte straight through the template (tool_calls, tool messages, no generation prompt included). Ordered Json keeps object key order. scripts/offline/diff_chat_template.py: 12000 generated conversations vs jinja2 (identical renders, identical raise_exception messages); committed golden + test. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
18d712eed5
commit
250fd3e65d
Generated
+29
@@ -1139,6 +1139,12 @@ version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "memo-map"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5449c8c750f1a07ea702bbd212bd999fceece9b3d1508b17023b3e174583124b"
|
||||
|
||||
[[package]]
|
||||
name = "micromap"
|
||||
version = "0.3.0"
|
||||
@@ -1151,6 +1157,27 @@ version = "0.3.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
|
||||
|
||||
[[package]]
|
||||
name = "minijinja"
|
||||
version = "2.24.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "86886cf6dbf4e614b19c9a1eec9775f021869d7eadde0fc73921a81b90c9b4c9"
|
||||
dependencies = [
|
||||
"indexmap",
|
||||
"memo-map",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "minijinja-contrib"
|
||||
version = "2.24.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bd3e5f077bc2379f0f7d911e7cfdd921114ed99fc884533dca502944cb355b11"
|
||||
dependencies = [
|
||||
"minijinja",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "1.2.4"
|
||||
@@ -2081,6 +2108,8 @@ dependencies = [
|
||||
"leleka-quant-core",
|
||||
"leleka-tokenizer",
|
||||
"libc",
|
||||
"minijinja",
|
||||
"minijinja-contrib",
|
||||
"regex",
|
||||
"regex-syntax",
|
||||
"reqwest",
|
||||
|
||||
@@ -20,6 +20,8 @@ leleka-quant-core = { path = "../crates/quant-core" }
|
||||
http-body = "1"
|
||||
jsonschema = { version = "0.58.4", default-features = false }
|
||||
libc = "0.2"
|
||||
minijinja = { version = "=2.24.0", default-features = false, features = ["builtins", "macros", "multi_template", "adjacent_loop_items", "serde", "preserve_order", "loop_controls"] }
|
||||
minijinja-contrib = { version = "=2.24.0", default-features = false, features = ["pycompat"] }
|
||||
reqwest = { version = "0.13.5", default-features = false, features = ["rustls"] }
|
||||
regex = "1.13.1"
|
||||
regex-syntax = "0.8.11"
|
||||
|
||||
@@ -805,6 +805,36 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
// JSON lines {"messages": [...], "tools": [...]|null, "add_generation_prompt": true, "kwargs": {...}} ->
|
||||
// {"ok": "<prompt>"} or {"error": "<message>"}: the pinned chat template, for scripts/offline/diff_chat_template.py.
|
||||
[model, action] if model == "model" && action == "render-chat" => {
|
||||
use strata_control::prompt::{ChatInput, Json, pinned};
|
||||
for line in std::io::stdin().lines() {
|
||||
let request: Json = serde_json::from_str(&line?)?;
|
||||
let array = |key: &str| match request.get(key) {
|
||||
Some(Json::Array(items)) => Some(items.as_slice()),
|
||||
_ => None,
|
||||
};
|
||||
let kwargs = match request.get("kwargs") {
|
||||
Some(Json::Object(fields)) => fields.iter().map(|(k, v)| (k.as_str(), v.clone())).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let rendered = pinned().render(&ChatInput {
|
||||
messages: array("messages").unwrap_or(&[]),
|
||||
tools: array("tools"),
|
||||
add_generation_prompt: !matches!(request.get("add_generation_prompt"), Some(Json::Bool(false))),
|
||||
kwargs,
|
||||
});
|
||||
println!(
|
||||
"{}",
|
||||
match rendered {
|
||||
Ok(text) => serde_json::json!({"ok": text}),
|
||||
Err(message) => serde_json::json!({"error": message}),
|
||||
}
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
[model, action, path] if model == "model" && action == "detokenize-batch" => {
|
||||
let tokenizer = tokenizer::Tokenizer::from_assets(Path::new(path))?;
|
||||
for line in std::io::stdin().lines() {
|
||||
@@ -822,7 +852,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
print!("{}", include_str!("../third_party/ggml/LICENSE"));
|
||||
Ok(())
|
||||
}
|
||||
_ => Err("usage: strata-next [service-switch --catalog FILE [--from ID] --to ID --state-dir ABSOLUTE_DIR|service-switch reconcile --catalog FILE --state-dir DIR --expected-journal-sha SHA256|api-key init --file ABSOLUTE_PATH|serve [--config FILE]|provision --config FILE [--defer-memory-check]|check-config [--config FILE]|wait-ready --url LOOPBACK_ORIGIN --model ID [--key-file FILE] [--timeout-s N]|service-control status|start|stop|restart|enable|disable|start-ready|restart-ready|drain-stop|resume --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--ready-url LOOPBACK_ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|service-unit --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE]|service-install --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--enable] [--start|--start-ready --ready-url ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|doctor|engine-info|engine-help|--ggml-license|model prepare-native-pack MANIFEST --source-dir DIR --output DIR [--compat-bf16] [--experts-bin] [--base BASE_PACK_DIR]|model smoke-fixture --output FILE.kar|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model export-tensor-f32 FILE.gguf TENSOR --output FILE.f32|model inspect FILE.gguf|model inspect-metadata FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model inspect-kar FILE.kar|model plan-kar-memory FILE.kar --level N --budget-mib M|model plan-kar-overlay-memory --base BASE.kar --overlay OVERLAY.kar --base-level N --overlay-level N --budget-mib M|model resolve-kar-overlay --base FILE.kar --overlay FILE.kar|model checksum-kar-preview FILE.kar TENSOR LEVEL|model checksum-kar-row FILE.kar TENSOR LEVEL --row ROW_ID|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N --ple-part-elements E|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model pre-tokenize-batch|model tokenize-batch TOKENIZER_DIR [--special]|model detokenize-batch TOKENIZER_DIR|model detokenize TOKENIZER_DIR IDS|tools embd-bf16-pack --model DIR --out FILE.gguf|tools ple-fp8-pack --model DIR --out FILE.gguf|tools draft-vocab --gguf FIRST.gguf [--base IDS.bin] [--add han,kana,hangul,cjk_punct,cjk,cyrillic] [--out IDS.bin] [--stats]|tools make-profile [TRACE ...] (--base PROFILE.bin | --no-base) --out PROFILE.bin [--n-expert N]|tools mtp-rt --gguf mtp-q2_0.gguf --out DIR [--n-expert N]|tools mtp-fetch inventory|fetch|verify --out DIR [--only SUBSTR] [--repo URL] [--sha256-file FILE]]".into()),
|
||||
_ => Err("usage: strata-next [service-switch --catalog FILE [--from ID] --to ID --state-dir ABSOLUTE_DIR|service-switch reconcile --catalog FILE --state-dir DIR --expected-journal-sha SHA256|api-key init --file ABSOLUTE_PATH|serve [--config FILE]|provision --config FILE [--defer-memory-check]|check-config [--config FILE]|wait-ready --url LOOPBACK_ORIGIN --model ID [--key-file FILE] [--timeout-s N]|service-control status|start|stop|restart|enable|disable|start-ready|restart-ready|drain-stop|resume --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--ready-url LOOPBACK_ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|service-unit --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE]|service-install --config ABSOLUTE_FILE --working-dir ABSOLUTE_DIR [--env-file ABSOLUTE_FILE] [--unit strata-next[-NAME].service] [--enable] [--start|--start-ready --ready-url ORIGIN --ready-model ID [--ready-key-file FILE] [--ready-timeout-s N]]|doctor|engine-info|engine-help|--ggml-license|model prepare-native-pack MANIFEST --source-dir DIR --output DIR [--compat-bf16] [--experts-bin] [--base BASE_PACK_DIR]|model smoke-fixture --output FILE.kar|model fetch MANIFEST --output DIR|model verify MANIFEST --output DIR|model ensure-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model ensure-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model export-tensor-f32 FILE.gguf TENSOR --output FILE.f32|model inspect FILE.gguf|model inspect-metadata FILE.gguf|model index FILE.gguf [--hash]|model derive-iq3-identity FILE.gguf|model derive-mixed-identity FILE.gguf|model derive-sharded-identity MANIFEST --source-dir DIR|model prepare-f32-preview FILE.gguf --output FILE.kar --levels N|model prepare-iq3-preview FILE.gguf --output FILE.kar --levels N|model prepare-mixed-preview FILE.gguf --output FILE.kar --levels N|model prepare-sharded-preview MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N|model prepare-sharded-streamed MANIFEST --source-dir DIR --output FILE.kar --levels N --ple-part-elements E|model inspect-kar FILE.kar|model plan-kar-memory FILE.kar --level N --budget-mib M|model plan-kar-overlay-memory --base BASE.kar --overlay OVERLAY.kar --base-level N --overlay-level N --budget-mib M|model resolve-kar-overlay --base FILE.kar --overlay FILE.kar|model checksum-kar-preview FILE.kar TENSOR LEVEL|model checksum-kar-row FILE.kar TENSOR LEVEL --row ROW_ID|model verify-kar FILE.kar [--manifest SPEC --source-dir DIR]|model verify-iq3-preview FILE.kar --source FILE.gguf|model verify-mixed-preview FILE.kar --source FILE.gguf|model verify-sharded-preview FILE.kar --manifest SPEC --source-dir DIR|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N|model verify-sharded-streamed FILE.kar --manifest SPEC --source-dir DIR --levels N --ple-part-elements E|model extract-tokenizer FILE.gguf --output DIR|model tokenize TOKENIZER_DIR TEXT [--special]|model tokenize TOKENIZER_DIR --stdin [--special]|model pre-tokenize-batch|model tokenize-batch TOKENIZER_DIR [--special]|model detokenize-batch TOKENIZER_DIR|model render-chat|model detokenize TOKENIZER_DIR IDS|tools embd-bf16-pack --model DIR --out FILE.gguf|tools ple-fp8-pack --model DIR --out FILE.gguf|tools draft-vocab --gguf FIRST.gguf [--base IDS.bin] [--add han,kana,hangul,cjk_punct,cjk,cyrillic] [--out IDS.bin] [--stats]|tools make-profile [TRACE ...] (--base PROFILE.bin | --no-base) --out PROFILE.bin [--n-expert N]|tools mtp-rt --gguf mtp-q2_0.gguf --out DIR [--n-expert N]|tools mtp-fetch inventory|fetch|verify --out DIR [--only SUBSTR] [--repo URL] [--sha256-file FILE]]".into()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+744
-174
@@ -1,8 +1,467 @@
|
||||
//! Supported text subset of the pinned Strata Qwen chat template.
|
||||
//! The no-tool path and a representative tool continuation are byte-for-byte
|
||||
//! checked against upstream golden cases. Tool definitions are adapted from
|
||||
//! Responses function objects.
|
||||
use serde_json::Value;
|
||||
//! Chat prompt rendering: the model's real Jinja chat template, executed natively.
|
||||
//!
|
||||
//! The pinned Strata template (`engine/strata/serve/chat_template.jinja`, the Qwen3.8-Flash-Next template with
|
||||
//! Unsloth's developer-role and tool fixes) is rendered with `minijinja`, configured like the Python server's
|
||||
//! `ChatTemplate` (`serve/frontend.py`): `trim_blocks` and `lstrip_blocks`, no autoescape, Python-style string
|
||||
//! methods, a `raise_exception` global, and Python-compatible `tojson` and `trim` filters. All ten cases of
|
||||
//! `serve/chat_golden.json` render byte for byte; `scripts/offline/diff_chat_template.py` compares the two renderers
|
||||
//! over generated conversations.
|
||||
//!
|
||||
//! * [`Renderer`] renders any template source with arbitrary JSON messages, tools and keyword arguments
|
||||
//! ([`ChatInput`]); [`pinned`] is the compiled default.
|
||||
//! * [`render`] / [`render_with_tools`] are the typed entry points the Responses path uses.
|
||||
//!
|
||||
//! Object key order matters to the model: `tojson` prints keys in the order they were given. [`Json`] keeps that
|
||||
//! order when it is deserialized directly from request text. Values that already went through `serde_json::Value`
|
||||
//! have lost it (the map is sorted), which is what [`Json::from_value`] and the tool schema heuristic in
|
||||
//! [`schema_order`] work around for the Responses path.
|
||||
use std::{collections::BTreeMap, fmt, sync::OnceLock};
|
||||
|
||||
use minijinja::{
|
||||
Environment, Error, ErrorKind, State, Value,
|
||||
value::{Kwargs, ValueKind},
|
||||
};
|
||||
use serde::{
|
||||
Deserialize, Serialize, Serializer,
|
||||
de::{MapAccess, SeqAccess, Visitor},
|
||||
ser::{SerializeMap, SerializeSeq},
|
||||
};
|
||||
use serde_json::Value as Plain;
|
||||
|
||||
/// The pinned chat template, embedded at build time.
|
||||
pub const PINNED_TEMPLATE: &str = include_str!("../../engine/strata/serve/chat_template.jinja");
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
// ordered JSON
|
||||
|
||||
/// JSON that remembers object key order (`serde_json::Value` sorts keys unless its `preserve_order` feature is on,
|
||||
/// which would change every response's key order in this binary).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Json {
|
||||
Null,
|
||||
Bool(bool),
|
||||
Number(serde_json::Number),
|
||||
String(String),
|
||||
Array(Vec<Json>),
|
||||
Object(Vec<(String, Json)>),
|
||||
}
|
||||
|
||||
impl Json {
|
||||
pub fn object<const N: usize>(fields: [(&str, Json); N]) -> Self {
|
||||
Self::Object(fields.into_iter().map(|(k, v)| (k.to_owned(), v)).collect())
|
||||
}
|
||||
|
||||
pub fn str(value: &str) -> Self {
|
||||
Self::String(value.to_owned())
|
||||
}
|
||||
|
||||
pub fn get(&self, key: &str) -> Option<&Json> {
|
||||
match self {
|
||||
Self::Object(fields) => fields.iter().find(|(k, _)| k == key).map(|(_, v)| v),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// From a `serde_json::Value`, whose maps are sorted: keys come out sorted.
|
||||
pub fn from_value(value: &Plain) -> Self {
|
||||
match value {
|
||||
Plain::Null => Self::Null,
|
||||
Plain::Bool(b) => Self::Bool(*b),
|
||||
Plain::Number(n) => Self::Number(n.clone()),
|
||||
Plain::String(s) => Self::String(s.clone()),
|
||||
Plain::Array(items) => Self::Array(items.iter().map(Self::from_value).collect()),
|
||||
Plain::Object(fields) => Self::Object(
|
||||
fields
|
||||
.iter()
|
||||
.map(|(k, v)| (k.clone(), Self::from_value(v)))
|
||||
.collect(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Like [`Json::from_value`], but every object that has a `"type"` key is ordered the way JSON Schema is
|
||||
/// conventionally written (see [`schema_order`]). Tool parameter schemas reach the server through
|
||||
/// `serde_json::Value`, so the client's own key order is gone; this is the order that matches it most often.
|
||||
pub fn from_schema_value(value: &Plain) -> Self {
|
||||
match value {
|
||||
Plain::Array(items) => Self::Array(items.iter().map(Self::from_schema_value).collect()),
|
||||
Plain::Object(fields) => {
|
||||
let mut keys: Vec<&String> = fields.keys().collect();
|
||||
if fields.contains_key("type") {
|
||||
keys.sort_by_key(|key| (schema_order(key), key.as_str()));
|
||||
}
|
||||
Self::Object(
|
||||
keys.into_iter()
|
||||
.map(|k| (k.clone(), Self::from_schema_value(&fields[k])))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
other => Self::from_value(other),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Position of a JSON Schema keyword in the conventional writing order.
|
||||
pub fn schema_order(key: &str) -> u8 {
|
||||
match key {
|
||||
"type" => 0,
|
||||
"properties" => 1,
|
||||
"required" => 2,
|
||||
"items" => 3,
|
||||
"enum" => 4,
|
||||
"description" => 5,
|
||||
"additionalProperties" => 6,
|
||||
_ => 7,
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for Json {
|
||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
match self {
|
||||
Self::Null => serializer.serialize_unit(),
|
||||
Self::Bool(b) => serializer.serialize_bool(*b),
|
||||
Self::Number(n) => n.serialize(serializer),
|
||||
Self::String(s) => serializer.serialize_str(s),
|
||||
Self::Array(items) => {
|
||||
let mut seq = serializer.serialize_seq(Some(items.len()))?;
|
||||
for item in items {
|
||||
seq.serialize_element(item)?;
|
||||
}
|
||||
seq.end()
|
||||
}
|
||||
Self::Object(fields) => {
|
||||
let mut map = serializer.serialize_map(Some(fields.len()))?;
|
||||
for (k, v) in fields {
|
||||
map.serialize_entry(k, v)?;
|
||||
}
|
||||
map.end()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Json {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
struct V;
|
||||
impl<'de> Visitor<'de> for V {
|
||||
type Value = Json;
|
||||
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("any JSON value")
|
||||
}
|
||||
|
||||
fn visit_unit<E>(self) -> Result<Json, E> {
|
||||
Ok(Json::Null)
|
||||
}
|
||||
|
||||
fn visit_none<E>(self) -> Result<Json, E> {
|
||||
Ok(Json::Null)
|
||||
}
|
||||
|
||||
fn visit_some<D: serde::Deserializer<'de>>(self, d: D) -> Result<Json, D::Error> {
|
||||
Json::deserialize(d)
|
||||
}
|
||||
|
||||
fn visit_bool<E>(self, v: bool) -> Result<Json, E> {
|
||||
Ok(Json::Bool(v))
|
||||
}
|
||||
|
||||
fn visit_i64<E>(self, v: i64) -> Result<Json, E> {
|
||||
Ok(Json::Number(v.into()))
|
||||
}
|
||||
|
||||
fn visit_u64<E>(self, v: u64) -> Result<Json, E> {
|
||||
Ok(Json::Number(v.into()))
|
||||
}
|
||||
|
||||
fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<Json, E> {
|
||||
serde_json::Number::from_f64(v)
|
||||
.map(Json::Number)
|
||||
.ok_or_else(|| E::custom("non-finite number"))
|
||||
}
|
||||
|
||||
fn visit_str<E>(self, v: &str) -> Result<Json, E> {
|
||||
Ok(Json::String(v.to_owned()))
|
||||
}
|
||||
|
||||
fn visit_string<E>(self, v: String) -> Result<Json, E> {
|
||||
Ok(Json::String(v))
|
||||
}
|
||||
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Json, A::Error> {
|
||||
let mut items = Vec::new();
|
||||
while let Some(item) = seq.next_element()? {
|
||||
items.push(item);
|
||||
}
|
||||
Ok(Json::Array(items))
|
||||
}
|
||||
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Json, A::Error> {
|
||||
let mut fields: Vec<(String, Json)> = Vec::new();
|
||||
while let Some((key, value)) = map.next_entry::<String, Json>()? {
|
||||
// a repeated key keeps its first position and takes the last value, as a Python dict does
|
||||
match fields.iter_mut().find(|(k, _)| *k == key) {
|
||||
Some(slot) => slot.1 = value,
|
||||
None => fields.push((key, value)),
|
||||
}
|
||||
}
|
||||
Ok(Json::Object(fields))
|
||||
}
|
||||
}
|
||||
deserializer.deserialize_any(V)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
// Python-compatible filters
|
||||
|
||||
/// `str.isspace()` for one character: Unicode White_Space plus the four separator controls U+001C-U+001F.
|
||||
fn py_space(c: char) -> bool {
|
||||
c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c)
|
||||
}
|
||||
|
||||
/// Jinja's `trim` filter is `str.strip(chars)`.
|
||||
fn trim(value: Value, chars: Option<String>) -> String {
|
||||
let text = if value.is_undefined() {
|
||||
String::new()
|
||||
} else {
|
||||
value.to_string()
|
||||
};
|
||||
match chars {
|
||||
None => text.trim_matches(py_space).to_owned(),
|
||||
Some(set) => text.trim_matches(|c| set.contains(c)).to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Python's `repr(float)` as `json.dumps` writes it: shortest round-trip digits, exponent form outside 1e-4..1e16.
|
||||
fn python_float(value: f64) -> String {
|
||||
if value == 0.0 {
|
||||
return if value.is_sign_negative() {
|
||||
"-0.0"
|
||||
} else {
|
||||
"0.0"
|
||||
}
|
||||
.to_owned();
|
||||
}
|
||||
let scientific = format!("{value:e}"); // shortest digits: "-1.2345e-5"
|
||||
let (mantissa, exponent) = scientific.split_once('e').expect("exponent");
|
||||
let exponent: i32 = exponent.parse().expect("exponent digits");
|
||||
let (sign, digits) = match mantissa.strip_prefix('-') {
|
||||
Some(rest) => ("-", rest),
|
||||
None => ("", mantissa),
|
||||
};
|
||||
let digits: String = digits.chars().filter(|c| *c != '.').collect();
|
||||
if (-4..16).contains(&exponent) {
|
||||
if exponent >= 0 {
|
||||
let point = exponent as usize + 1;
|
||||
if digits.len() <= point {
|
||||
format!("{sign}{digits}{}.0", "0".repeat(point - digits.len()))
|
||||
} else {
|
||||
format!("{sign}{}.{}", &digits[..point], &digits[point..])
|
||||
}
|
||||
} else {
|
||||
format!("{sign}0.{}{digits}", "0".repeat((-exponent - 1) as usize))
|
||||
}
|
||||
} else {
|
||||
let mut out = format!("{sign}{}", &digits[..1]);
|
||||
if digits.len() > 1 {
|
||||
out.push('.');
|
||||
out.push_str(&digits[1..]);
|
||||
}
|
||||
format!(
|
||||
"{out}e{}{:02}",
|
||||
if exponent < 0 { '-' } else { '+' },
|
||||
exponent.abs()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn json_string(text: &str, ensure_ascii: bool, out: &mut String) {
|
||||
out.push('"');
|
||||
for c in text.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
'\u{8}' => out.push_str("\\b"),
|
||||
'\u{c}' => out.push_str("\\f"),
|
||||
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
|
||||
c if ensure_ascii && !c.is_ascii() => {
|
||||
let mut units = [0u16; 2];
|
||||
for unit in c.encode_utf16(&mut units) {
|
||||
out.push_str(&format!("\\u{unit:04x}"));
|
||||
}
|
||||
}
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
}
|
||||
|
||||
fn write_json(
|
||||
value: &Value,
|
||||
sort_keys: bool,
|
||||
ensure_ascii: bool,
|
||||
out: &mut String,
|
||||
) -> Result<(), Error> {
|
||||
match value.kind() {
|
||||
ValueKind::None => out.push_str("null"),
|
||||
ValueKind::Bool => out.push_str(if value.is_true() { "true" } else { "false" }),
|
||||
ValueKind::Number => {
|
||||
if value.is_integer() {
|
||||
out.push_str(&value.to_string());
|
||||
} else {
|
||||
let float = f64::try_from(value.clone())?;
|
||||
if !float.is_finite() {
|
||||
out.push_str(if float.is_nan() {
|
||||
"NaN"
|
||||
} else if float > 0.0 {
|
||||
"Infinity"
|
||||
} else {
|
||||
"-Infinity"
|
||||
});
|
||||
} else {
|
||||
out.push_str(&python_float(float));
|
||||
}
|
||||
}
|
||||
}
|
||||
ValueKind::String => json_string(value.as_str().unwrap_or_default(), ensure_ascii, out),
|
||||
ValueKind::Seq | ValueKind::Iterable => {
|
||||
out.push('[');
|
||||
for (at, item) in value.try_iter()?.enumerate() {
|
||||
if at > 0 {
|
||||
out.push_str(", ");
|
||||
}
|
||||
write_json(&item, sort_keys, ensure_ascii, out)?;
|
||||
}
|
||||
out.push(']');
|
||||
}
|
||||
ValueKind::Map => {
|
||||
let mut keys: Vec<Value> = value.try_iter()?.collect();
|
||||
if sort_keys {
|
||||
keys.sort_by_key(|k| k.to_string());
|
||||
}
|
||||
out.push('{');
|
||||
for (at, key) in keys.iter().enumerate() {
|
||||
if at > 0 {
|
||||
out.push_str(", ");
|
||||
}
|
||||
let Some(name) = key.as_str() else {
|
||||
return Err(Error::new(
|
||||
ErrorKind::InvalidOperation,
|
||||
"tojson keys must be strings",
|
||||
));
|
||||
};
|
||||
json_string(name, ensure_ascii, out);
|
||||
out.push_str(": ");
|
||||
write_json(&value.get_item(key)?, sort_keys, ensure_ascii, out)?;
|
||||
}
|
||||
out.push('}');
|
||||
}
|
||||
other => {
|
||||
return Err(Error::new(
|
||||
ErrorKind::InvalidOperation,
|
||||
format!("Object of type {other:?} is not JSON serializable"),
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The server's `tojson`: `json.dumps(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False)`.
|
||||
fn tojson(_state: &State, value: Value, kwargs: Kwargs) -> Result<String, Error> {
|
||||
let ensure_ascii = kwargs.get::<Option<bool>>("ensure_ascii")?.unwrap_or(false);
|
||||
let sort_keys = kwargs.get::<Option<bool>>("sort_keys")?.unwrap_or(false);
|
||||
let indent: Option<Value> = kwargs.get("indent")?;
|
||||
let separators: Option<Value> = kwargs.get("separators")?;
|
||||
kwargs.assert_all_used()?;
|
||||
if indent.is_some_and(|v| !v.is_none()) || separators.is_some_and(|v| !v.is_none()) {
|
||||
return Err(Error::new(
|
||||
ErrorKind::InvalidOperation,
|
||||
"tojson with indent or separators is not supported by the native renderer",
|
||||
));
|
||||
}
|
||||
let mut out = String::new();
|
||||
write_json(&value, sort_keys, ensure_ascii, &mut out)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
// the renderer
|
||||
|
||||
/// One rendering: what `ChatTemplate.render(messages, tools, add_generation_prompt, **kwargs)` takes.
|
||||
#[derive(Debug)]
|
||||
pub struct ChatInput<'a> {
|
||||
pub messages: &'a [Json],
|
||||
pub tools: Option<&'a [Json]>,
|
||||
pub add_generation_prompt: bool,
|
||||
/// Extra template variables (`enable_thinking`, `reasoning_effort`, `preserve_thinking`, ...).
|
||||
pub kwargs: Vec<(&'a str, Json)>,
|
||||
}
|
||||
|
||||
pub struct Renderer {
|
||||
env: Environment<'static>,
|
||||
}
|
||||
|
||||
impl Renderer {
|
||||
/// A template configured like `ChatTemplate`: `trim_blocks`, `lstrip_blocks`, no autoescape, Python string
|
||||
/// methods, `raise_exception`, `tojson`, `trim`.
|
||||
pub fn new(source: &str) -> Result<Self, String> {
|
||||
let mut env = Environment::new();
|
||||
env.set_trim_blocks(true);
|
||||
env.set_lstrip_blocks(true);
|
||||
env.set_keep_trailing_newline(false);
|
||||
env.set_auto_escape_callback(|_| minijinja::AutoEscape::None);
|
||||
env.set_unknown_method_callback(minijinja_contrib::pycompat::unknown_method_callback);
|
||||
env.add_filter("tojson", tojson);
|
||||
env.add_filter("trim", trim);
|
||||
env.add_function(
|
||||
"raise_exception",
|
||||
|message: String| -> Result<String, Error> {
|
||||
Err(Error::new(ErrorKind::InvalidOperation, message))
|
||||
},
|
||||
);
|
||||
env.add_template_owned("chat", source.to_owned())
|
||||
.map_err(|e| format!("chat template does not compile: {e:#}"))?;
|
||||
Ok(Self { env })
|
||||
}
|
||||
|
||||
pub fn render(&self, input: &ChatInput<'_>) -> Result<String, String> {
|
||||
let mut context: BTreeMap<&str, Value> = BTreeMap::new();
|
||||
context.insert("messages", Value::from_serialize(input.messages));
|
||||
context.insert(
|
||||
"tools",
|
||||
input.tools.map_or(Value::from(()), Value::from_serialize),
|
||||
);
|
||||
context.insert(
|
||||
"add_generation_prompt",
|
||||
Value::from(input.add_generation_prompt),
|
||||
);
|
||||
for (name, value) in &input.kwargs {
|
||||
context.insert(name, Value::from_serialize(value));
|
||||
}
|
||||
self.env
|
||||
.get_template("chat")
|
||||
.and_then(|template| template.render(&context))
|
||||
.map_err(|error| {
|
||||
error
|
||||
.detail()
|
||||
.map_or_else(|| error.to_string(), str::to_owned)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The compiled pinned template.
|
||||
pub fn pinned() -> &'static Renderer {
|
||||
static PINNED: OnceLock<Renderer> = OnceLock::new();
|
||||
PINNED
|
||||
.get_or_init(|| Renderer::new(PINNED_TEMPLATE).expect("the pinned chat template compiles"))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------------
|
||||
// typed entry points
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Role {
|
||||
@@ -12,6 +471,17 @@ pub enum Role {
|
||||
Assistant,
|
||||
}
|
||||
|
||||
impl Role {
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::System => "system",
|
||||
Self::Developer => "developer",
|
||||
Self::User => "user",
|
||||
Self::Assistant => "assistant",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Message<'a> {
|
||||
pub role: Role,
|
||||
@@ -29,20 +499,53 @@ pub enum Effort {
|
||||
XHigh,
|
||||
}
|
||||
|
||||
const XHIGH: &str = "Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.";
|
||||
const LOW: &str = "Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.";
|
||||
impl Effort {
|
||||
/// `serve/frontend.py::effort_kwargs`: the template's `enable_thinking` / `reasoning_effort`.
|
||||
pub fn kwargs(self) -> Vec<(&'static str, Json)> {
|
||||
match self {
|
||||
Self::None => vec![("enable_thinking", Json::Bool(false))],
|
||||
Self::Low => vec![("reasoning_effort", Json::str("low"))],
|
||||
Self::Medium => vec![("reasoning_effort", Json::str("medium"))],
|
||||
Self::High => vec![("reasoning_effort", Json::str("high"))],
|
||||
Self::XHigh => vec![("reasoning_effort", Json::str("xhigh"))],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn render(messages: &[Message<'_>], effort: Effort) -> Result<String, &'static str> {
|
||||
pub fn render(messages: &[Message<'_>], effort: Effort) -> Result<String, String> {
|
||||
render_with_tools(messages, effort, &[])
|
||||
}
|
||||
|
||||
/// Adapt a flat Responses function object to the `{"type": "function", "function": {...}}` form the template
|
||||
/// prints. Field order is the template-conventional one; the parameter schema keeps [`Json::from_schema_value`] order.
|
||||
pub fn chat_tool(tool: &Plain) -> Result<Json, String> {
|
||||
let name = tool
|
||||
.get("name")
|
||||
.and_then(Plain::as_str)
|
||||
.ok_or("tool needs a name")?;
|
||||
let mut function = vec![("name".to_owned(), Json::str(name))];
|
||||
if let Some(description) = tool.get("description").and_then(Plain::as_str) {
|
||||
function.push(("description".to_owned(), Json::str(description)));
|
||||
}
|
||||
if let Some(parameters) = tool.get("parameters") {
|
||||
function.push(("parameters".to_owned(), Json::from_schema_value(parameters)));
|
||||
}
|
||||
if let Some(strict) = tool.get("strict") {
|
||||
function.push(("strict".to_owned(), Json::from_schema_value(strict)));
|
||||
}
|
||||
Ok(Json::object([
|
||||
("type", Json::str("function")),
|
||||
("function", Json::Object(function)),
|
||||
]))
|
||||
}
|
||||
|
||||
pub fn render_with_tools(
|
||||
messages: &[Message<'_>],
|
||||
effort: Effort,
|
||||
tools: &[Value],
|
||||
) -> Result<String, &'static str> {
|
||||
tools: &[Plain],
|
||||
) -> Result<String, String> {
|
||||
if messages.is_empty() {
|
||||
return Err("prompt needs a message");
|
||||
return Err("prompt needs a message".into());
|
||||
}
|
||||
let first_non_system = messages
|
||||
.iter()
|
||||
@@ -53,141 +556,90 @@ pub fn render_with_tools(
|
||||
.iter()
|
||||
.any(|message| matches!(message.role, Role::System | Role::Developer))
|
||||
{
|
||||
return Err("system and developer messages must be at the beginning");
|
||||
return Err("system and developer messages must be at the beginning".into());
|
||||
}
|
||||
if messages
|
||||
.last()
|
||||
.is_none_or(|message| message.role != Role::User)
|
||||
{
|
||||
return Err("generation needs a final user message");
|
||||
return Err("generation needs a final user message".into());
|
||||
}
|
||||
|
||||
let system = messages[..first_non_system]
|
||||
let chat: Vec<Json> = messages
|
||||
.iter()
|
||||
.map(|message| message.content.trim())
|
||||
.filter(|content| !content.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
let instruction = match effort {
|
||||
Effort::None | Effort::Medium => "",
|
||||
Effort::Low => LOW,
|
||||
Effort::High | Effort::XHigh => XHIGH,
|
||||
};
|
||||
let mut prompt = String::new();
|
||||
if !instruction.is_empty() || !system.is_empty() || !tools.is_empty() {
|
||||
prompt.push_str("<|im_start|>system\n");
|
||||
prompt.push_str(instruction);
|
||||
if !tools.is_empty() {
|
||||
if !instruction.is_empty() {
|
||||
prompt.push_str("\n\n");
|
||||
.map(|message| {
|
||||
let mut fields = vec![
|
||||
("role".to_owned(), Json::str(message.role.name())),
|
||||
("content".to_owned(), Json::str(message.content)),
|
||||
];
|
||||
if let Some(reasoning) = message.reasoning {
|
||||
fields.push(("reasoning_content".to_owned(), Json::str(reasoning)));
|
||||
}
|
||||
prompt.push_str("# Tools\n\nYou have access to the following functions:\n\n<tools>");
|
||||
for tool in tools {
|
||||
let name = tool
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or("tool needs a name")?;
|
||||
prompt.push('\n');
|
||||
prompt.push_str("{\"type\": \"function\", \"function\": {\"name\": ");
|
||||
prompt.push_str(&serde_json::to_string(name).expect("string JSON"));
|
||||
if let Some(description) = tool.get("description").and_then(Value::as_str) {
|
||||
prompt.push_str(", \"description\": ");
|
||||
prompt.push_str(&serde_json::to_string(description).expect("string JSON"));
|
||||
}
|
||||
if let Some(parameters) = tool.get("parameters") {
|
||||
prompt.push_str(", \"parameters\": ");
|
||||
write_template_json(parameters, &mut prompt);
|
||||
}
|
||||
if let Some(strict) = tool.get("strict") {
|
||||
prompt.push_str(", \"strict\": ");
|
||||
write_template_json(strict, &mut prompt);
|
||||
}
|
||||
prompt.push_str("}}");
|
||||
}
|
||||
prompt.push_str("\n</tools>\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>");
|
||||
}
|
||||
if !system.is_empty() && (!instruction.is_empty() || !tools.is_empty()) {
|
||||
prompt.push_str("\n\n");
|
||||
}
|
||||
prompt.push_str(&system);
|
||||
prompt.push_str("<|im_end|>\n");
|
||||
}
|
||||
for message in &messages[first_non_system..] {
|
||||
match message.role {
|
||||
Role::User => {
|
||||
prompt.push_str("<|im_start|>user\n");
|
||||
prompt.push_str(message.content.trim());
|
||||
prompt.push_str("<|im_end|>\n");
|
||||
}
|
||||
Role::Assistant => {
|
||||
prompt.push_str("<|im_start|>assistant\n<think>\n");
|
||||
prompt.push_str(message.reasoning.unwrap_or("").trim());
|
||||
prompt.push_str("\n</think>\n\n");
|
||||
prompt.push_str(message.content.trim());
|
||||
prompt.push_str("<|im_end|>\n");
|
||||
}
|
||||
Role::System | Role::Developer => unreachable!(),
|
||||
}
|
||||
}
|
||||
prompt.push_str("<|im_start|>assistant\n<think>\n");
|
||||
if effort == Effort::None {
|
||||
prompt.push_str("\n</think>\n\n");
|
||||
}
|
||||
Ok(prompt)
|
||||
}
|
||||
|
||||
fn write_template_json(value: &Value, output: &mut String) {
|
||||
match value {
|
||||
Value::Object(fields) => {
|
||||
let mut keys = fields.keys().collect::<Vec<_>>();
|
||||
if fields.contains_key("type") {
|
||||
let priority = |key: &str| match key {
|
||||
"type" => 0,
|
||||
"properties" => 1,
|
||||
"required" => 2,
|
||||
"items" => 3,
|
||||
"enum" => 4,
|
||||
"description" => 5,
|
||||
"additionalProperties" => 6,
|
||||
_ => 7,
|
||||
};
|
||||
keys.sort_by_key(|key| (priority(key), key.as_str()));
|
||||
}
|
||||
output.push('{');
|
||||
for (index, key) in keys.into_iter().enumerate() {
|
||||
if index > 0 {
|
||||
output.push_str(", ");
|
||||
}
|
||||
output.push_str(&serde_json::to_string(key).expect("object key JSON"));
|
||||
output.push_str(": ");
|
||||
write_template_json(&fields[key], output);
|
||||
}
|
||||
output.push('}');
|
||||
}
|
||||
Value::Array(items) => {
|
||||
output.push('[');
|
||||
for (index, item) in items.iter().enumerate() {
|
||||
if index > 0 {
|
||||
output.push_str(", ");
|
||||
}
|
||||
write_template_json(item, output);
|
||||
}
|
||||
output.push(']');
|
||||
}
|
||||
_ => output.push_str(&value.to_string()),
|
||||
}
|
||||
Json::Object(fields)
|
||||
})
|
||||
.collect();
|
||||
let tools = tools.iter().map(chat_tool).collect::<Result<Vec<_>, _>>()?;
|
||||
pinned().render(&ChatInput {
|
||||
messages: &chat,
|
||||
tools: (!tools.is_empty()).then_some(&tools),
|
||||
add_generation_prompt: true,
|
||||
kwargs: effort.kwargs(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::json;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Case {
|
||||
name: String,
|
||||
messages: Vec<Json>,
|
||||
#[serde(default)]
|
||||
tools: Option<Vec<Json>>,
|
||||
#[serde(default)]
|
||||
add_generation_prompt: Option<bool>,
|
||||
#[serde(default)]
|
||||
enable_thinking: Option<bool>,
|
||||
rendered: String,
|
||||
hf: String,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
fn golden() -> Vec<Case> {
|
||||
serde_json::from_str(include_str!("../../engine/strata/serve/chat_golden.json")).unwrap()
|
||||
}
|
||||
|
||||
/// All ten cases of `serve/chat_golden.json`, straight through the Jinja template: system merging, tool
|
||||
/// definitions, assistant `tool_calls` with mapping arguments, `tool` messages, thinking on and off, and no
|
||||
/// generation prompt.
|
||||
#[test]
|
||||
fn all_ten_golden_cases_render_byte_for_byte() {
|
||||
let cases = golden();
|
||||
assert_eq!(cases.len(), 10);
|
||||
for case in cases {
|
||||
assert!(case.error.is_none(), "{}", case.name);
|
||||
assert_eq!(case.rendered, case.hf, "{}", case.name);
|
||||
let kwargs = case
|
||||
.enable_thinking
|
||||
.map(|b| ("enable_thinking", Json::Bool(b)))
|
||||
.into_iter()
|
||||
.collect();
|
||||
let got = pinned()
|
||||
.render(&ChatInput {
|
||||
messages: &case.messages,
|
||||
tools: case.tools.as_deref(),
|
||||
add_generation_prompt: case.add_generation_prompt.unwrap_or(true),
|
||||
kwargs,
|
||||
})
|
||||
.unwrap_or_else(|e| panic!("{}: {e}", case.name));
|
||||
assert_eq!(got, case.rendered, "{}", case.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_prompt_matches_upstream_golden_bytes() {
|
||||
let golden: Vec<Value> =
|
||||
serde_json::from_str(include_str!("../../engine/strata/serve/chat_golden.json"))
|
||||
.unwrap();
|
||||
fn typed_text_prompts_match_the_golden_bytes() {
|
||||
let cases = golden();
|
||||
for name in [
|
||||
"single user",
|
||||
"system + user",
|
||||
@@ -198,21 +650,29 @@ mod tests {
|
||||
"whitespace and newlines",
|
||||
"thinking disabled",
|
||||
] {
|
||||
let case = golden.iter().find(|case| case["name"] == name).unwrap();
|
||||
let messages = case["messages"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
let case = cases.iter().find(|case| case.name == name).unwrap();
|
||||
let messages = case
|
||||
.messages
|
||||
.iter()
|
||||
.map(|message| Message {
|
||||
role: match message["role"].as_str().unwrap() {
|
||||
"system" => Role::System,
|
||||
"developer" => Role::Developer,
|
||||
"user" => Role::User,
|
||||
"assistant" => Role::Assistant,
|
||||
role => panic!("unsupported role: {role}"),
|
||||
role: match message.get("role") {
|
||||
Some(Json::String(role)) => match role.as_str() {
|
||||
"system" => Role::System,
|
||||
"developer" => Role::Developer,
|
||||
"user" => Role::User,
|
||||
"assistant" => Role::Assistant,
|
||||
role => panic!("unsupported role: {role}"),
|
||||
},
|
||||
_ => panic!("role"),
|
||||
},
|
||||
content: match message.get("content") {
|
||||
Some(Json::String(text)) => text,
|
||||
_ => panic!("content"),
|
||||
},
|
||||
reasoning: match message.get("reasoning_content") {
|
||||
Some(Json::String(text)) => Some(text),
|
||||
_ => None,
|
||||
},
|
||||
content: message["content"].as_str().unwrap(),
|
||||
reasoning: message["reasoning_content"].as_str(),
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let effort = if name == "thinking disabled" {
|
||||
@@ -220,53 +680,41 @@ mod tests {
|
||||
} else {
|
||||
Effort::XHigh
|
||||
};
|
||||
assert_eq!(
|
||||
render(&messages, effort).unwrap(),
|
||||
case["rendered"],
|
||||
"{name}"
|
||||
);
|
||||
assert_eq!(render(&messages, effort).unwrap(), case.rendered, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn representative_tool_prompt_matches_upstream_golden_bytes() {
|
||||
let golden: Vec<Value> =
|
||||
serde_json::from_str(include_str!("../../engine/strata/serve/chat_golden.json"))
|
||||
.unwrap();
|
||||
let case = golden
|
||||
.iter()
|
||||
.find(|case| case["name"] == "tool call and response")
|
||||
fn flattened_tool_continuation_matches_the_golden_bytes() {
|
||||
let case = golden()
|
||||
.into_iter()
|
||||
.find(|c| c.name == "tool call and response")
|
||||
.unwrap();
|
||||
let function = &case["tools"][0]["function"];
|
||||
let function = case.tools.as_ref().unwrap()[0].get("function").unwrap();
|
||||
let tools = [json!({
|
||||
"type":"function", "name":function["name"], "description":function["description"],
|
||||
"parameters":function["parameters"]
|
||||
"type":"function",
|
||||
"name": serde_json::to_value(function.get("name")).unwrap(),
|
||||
"description": serde_json::to_value(function.get("description")).unwrap(),
|
||||
"parameters": serde_json::to_value(function.get("parameters")).unwrap(),
|
||||
})];
|
||||
let user = |content| Message {
|
||||
role: Role::User,
|
||||
content,
|
||||
reasoning: None,
|
||||
};
|
||||
let messages = [
|
||||
Message {
|
||||
role: Role::User,
|
||||
content: "Weather in Oslo?",
|
||||
reasoning: None,
|
||||
},
|
||||
user("Weather in Oslo?"),
|
||||
Message {
|
||||
role: Role::Assistant,
|
||||
content: "<tool_call>\n<function=get_weather>\n<parameter=city>\nOslo\n</parameter>\n</function>\n</tool_call>",
|
||||
reasoning: None,
|
||||
},
|
||||
Message {
|
||||
role: Role::User,
|
||||
content: "<tool_response>\n{\"temp\": 3}\n</tool_response>",
|
||||
reasoning: None,
|
||||
},
|
||||
Message {
|
||||
role: Role::User,
|
||||
content: "And in Bergen?",
|
||||
reasoning: None,
|
||||
},
|
||||
user("<tool_response>\n{\"temp\": 3}\n</tool_response>"),
|
||||
user("And in Bergen?"),
|
||||
];
|
||||
assert_eq!(
|
||||
render_with_tools(&messages, Effort::XHigh, &tools).unwrap(),
|
||||
case["rendered"]
|
||||
case.rendered
|
||||
);
|
||||
}
|
||||
|
||||
@@ -284,5 +732,127 @@ mod tests {
|
||||
};
|
||||
assert!(render(&[user, system], Effort::XHigh).is_err());
|
||||
assert!(render(&[system], Effort::XHigh).is_err());
|
||||
assert!(render(&[], Effort::XHigh).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn efforts_select_the_template_instructions() {
|
||||
let user = [Message {
|
||||
role: Role::User,
|
||||
content: "hi",
|
||||
reasoning: None,
|
||||
}];
|
||||
let text = |effort| render(&user, effort).unwrap();
|
||||
assert!(text(Effort::XHigh).contains("Reasoning effort is set to xhigh."));
|
||||
assert!(text(Effort::High).contains("Reasoning effort is set to xhigh."));
|
||||
assert!(text(Effort::Low).contains("Reasoning effort is set to low."));
|
||||
assert_eq!(
|
||||
text(Effort::Medium),
|
||||
"<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n<think>\n"
|
||||
);
|
||||
assert_eq!(
|
||||
text(Effort::None),
|
||||
"<|im_start|>user\nhi<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raise_exception_surfaces_the_template_message() {
|
||||
let messages = [Json::object([
|
||||
("role", Json::str("tool")),
|
||||
("content", Json::str("x")),
|
||||
])];
|
||||
let bad = pinned().render(&ChatInput {
|
||||
messages: &[Json::object([
|
||||
("role", Json::str("robot")),
|
||||
("content", Json::str("x")),
|
||||
])],
|
||||
tools: None,
|
||||
add_generation_prompt: true,
|
||||
kwargs: vec![],
|
||||
});
|
||||
assert_eq!(bad.unwrap_err(), "Unexpected message role.");
|
||||
let effort = pinned().render(&ChatInput {
|
||||
messages: &[Json::object([
|
||||
("role", Json::str("user")),
|
||||
("content", Json::str("x")),
|
||||
])],
|
||||
tools: None,
|
||||
add_generation_prompt: true,
|
||||
kwargs: vec![("reasoning_effort", Json::str("extreme"))],
|
||||
});
|
||||
assert_eq!(
|
||||
effort.unwrap_err(),
|
||||
"Unexpected reasoning effort extreme. Supported types are xhigh (default), medium, and low."
|
||||
);
|
||||
let _ = messages;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tojson_matches_python_json_dumps() {
|
||||
let renderer = Renderer::new("{{ value | tojson }}").unwrap();
|
||||
let render = |json: &str| {
|
||||
let value: Json = serde_json::from_str(json).unwrap();
|
||||
let mut context = BTreeMap::new();
|
||||
context.insert("value", Value::from_serialize(&value));
|
||||
renderer
|
||||
.env
|
||||
.get_template("chat")
|
||||
.unwrap()
|
||||
.render(&context)
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(
|
||||
render(r#"{"b": 1, "a": [1.0, 2.5, "x\ny"], "c": null, "d": true}"#),
|
||||
r#"{"b": 1, "a": [1.0, 2.5, "x\ny"], "c": null, "d": true}"#
|
||||
);
|
||||
assert_eq!(
|
||||
render(r#"["é", "\u0001", "\u007f", "😀", "\u2028"]"#),
|
||||
"[\"é\", \"\\u0001\", \"\u{7f}\", \"😀\", \"\u{2028}\"]"
|
||||
);
|
||||
assert_eq!(
|
||||
render("[1e16, 1e15, 1.5e-5, 0.0001, 123456789012345680000.0, -0.0, 100.0]"),
|
||||
"[1e+16, 1000000000000000.0, 1.5e-05, 0.0001, 1.2345678901234568e+20, -0.0, 100.0]"
|
||||
);
|
||||
assert_eq!(
|
||||
render("[18446744073709551615, -9223372036854775808]"),
|
||||
"[18446744073709551615, -9223372036854775808]"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trim_is_pythons_strip() {
|
||||
let renderer = Renderer::new("[{{ value | trim }}]").unwrap();
|
||||
let render = |text: &str| {
|
||||
let mut context = BTreeMap::new();
|
||||
context.insert("value", Value::from(text));
|
||||
renderer
|
||||
.env
|
||||
.get_template("chat")
|
||||
.unwrap()
|
||||
.render(&context)
|
||||
.unwrap()
|
||||
};
|
||||
// U+001C..U+001F are whitespace to Python's str.strip() but not to Unicode White_Space
|
||||
assert_eq!(render("\u{1c}\u{1f} a b \u{a0}\u{3000}\n"), "[a b]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn objects_keep_the_order_they_were_written_in() {
|
||||
let tools: Vec<Json> =
|
||||
serde_json::from_str(r#"[{"type":"function","function":{"name":"f","parameters":{"z":1,"a":{"y":2,"b":3}}}}]"#)
|
||||
.unwrap();
|
||||
let out = pinned()
|
||||
.render(&ChatInput {
|
||||
messages: &[Json::object([
|
||||
("role", Json::str("user")),
|
||||
("content", Json::str("x")),
|
||||
])],
|
||||
tools: Some(&tools),
|
||||
add_generation_prompt: true,
|
||||
kwargs: vec![("enable_thinking", Json::Bool(false))],
|
||||
})
|
||||
.unwrap();
|
||||
assert!(out.contains(r#"{"type": "function", "function": {"name": "f", "parameters": {"z": 1, "a": {"y": 2, "b": 3}}}}"#), "{out}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1664,7 +1664,6 @@ fn render_request_prompt(request: &CreateRequest) -> Result<String, String> {
|
||||
&catalog.flat
|
||||
},
|
||||
)
|
||||
.map_err(str::to_owned)
|
||||
}
|
||||
|
||||
fn stream_live_text(
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
//! The native Jinja renderer against the Python server's `ChatTemplate` (jinja2) on generated conversations.
|
||||
//!
|
||||
//! `tests/fixtures/offline/chat_template_oracle.json` comes from `scripts/offline/gen_goldens.py chat_template_oracle`:
|
||||
//! 90 renders (every role incl. developer and tool, list content with image/video parts, assistant `tool_calls`
|
||||
//! with mapping arguments, tools, `enable_thinking` / `reasoning_effort` / `preserve_thinking`, no generation
|
||||
//! prompt) and 25 conversations the template refuses, with the exact `raise_exception` message.
|
||||
//! `scripts/offline/diff_chat_template.py` runs the same generator live over thousands of cases.
|
||||
use serde::Deserialize;
|
||||
use strata_control::prompt::{ChatInput, Json, pinned};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Case {
|
||||
messages: Vec<Json>,
|
||||
tools: Option<Json>,
|
||||
add_generation_prompt: bool,
|
||||
kwargs: Json,
|
||||
rendered: Option<String>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Golden {
|
||||
ok: Vec<Case>,
|
||||
raised: Vec<Case>,
|
||||
}
|
||||
|
||||
fn render(case: &Case) -> Result<String, String> {
|
||||
let tools = match &case.tools {
|
||||
Some(Json::Array(items)) => Some(items.as_slice()),
|
||||
_ => None, // null, or a mapping the template ignores
|
||||
};
|
||||
let kwargs = match &case.kwargs {
|
||||
Json::Object(fields) => fields
|
||||
.iter()
|
||||
.map(|(k, v)| (k.as_str(), v.clone()))
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
pinned().render(&ChatInput {
|
||||
messages: &case.messages,
|
||||
tools,
|
||||
add_generation_prompt: case.add_generation_prompt,
|
||||
kwargs,
|
||||
})
|
||||
}
|
||||
|
||||
fn golden() -> Golden {
|
||||
serde_json::from_str(include_str!("fixtures/offline/chat_template_oracle.json")).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renders_are_byte_identical_to_jinja2() {
|
||||
let golden = golden();
|
||||
assert!(golden.ok.len() >= 90);
|
||||
for (at, case) in golden.ok.iter().enumerate() {
|
||||
assert_eq!(
|
||||
render(case),
|
||||
Ok(case.rendered.clone().unwrap()),
|
||||
"case {at}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refusals_carry_the_templates_own_message() {
|
||||
let golden = golden();
|
||||
assert!(golden.raised.len() >= 25);
|
||||
for (at, case) in golden.raised.iter().enumerate() {
|
||||
assert_eq!(render(case), Err(case.error.clone().unwrap()), "case {at}");
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,194 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Chat-template differential: strata-next's native Jinja renderer (`model render-chat`) vs the Python server's
|
||||
`ChatTemplate` (serve/frontend.py, jinja2 ImmutableSandboxedEnvironment) on the same template, over generated
|
||||
conversations: every role incl. developer and tool, string / list / null content with image and video parts, reasoning
|
||||
content, assistant tool_calls (mapping / string / malformed arguments), tools with nested schemas and non-ASCII text,
|
||||
and the template kwargs (enable_thinking, reasoning_effort incl. bad values, preserve_thinking, add_generation_prompt).
|
||||
|
||||
Both must either render the same bytes or both refuse; template-raised messages (raise_exception) must match exactly.
|
||||
|
||||
pip install jinja2; python scripts/offline/diff_chat_template.py <strata-next> [--cases N] [--seed S]
|
||||
"""
|
||||
import json
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(REPO / 'engine/strata/serve'))
|
||||
sys.path.insert(0, str(REPO / 'engine/strata'))
|
||||
import jinja2 # noqa: E402,F401
|
||||
from frontend import ChatTemplate, TemplateRequestError # noqa: E402 (the oracle, unchanged)
|
||||
|
||||
TEXTS = ['Hello', '', ' ', ' padded ', 'line1\nline2\n\n', '你好,世界 😀', 'tab\there', ' nbsp ', '\x1c\x1dsep\x1f',
|
||||
' ideographic ', 'quote " and \\ backslash', '<tool_response>\n{"temp": 3}\n</tool_response>',
|
||||
'<tool_response>x</tool_response> trailing', '<think>no</think>', '{{ not a template }} {% nope %}',
|
||||
'a' * 300, 'é' * 40, '\x00nul', '
', '<|im_end|><|im_start|>user']
|
||||
NAMES = ['get_weather', 'search', 'ls', 'my.tool-1', 'ünï', 'a b']
|
||||
|
||||
|
||||
def rand_value(rng, depth=0):
|
||||
kinds = ['s', 'i', 'f', 'b', 'n'] + (['l', 'd'] if depth < 3 else [])
|
||||
k = rng.choice(kinds)
|
||||
if k == 's':
|
||||
return rng.choice(TEXTS[:12] + ['x'])
|
||||
if k == 'i':
|
||||
return rng.choice([0, 1, -5, 2 ** 40, 18446744073709551615])
|
||||
if k == 'f':
|
||||
return rng.choice([0.5, 1.0, 1e16, 1e-5, 123456789.125, -0.0, 2.5e300])
|
||||
if k == 'b':
|
||||
return rng.random() < 0.5
|
||||
if k == 'n':
|
||||
return None
|
||||
if k == 'l':
|
||||
return [rand_value(rng, depth + 1) for _ in range(rng.randint(0, 3))]
|
||||
return {rng.choice(['z', 'a', 'type', 'ключ', 'k y', '']) + str(i): rand_value(rng, depth + 1)
|
||||
for i in range(rng.randint(0, 3))}
|
||||
|
||||
|
||||
def rand_content(rng):
|
||||
r = rng.random()
|
||||
if r < 0.6:
|
||||
return rng.choice(TEXTS)
|
||||
if r < 0.68:
|
||||
return None
|
||||
if r < 0.72:
|
||||
return 42
|
||||
parts = []
|
||||
for _ in range(rng.randint(0, 4)):
|
||||
p = rng.random()
|
||||
if p < 0.5:
|
||||
parts.append({'type': 'text', 'text': rng.choice(TEXTS)})
|
||||
elif p < 0.7:
|
||||
parts.append({'type': 'image_url', 'image_url': {'url': 'data:image/png;base64,AAAA'}})
|
||||
elif p < 0.8:
|
||||
parts.append({'type': 'image'})
|
||||
elif p < 0.88:
|
||||
parts.append({'type': 'video', 'video': 'x.mp4'})
|
||||
elif p < 0.94:
|
||||
parts.append({'text': rng.choice(TEXTS)})
|
||||
else:
|
||||
parts.append({'type': 'audio'}) # unexpected: the template raises
|
||||
return parts
|
||||
|
||||
|
||||
def rand_tool_calls(rng):
|
||||
calls = []
|
||||
for _ in range(rng.randint(1, 3)):
|
||||
r = rng.random()
|
||||
args = rng.choice([{}, {'city': 'Oslo'}, {'z': 1, 'a': [1, 2], 'm': {'y': None, 'b': True}}, {'q': 'multi\nline'},
|
||||
{'n': 1.5, 'u': 'ünï'}])
|
||||
if r < 0.55:
|
||||
calls.append({'type': 'function', 'function': {'name': rng.choice(NAMES), 'arguments': args}})
|
||||
elif r < 0.75:
|
||||
calls.append({'name': rng.choice(NAMES), 'arguments': args})
|
||||
elif r < 0.82:
|
||||
calls.append({'function': {'name': rng.choice(NAMES), 'arguments': json.dumps(args)}})
|
||||
elif r < 0.88:
|
||||
calls.append({'function': {'name': rng.choice(NAMES), 'arguments': ''}})
|
||||
elif r < 0.92:
|
||||
calls.append({'function': {'arguments': args}}) # no name: raises
|
||||
elif r < 0.96:
|
||||
calls.append({'function': {'name': 'f', 'arguments': 5}}) # not an object: raises
|
||||
else:
|
||||
calls.append({'function': {'name': 'f'}})
|
||||
return calls
|
||||
|
||||
|
||||
def rand_messages(rng):
|
||||
n = rng.randint(1, 7)
|
||||
messages = []
|
||||
leading = rng.choice([0, 0, 1, 2, 3])
|
||||
for i in range(leading):
|
||||
messages.append({'role': rng.choice(['system', 'developer']), 'content': rand_content(rng)})
|
||||
for _ in range(n):
|
||||
role = rng.choices(['user', 'assistant', 'tool', 'system', 'developer', 'robot'], [8, 6, 3, 0.4, 0.3, 0.2])[0]
|
||||
m = {'role': role, 'content': rand_content(rng)}
|
||||
if role == 'assistant':
|
||||
if rng.random() < 0.5:
|
||||
m['reasoning_content'] = rng.choice(TEXTS + [None, 5])
|
||||
if rng.random() < 0.4:
|
||||
m['tool_calls'] = rand_tool_calls(rng)
|
||||
elif rng.random() < 0.1:
|
||||
m['tool_calls'] = []
|
||||
messages.append(m)
|
||||
return messages
|
||||
|
||||
|
||||
def rand_tools(rng):
|
||||
if rng.random() < 0.55:
|
||||
return None
|
||||
tools = []
|
||||
for _ in range(rng.randint(0, 3)):
|
||||
schema = {'type': 'object', 'properties': {rng.choice(['city', 'path', 'q', 'zz']) + str(i): {
|
||||
'type': rng.choice(['string', 'integer']), 'description': rng.choice(TEXTS[:8])} for i in range(rng.randint(0, 3))},
|
||||
'required': ['city']}
|
||||
if rng.random() < 0.3:
|
||||
schema['additionalProperties'] = False
|
||||
fn = {'name': rng.choice(NAMES), 'description': rng.choice(['Get the weather', 'ünï "q"', '']), 'parameters': schema}
|
||||
if rng.random() < 0.3:
|
||||
fn['strict'] = True
|
||||
tools.append({'type': 'function', 'function': fn} if rng.random() < 0.9 else fn)
|
||||
return tools if rng.random() < 0.9 else rng.choice([[], {'type': 'function'}])
|
||||
|
||||
|
||||
def rand_kwargs(rng):
|
||||
kw = {}
|
||||
if rng.random() < 0.3:
|
||||
kw['enable_thinking'] = rng.choice([True, False, None])
|
||||
if rng.random() < 0.4:
|
||||
kw['reasoning_effort'] = rng.choice(['low', 'medium', 'high', 'xhigh', 'xhigh', 'extreme', None])
|
||||
if rng.random() < 0.2:
|
||||
kw['preserve_thinking'] = rng.choice([True, False])
|
||||
return kw
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
cases = int(args[args.index('--cases') + 1]) if '--cases' in args else 3000
|
||||
seed = int(args[args.index('--seed') + 1]) if '--seed' in args else 20261014
|
||||
binary = str(Path(args[0]).resolve())
|
||||
rng = random.Random(seed)
|
||||
template = ChatTemplate(REPO / 'engine/strata/serve/chat_template.jinja')
|
||||
requests, expected = [], []
|
||||
for _ in range(cases):
|
||||
req = {'messages': rand_messages(rng), 'tools': rand_tools(rng),
|
||||
'add_generation_prompt': rng.random() < 0.9, 'kwargs': rand_kwargs(rng)}
|
||||
requests.append(req)
|
||||
try:
|
||||
expected.append({'ok': template.render(req['messages'], req['tools'], req['add_generation_prompt'],
|
||||
**req['kwargs'])})
|
||||
except TemplateRequestError as e:
|
||||
expected.append({'error': str(e), 'raised': True})
|
||||
except Exception as e: # noqa: BLE001 (jinja2 UndefinedError, TypeError ...: the Python server answers 400/500)
|
||||
expected.append({'error': f'{type(e).__name__}: {e}', 'raised': False})
|
||||
payload = ''.join(json.dumps(r, ensure_ascii=False) + '\n' for r in requests).encode('utf-8')
|
||||
run = subprocess.run([binary, 'model', 'render-chat'], input=payload, capture_output=True)
|
||||
if run.returncode:
|
||||
print('FAIL render-chat exited', run.returncode, run.stderr.decode()[-300:])
|
||||
return 1
|
||||
got = [json.loads(l) for l in run.stdout.decode('utf-8').split('\n')[:-1]]
|
||||
bad, both_error, agree_ok = [], 0, 0
|
||||
for i, (want, have, req) in enumerate(zip(expected, got, requests)):
|
||||
if 'ok' in want and 'ok' in have:
|
||||
if want['ok'] != have['ok']:
|
||||
bad.append(f'case {i}: bytes differ\n python: {want["ok"]!r}\n rust: {have["ok"]!r}\n request: {json.dumps(req, ensure_ascii=False)[:400]}')
|
||||
else:
|
||||
agree_ok += 1
|
||||
elif 'error' in want and 'error' in have:
|
||||
both_error += 1
|
||||
if want['raised'] and want['error'] != have['error']:
|
||||
bad.append(f'case {i}: raise_exception messages differ: {want["error"]!r} vs {have["error"]!r}')
|
||||
else:
|
||||
bad.append(f'case {i}: python {list(want)} vs rust {list(have)}: {want.get("error") or have.get("error")}\n request: {json.dumps(req, ensure_ascii=False)[:400]}')
|
||||
assert len(got) == len(expected)
|
||||
for b in bad[:12]:
|
||||
print('FAIL', b)
|
||||
print(json.dumps({'cases': cases, 'identical_renders': agree_ok, 'both_refused': both_error, 'failures': len(bad),
|
||||
'jinja2': jinja2.__version__, 'oracle': 'serve/frontend.py ChatTemplate (unmodified)'}))
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -272,6 +272,33 @@ def setup_policy():
|
||||
(target / 'setup_policy_oracle.json').write_text(json.dumps(out, separators=(',', ':')) + '\n')
|
||||
|
||||
|
||||
@golden
|
||||
def chat_template_oracle():
|
||||
"""Generated conversations (all roles, list content with image parts, tool_calls, tools, kwargs) and what the Python
|
||||
server's ChatTemplate renders - or the message it raises - for each."""
|
||||
import random
|
||||
import diff_chat_template as D
|
||||
rng = random.Random(20261014)
|
||||
template = D.ChatTemplate(REPO / 'engine/strata/serve/chat_template.jinja')
|
||||
cases = {'ok': [], 'raised': []}
|
||||
while len(cases['ok']) < 90 or len(cases['raised']) < 25:
|
||||
req = {'messages': D.rand_messages(rng), 'tools': D.rand_tools(rng),
|
||||
'add_generation_prompt': rng.random() < 0.9, 'kwargs': D.rand_kwargs(rng)}
|
||||
if len(json.dumps(req)) > 2500:
|
||||
continue
|
||||
try:
|
||||
text = template.render(req['messages'], req['tools'], req['add_generation_prompt'], **req['kwargs'])
|
||||
if len(cases['ok']) < 90:
|
||||
cases['ok'].append({**req, 'rendered': text})
|
||||
except D.TemplateRequestError as e:
|
||||
if len(cases['raised']) < 25:
|
||||
cases['raised'].append({**req, 'error': str(e)})
|
||||
except Exception: # noqa: BLE001 (jinja2 errors: not part of the contract)
|
||||
pass
|
||||
(OUT / 'chat_template_oracle.json').write_text(json.dumps(cases, ensure_ascii=False, separators=(',', ':')) + '\n',
|
||||
encoding='utf-8')
|
||||
|
||||
|
||||
def main():
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
names = sys.argv[1:] or list(GENERATORS)
|
||||
|
||||
Reference in New Issue
Block a user