The gpt-oss template writes "Current date: <UTC today>" into the system message, which is part of the prefix a worker's KV cache is matched on, so every cache missed once a day at midnight UTC. prompt_date in the config (STRATA_PROMPT_DATE) now selects: utc (default, unchanged), a fixed YYYY-MM-DD, or none, which leaves the line out (RenderOptions::omit_date; the blank line after it stays) for clients that give the date as a function tool. The control plane does not host tools; the client supplies the tool. Teacher-forced on four 770-957 token prompts the model is not indifferent: dropping the line moves the next-token distribution by mean KL 0.034-0.056 (best token same at 89-90%), changing only the date value by 0.023-0.040 (92-93%), numerical noise 0.005-0.023 (93-97%). Task quality was not measured, so none is opt-in. Checked end to end through the control plane: 68 input tokens for "Hi" with the date, 57 without, 68 with a fixed date; a bad value is refused at start. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
512 lines
19 KiB
Rust
512 lines
19 KiB
Rust
//! Prompt rendering. Mirrors the gpt-oss chat template (Jinja) statement by statement; the odd
|
|
//! whitespace in nested object types is the template's, kept on purpose.
|
|
|
|
use crate::{HarmonyError, Message, Role, Tool};
|
|
use serde_json::{Map, Value};
|
|
|
|
#[derive(Clone, Debug)]
|
|
pub struct RenderOptions {
|
|
/// `YYYY-MM-DD`, written into the system message.
|
|
pub current_date: String,
|
|
/// EXPERIMENTAL: leave the "Current date:" line out of the system message (the model is trained with it; the
|
|
/// blank line that follows it stays). For clients that offer the date as a tool, and for stable prompt prefixes.
|
|
pub omit_date: bool,
|
|
/// `low`, `medium` or `high`.
|
|
pub reasoning_effort: String,
|
|
/// Replaces "You are ChatGPT, a large language model trained by OpenAI." when set.
|
|
pub model_identity: Option<String>,
|
|
/// Append `<|start|>assistant` so the model continues as the assistant.
|
|
pub add_generation_prompt: bool,
|
|
/// Write the special markers as private-use sentinel characters ([`SENTINELS`]) and neutralize those
|
|
/// characters in caller text, so a tokenizer can map exactly the template's markers to special tokens.
|
|
pub sentinel_markers: bool,
|
|
}
|
|
|
|
impl RenderOptions {
|
|
pub fn new(current_date: impl Into<String>) -> Self {
|
|
Self {
|
|
current_date: current_date.into(),
|
|
omit_date: false,
|
|
reasoning_effort: "medium".into(),
|
|
model_identity: None,
|
|
add_generation_prompt: true,
|
|
sentinel_markers: false,
|
|
}
|
|
}
|
|
}
|
|
|
|
fn err(what: impl Into<String>) -> HarmonyError {
|
|
HarmonyError::InvalidConversation(what.into())
|
|
}
|
|
|
|
// ---- Jinja value semantics used by the template ----
|
|
|
|
/// Jinja truthiness of an optional JSON value.
|
|
fn truthy(v: Option<&Value>) -> bool {
|
|
match v {
|
|
None | Some(Value::Null) => false,
|
|
Some(Value::Bool(b)) => *b,
|
|
Some(Value::Number(n)) => n.as_f64().is_some_and(|f| f != 0.0),
|
|
Some(Value::String(s)) => !s.is_empty(),
|
|
Some(Value::Array(a)) => !a.is_empty(),
|
|
Some(Value::Object(o)) => !o.is_empty(),
|
|
}
|
|
}
|
|
|
|
/// `json.dumps`-style output as minja's `tojson` writes it: ", " and ": " separators, keys in
|
|
/// insertion order, non-ASCII characters kept as they are.
|
|
pub(crate) fn to_json(v: &Value) -> String {
|
|
let mut out = String::new();
|
|
write_json(v, &mut out);
|
|
out
|
|
}
|
|
|
|
fn write_json_string(s: &str, out: &mut String) {
|
|
out.push('"');
|
|
for c in s.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 => out.push(c),
|
|
}
|
|
}
|
|
out.push('"');
|
|
}
|
|
|
|
fn write_json(v: &Value, out: &mut String) {
|
|
match v {
|
|
Value::Null => out.push_str("null"),
|
|
Value::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
|
|
Value::Number(n) => out.push_str(&n.to_string()),
|
|
Value::String(s) => write_json_string(s, out),
|
|
Value::Array(a) => {
|
|
out.push('[');
|
|
for (i, item) in a.iter().enumerate() {
|
|
if i > 0 {
|
|
out.push_str(", ");
|
|
}
|
|
write_json(item, out);
|
|
}
|
|
out.push(']');
|
|
}
|
|
Value::Object(o) => {
|
|
out.push('{');
|
|
for (i, (k, item)) in o.iter().enumerate() {
|
|
if i > 0 {
|
|
out.push_str(", ");
|
|
}
|
|
write_json_string(k, out);
|
|
out.push_str(": ");
|
|
write_json(item, out);
|
|
}
|
|
out.push('}');
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A JSON value as Jinja's string concatenation would take it (only strings concatenate).
|
|
fn as_concat_str(v: &Value, what: &str) -> Result<String, HarmonyError> {
|
|
match v {
|
|
Value::String(s) => Ok(s.clone()),
|
|
other => Err(err(format!(
|
|
"{what} must be a string to be joined into the prompt, found {}",
|
|
to_json(other)
|
|
))),
|
|
}
|
|
}
|
|
|
|
// ---- tool definitions ----
|
|
|
|
/// Indent the template writes before the type of a property inside an object type.
|
|
const NESTED_INDENT: &str = " ";
|
|
/// Indent before a oneOf variant's default comment (the template's, on its expression line).
|
|
const ONE_OF_DEFAULT_INDENT: &str = " ";
|
|
|
|
fn render_type(spec: &Value) -> Result<String, HarmonyError> {
|
|
let get = |k: &str| spec.get(k);
|
|
let ty = get("type");
|
|
let mut out = String::new();
|
|
if ty.and_then(Value::as_str) == Some("array") {
|
|
let items = get("items");
|
|
if truthy(items) {
|
|
let items = items.expect("truthy");
|
|
match items.get("type").and_then(Value::as_str) {
|
|
Some("string") => out.push_str("string[]"),
|
|
Some("number") | Some("integer") => out.push_str("number[]"),
|
|
Some("boolean") => out.push_str("boolean[]"),
|
|
_ => {
|
|
let inner = render_type(items)?;
|
|
if inner == "object | object" || inner.chars().count() > 50 {
|
|
out.push_str("any[]");
|
|
} else {
|
|
out.push_str(&inner);
|
|
out.push_str("[]");
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
out.push_str("any[]");
|
|
}
|
|
if truthy(get("nullable")) {
|
|
out.push_str(" | null");
|
|
}
|
|
return Ok(out);
|
|
}
|
|
if let Some(Value::Array(types)) = ty
|
|
&& !types.is_empty()
|
|
{
|
|
// a list of types such as ["string", "null"]
|
|
let names: Vec<String> = types
|
|
.iter()
|
|
.map(|t| as_concat_str(t, "a type name"))
|
|
.collect::<Result<_, _>>()?;
|
|
return Ok(if names.len() > 1 {
|
|
names.join(" | ")
|
|
} else {
|
|
names[0].clone()
|
|
});
|
|
}
|
|
if truthy(get("oneOf")) {
|
|
// The template tests for object variants with a `set` inside a loop, which does not leak out of
|
|
// the loop in Jinja, so its "any" shortcut never applies: every alternative is rendered.
|
|
let variants = get("oneOf")
|
|
.and_then(Value::as_array)
|
|
.cloned()
|
|
.unwrap_or_default();
|
|
for (i, variant) in variants.iter().enumerate() {
|
|
out.push_str(&render_type(variant)?);
|
|
if truthy(variant.get("description")) {
|
|
out.push_str("// ");
|
|
out.push_str(&as_concat_str(&variant["description"], "a description")?);
|
|
}
|
|
if let Some(default) = variant.get("default") {
|
|
out.push_str(ONE_OF_DEFAULT_INDENT);
|
|
out.push_str("// default: ");
|
|
out.push_str(&to_json(default));
|
|
}
|
|
if i + 1 < variants.len() {
|
|
out.push_str(" | \n");
|
|
}
|
|
}
|
|
return Ok(out);
|
|
}
|
|
match ty.and_then(Value::as_str) {
|
|
Some("string") => {
|
|
let en = get("enum");
|
|
if truthy(en) {
|
|
let names: Vec<String> = en
|
|
.and_then(Value::as_array)
|
|
.map(|a| {
|
|
a.iter()
|
|
.map(|v| as_concat_str(v, "an enum value"))
|
|
.collect()
|
|
})
|
|
.unwrap_or_else(|| Ok(Vec::new()))?;
|
|
out.push('"');
|
|
out.push_str(&names.join("\" | \""));
|
|
out.push('"');
|
|
} else {
|
|
out.push_str("string");
|
|
if truthy(get("nullable")) {
|
|
out.push_str(" | null");
|
|
}
|
|
}
|
|
}
|
|
Some("number") | Some("integer") => out.push_str("number"),
|
|
Some("boolean") => out.push_str("boolean"),
|
|
Some("object") => {
|
|
let props = get("properties");
|
|
if truthy(props) {
|
|
let props: &Map<String, Value> = props
|
|
.and_then(Value::as_object)
|
|
.ok_or_else(|| err("properties must be an object"))?;
|
|
let required = required_names(spec)?;
|
|
out.push_str("{\n");
|
|
let last = props.len() - 1;
|
|
for (i, (name, prop)) in props.iter().enumerate() {
|
|
out.push_str(name);
|
|
if !required.contains(name) {
|
|
out.push('?');
|
|
}
|
|
out.push_str(": ");
|
|
out.push('\n');
|
|
out.push_str(NESTED_INDENT);
|
|
out.push_str(&render_type(prop)?);
|
|
if i != last {
|
|
out.push_str(", ");
|
|
}
|
|
}
|
|
out.push('}');
|
|
} else {
|
|
out.push_str("object");
|
|
}
|
|
}
|
|
_ => out.push_str("any"),
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
fn required_names(spec: &Value) -> Result<Vec<String>, HarmonyError> {
|
|
match spec.get("required") {
|
|
Some(Value::Array(a)) => a
|
|
.iter()
|
|
.map(|v| as_concat_str(v, "a required name"))
|
|
.collect(),
|
|
_ => Ok(Vec::new()),
|
|
}
|
|
}
|
|
|
|
fn render_namespace(name: &str, tools: &[Tool]) -> Result<String, HarmonyError> {
|
|
let mut out = format!("## {name}\n\nnamespace {name} {{\n\n");
|
|
for tool in tools {
|
|
if let Some(description) = &tool.description {
|
|
out.push_str(&format!("// {description}\n"));
|
|
}
|
|
out.push_str(&format!("type {} = ", tool.name));
|
|
let props = tool.parameters.get("properties");
|
|
if truthy(Some(&tool.parameters)) && truthy(props) {
|
|
let props = props
|
|
.and_then(Value::as_object)
|
|
.ok_or_else(|| err("tool parameters: properties must be an object"))?;
|
|
let required = required_names(&tool.parameters)?;
|
|
out.push_str("(_: {\n");
|
|
let last = props.len() - 1;
|
|
for (i, (param, spec)) in props.iter().enumerate() {
|
|
if truthy(spec.get("description")) {
|
|
out.push_str(&format!(
|
|
"// {}\n",
|
|
as_concat_str(&spec["description"], "a description")?
|
|
));
|
|
}
|
|
out.push_str(param);
|
|
if !required.contains(param) {
|
|
out.push('?');
|
|
}
|
|
out.push_str(": ");
|
|
out.push_str(&render_type(spec)?);
|
|
if let Some(default) = spec.get("default") {
|
|
if truthy(spec.get("enum")) {
|
|
out.push_str(", // default: ");
|
|
out.push_str(&as_concat_str(default, "a default")?);
|
|
} else if truthy(spec.get("oneOf")) {
|
|
out.push_str("// default: ");
|
|
out.push_str(&as_concat_str(default, "a default")?);
|
|
} else {
|
|
out.push_str(", // default: ");
|
|
out.push_str(&to_json(default));
|
|
}
|
|
}
|
|
out.push_str(if i != last { ",\n" } else { "\n" });
|
|
}
|
|
out.push_str("}) => any;\n\n");
|
|
} else {
|
|
out.push_str("() => any;\n\n");
|
|
}
|
|
}
|
|
out.push_str(&format!("}} // namespace {name}"));
|
|
Ok(out)
|
|
}
|
|
|
|
// ---- the conversation ----
|
|
|
|
/// The private-use characters that stand for the format's special tokens in sentinel mode, in the order
|
|
/// start, end, message, channel, call, return, constrain.
|
|
pub const SENTINELS: [(char, &str); 7] = [
|
|
('\u{E000}', "<|start|>"),
|
|
('\u{E001}', "<|end|>"),
|
|
('\u{E002}', "<|message|>"),
|
|
('\u{E003}', "<|channel|>"),
|
|
('\u{E004}', "<|call|>"),
|
|
('\u{E005}', "<|return|>"),
|
|
('\u{E006}', "<|constrain|>"),
|
|
];
|
|
|
|
/// The prompt under construction. Template text goes in through [`Out::lit`], text that came from the
|
|
/// caller through [`Out::text`]. In sentinel mode the template's special markers are written as their
|
|
/// [`SENTINELS`] and any sentinel character in caller text is replaced, so only the template can
|
|
/// produce a marker when the result is tokenized.
|
|
struct Out {
|
|
s: String,
|
|
sentinel: bool,
|
|
}
|
|
|
|
impl Out {
|
|
fn new(sentinel: bool) -> Self {
|
|
Self {
|
|
s: String::new(),
|
|
sentinel,
|
|
}
|
|
}
|
|
|
|
fn lit(&mut self, template: &str) {
|
|
if self.sentinel {
|
|
let mut mapped = template.to_owned();
|
|
for (character, marker) in SENTINELS {
|
|
mapped = mapped.replace(marker, &character.to_string());
|
|
}
|
|
self.s.push_str(&mapped);
|
|
} else {
|
|
self.s.push_str(template);
|
|
}
|
|
}
|
|
|
|
fn text(&mut self, caller_text: &str) {
|
|
if self.sentinel {
|
|
self.s.extend(caller_text.chars().map(|c| {
|
|
if SENTINELS.iter().any(|(s, _)| *s == c) {
|
|
'\u{FFFD}'
|
|
} else {
|
|
c
|
|
}
|
|
}));
|
|
} else {
|
|
self.s.push_str(caller_text);
|
|
}
|
|
}
|
|
}
|
|
/// Render `messages` and `tools` as the gpt-oss prompt.
|
|
pub fn render(
|
|
messages: &[Message],
|
|
tools: &[Tool],
|
|
options: &RenderOptions,
|
|
) -> Result<String, HarmonyError> {
|
|
let mut out = Out::new(options.sentinel_markers);
|
|
out.lit("<|start|>system<|message|>");
|
|
out.text(
|
|
options
|
|
.model_identity
|
|
.as_deref()
|
|
.unwrap_or("You are ChatGPT, a large language model trained by OpenAI."),
|
|
);
|
|
out.lit("\nKnowledge cutoff: 2024-06\n");
|
|
if options.omit_date {
|
|
out.lit("\n");
|
|
} else {
|
|
out.text(&format!("Current date: {}\n\n", options.current_date));
|
|
}
|
|
out.text(&format!("Reasoning: {}\n\n", options.reasoning_effort));
|
|
out.lit("# Valid channels: analysis, commentary, final. Channel must be included for every message.");
|
|
if !tools.is_empty() {
|
|
out.lit("\nCalls to these tools must go to the commentary channel: 'functions'.");
|
|
}
|
|
out.lit("<|end|>");
|
|
|
|
// the first system or developer message carries the developer instructions
|
|
let (developer, rest) = match messages.first() {
|
|
Some(m) if matches!(m.role, Role::Developer | Role::System) => {
|
|
(m.content.clone().unwrap_or_default(), &messages[1..])
|
|
}
|
|
_ => (String::new(), messages),
|
|
};
|
|
if !developer.is_empty() || !tools.is_empty() {
|
|
out.lit("<|start|>developer<|message|>");
|
|
if !developer.is_empty() {
|
|
out.lit("# Instructions\n\n");
|
|
out.text(&developer);
|
|
}
|
|
if !tools.is_empty() {
|
|
out.lit("\n\n# Tools\n\n");
|
|
out.text(&render_namespace("functions", tools)?);
|
|
}
|
|
out.lit("<|end|>");
|
|
}
|
|
|
|
let mut last_tool_call: Option<String> = None;
|
|
for (index, message) in rest.iter().enumerate() {
|
|
let is_last = index + 1 == rest.len();
|
|
match message.role {
|
|
Role::Assistant => {
|
|
if let Some(call) = message.tool_calls.first() {
|
|
let content = message.content.as_deref().filter(|c| !c.is_empty());
|
|
let thinking = message.thinking.as_deref().filter(|c| !c.is_empty());
|
|
match (content, thinking) {
|
|
(Some(_), Some(_)) => {
|
|
return Err(err(
|
|
"an assistant message with tool calls cannot have both content and thinking",
|
|
));
|
|
}
|
|
(Some(text), None) | (None, Some(text)) => {
|
|
out.lit("<|start|>assistant<|channel|>analysis<|message|>");
|
|
out.text(text);
|
|
out.lit("<|end|>");
|
|
}
|
|
(None, None) => {}
|
|
}
|
|
out.lit("<|start|>assistant to=functions.");
|
|
out.text(&call.name);
|
|
out.lit("<|channel|>commentary ");
|
|
out.text(call.content_type.as_deref().unwrap_or("json"));
|
|
out.lit("<|message|>");
|
|
out.text(&to_json(&call.arguments));
|
|
out.lit("<|call|>");
|
|
last_tool_call = Some(call.name.clone());
|
|
} else {
|
|
let content = message
|
|
.content
|
|
.as_deref()
|
|
.ok_or_else(|| err("an assistant message needs content"))?;
|
|
if let Some(thinking) = &message.thinking
|
|
&& (thinking.contains("<|channel|>analysis<|message|>")
|
|
|| thinking.contains("<|channel|>final<|message|>"))
|
|
{
|
|
return Err(err("thinking must not contain channel markers"));
|
|
}
|
|
if is_last && !options.add_generation_prompt {
|
|
if let Some(thinking) = &message.thinking {
|
|
out.lit("<|start|>assistant<|channel|>analysis<|message|>");
|
|
out.text(thinking);
|
|
out.lit("<|end|>");
|
|
}
|
|
out.lit("<|start|>assistant<|channel|>final<|message|>");
|
|
out.text(content);
|
|
out.lit("<|return|>");
|
|
} else {
|
|
out.lit("<|start|>assistant<|channel|>final<|message|>");
|
|
out.text(content);
|
|
out.lit("<|end|>");
|
|
last_tool_call = None;
|
|
}
|
|
}
|
|
}
|
|
Role::Tool => {
|
|
let Some(name) = &last_tool_call else {
|
|
return Err(err(
|
|
"a tool message needs an earlier assistant message with a tool call",
|
|
));
|
|
};
|
|
let content = message
|
|
.content
|
|
.as_deref()
|
|
.ok_or_else(|| err("a tool message needs content"))?;
|
|
out.lit("<|start|>functions.");
|
|
out.text(name);
|
|
out.lit(" to=assistant<|channel|>commentary<|message|>");
|
|
out.text(&to_json(&Value::String(content.to_owned())));
|
|
out.lit("<|end|>");
|
|
}
|
|
Role::User => {
|
|
out.lit("<|start|>user<|message|>");
|
|
out.text(
|
|
message
|
|
.content
|
|
.as_deref()
|
|
.ok_or_else(|| err("a user message needs content"))?,
|
|
);
|
|
out.lit("<|end|>");
|
|
}
|
|
// later system or developer messages are not rendered, as in the template
|
|
Role::System | Role::Developer => {}
|
|
}
|
|
}
|
|
if options.add_generation_prompt {
|
|
out.lit("<|start|>assistant");
|
|
}
|
|
Ok(out.s)
|
|
}
|