Add context compositor: named sections from SQLite + DIALOG region
The model context is now composed by a dedicated module (src/context.rs) from named sections wrapped in <NAME>...</NAME>. Static sections (SYSTEM_PROMPT, TOOL_USE) live in a new context_sections SQLite table (seeded once, editable/extensible without recompiling); SYSTEM_PROMPT injects identity/speaker-note/session-SP via placeholders. DIALOG wraps the real role messages (history + new turn) with opener/closer markers so the engine keeps turn structure. Provenance/time helpers moved into the compositor; build_request now only assembles sampling. +tests (140 green), clippy/fmt clean; live probe confirms the model sees the sections.
This commit is contained in:
1 parent
77bfa72689
commit
a4722b7379
4 files changed
+433
-238
No files matched your search
+262
@@ -0,0 +1,262 @@
|
||||
//! The context compositor: assembles the model prompt from named sections.
|
||||
//!
|
||||
//! Static sections (`SYSTEM_PROMPT`, `TOOL_USE`, …) live in the store and are
|
||||
//! emitted wrapped in `<NAME>…</NAME>`; the interactive `DIALOG` region wraps the
|
||||
//! real role messages (history + new turn) so the engine keeps its turn structure.
|
||||
//! Per-turn `[SPEAKER]` provenance and the server-local stamp are applied here,
|
||||
//! prompt-only (stored content stays clean). Adding a section = adding a store row.
|
||||
|
||||
use crate::api::types::{now_unix, ChatMessage, Role};
|
||||
use crate::i18n::t;
|
||||
use crate::store::{ContextSection, Session, StoredMessage};
|
||||
|
||||
/// Compose the full context message list: static sections, then the DIALOG region.
|
||||
/// `user_content` is the new turn's typed text plus attachment context.
|
||||
pub fn compose(
|
||||
sess: &Session,
|
||||
history: &[StoredMessage],
|
||||
user_content: &str,
|
||||
images: &[serde_json::Value],
|
||||
user_name: &str,
|
||||
sections: &[ContextSection],
|
||||
) -> Vec<ChatMessage> {
|
||||
let mut messages = Vec::new();
|
||||
// Server-local timezone offset, computed once for every turn in this request.
|
||||
let tz_offset = server_utc_offset_secs();
|
||||
// Structural identity reminder (name + personal folder) and the speaker
|
||||
// convention are injected into the SYSTEM_PROMPT template via placeholders.
|
||||
let mut identity = t("identity.name", &[("name", &sess.title)]);
|
||||
if let Some(folder) = &sess.folder {
|
||||
identity.push_str(&t("identity.folder", &[("folder", folder)]));
|
||||
}
|
||||
let speaker_note = t("speaker.note", &[]);
|
||||
let session_prompt = sess.settings.system_prompt.clone().unwrap_or_default();
|
||||
// Static context sections live in the store (editable without recompiling);
|
||||
// each is emitted as a system message wrapped in its own <NAME> tag.
|
||||
for sec in sections {
|
||||
let rendered = sec
|
||||
.content
|
||||
.replace("{identity}", &identity)
|
||||
.replace("{speaker_note}", &speaker_note)
|
||||
.replace("{session_prompt}", &session_prompt);
|
||||
messages.push(text_message(
|
||||
Role::System,
|
||||
format!("<{}>\n{}\n</{}>", sec.name, rendered, sec.name),
|
||||
));
|
||||
}
|
||||
// The interactive region is its own section: opener/closer markers around the
|
||||
// real role messages, which keep the engine's turn structure intact.
|
||||
messages.push(text_message(Role::System, "<DIALOG>".to_string()));
|
||||
for m in history {
|
||||
// Per-turn provenance for the model: [SPEAKER: name - datetime]. The
|
||||
// human uses the global user name; the assistant uses the session name.
|
||||
// Tool/system turns stay untagged. Strip any tag the model echoed into
|
||||
// stored content so we never stack a second one (duplication loop).
|
||||
let clean = strip_speaker_tags(&m.content);
|
||||
let content = match m.role.as_str() {
|
||||
"user" => format!(
|
||||
"{}{}",
|
||||
speaker_prefix(user_name, m.created_at, tz_offset),
|
||||
clean
|
||||
),
|
||||
"assistant" => format!(
|
||||
"{}{}",
|
||||
speaker_prefix(&sess.title, m.created_at, tz_offset),
|
||||
clean
|
||||
),
|
||||
_ => clean,
|
||||
};
|
||||
let mut msg = text_message(role_of(&m.role), content);
|
||||
msg.tool_calls = m
|
||||
.tool_calls_json
|
||||
.as_deref()
|
||||
.and_then(|s| serde_json::from_str(s).ok());
|
||||
messages.push(msg);
|
||||
}
|
||||
// The user turn: typed text + attachment context. Images become multipart
|
||||
// image_url parts that the Vision bridge materializes; else a plain string.
|
||||
let user_text = format!(
|
||||
"{}{}",
|
||||
speaker_prefix(user_name, now_unix() as i64, tz_offset),
|
||||
user_content
|
||||
);
|
||||
if images.is_empty() {
|
||||
messages.push(text_message(Role::User, user_text));
|
||||
} else {
|
||||
let mut parts = vec![serde_json::json!({"type": "text", "text": user_text})];
|
||||
parts.extend(images.iter().cloned());
|
||||
messages.push(ChatMessage {
|
||||
role: Role::User,
|
||||
content: Some(serde_json::Value::Array(parts)),
|
||||
tool_call_id: None,
|
||||
tool_calls: None,
|
||||
name: None,
|
||||
reasoning_content: None,
|
||||
});
|
||||
}
|
||||
messages.push(text_message(Role::System, "</DIALOG>".to_string()));
|
||||
messages
|
||||
}
|
||||
|
||||
fn role_of(s: &str) -> Role {
|
||||
match s {
|
||||
"system" | "developer" => Role::System,
|
||||
"assistant" => Role::Assistant,
|
||||
"tool" => Role::Tool,
|
||||
_ => Role::User,
|
||||
}
|
||||
}
|
||||
|
||||
fn text_message(role: Role, text: String) -> ChatMessage {
|
||||
ChatMessage {
|
||||
role,
|
||||
content: Some(serde_json::Value::String(text)),
|
||||
tool_call_id: None,
|
||||
tool_calls: None,
|
||||
name: None,
|
||||
reasoning_content: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The `[SPEAKER: name - datetime]` line prefixed to a turn's content in the
|
||||
/// model prompt (provenance), followed by a newline. `offset` is the server's
|
||||
/// UTC offset in seconds, so the stamp is in the server's local timezone.
|
||||
fn speaker_prefix(name: &str, secs: i64, offset: i64) -> String {
|
||||
format!(
|
||||
"{}\n",
|
||||
t(
|
||||
"speaker.tag",
|
||||
&[("name", name), ("when", &format_stamp(secs, offset))]
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/// Remove leading `[SPEAKER: name - YYYY-MM-DD HH:MM]` tag(s) a model may have
|
||||
/// echoed into its own reply. The tag is framework metadata for the prompt, not
|
||||
/// reply text: stripping keeps stored/displayed content clean and breaks the
|
||||
/// history feedback loop that would otherwise stack a second tag each turn.
|
||||
pub fn strip_speaker_tags(content: &str) -> String {
|
||||
let mut rest = content;
|
||||
let mut stripped = false;
|
||||
loop {
|
||||
let t = rest.trim_start();
|
||||
if !t.starts_with("[SPEAKER:") {
|
||||
break;
|
||||
}
|
||||
let Some(end) = t.find(']') else { break };
|
||||
let inner = &t[..end];
|
||||
let Some(dash) = inner.rfind(" - ") else {
|
||||
break;
|
||||
};
|
||||
if !looks_like_stamp(&inner[dash + 3..]) {
|
||||
break;
|
||||
}
|
||||
rest = &t[end + 1..];
|
||||
stripped = true;
|
||||
}
|
||||
if stripped {
|
||||
rest.trim_start().to_string()
|
||||
} else {
|
||||
content.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `s` is exactly `YYYY-MM-DD HH:MM` (the speaker tag's stamp shape).
|
||||
fn looks_like_stamp(s: &str) -> bool {
|
||||
let b = s.as_bytes();
|
||||
if b.len() != 16 {
|
||||
return false;
|
||||
}
|
||||
b.iter().enumerate().all(|(i, c)| match i {
|
||||
4 | 7 => *c == b'-',
|
||||
10 => *c == b' ',
|
||||
13 => *c == b':',
|
||||
_ => c.is_ascii_digit(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Format unix seconds as `YYYY-MM-DD HH:MM` in the server's local timezone
|
||||
/// (`offset` seconds east of UTC). Dependency-free civil-date arithmetic.
|
||||
fn format_stamp(secs: i64, offset: i64) -> String {
|
||||
let local = secs + offset;
|
||||
let days = local.div_euclid(86400);
|
||||
let tod = local.rem_euclid(86400);
|
||||
let (y, m, d) = civil_from_days(days);
|
||||
format!(
|
||||
"{y:04}-{m:02}-{d:02} {:02}:{:02}",
|
||||
tod / 3600,
|
||||
(tod % 3600) / 60
|
||||
)
|
||||
}
|
||||
|
||||
/// The server's current UTC offset in seconds, from the OS `date +%z` (reads the
|
||||
/// system timezone incl. DST). One cheap call per request build; 0 (UTC) on fail.
|
||||
fn server_utc_offset_secs() -> i64 {
|
||||
std::process::Command::new("date")
|
||||
.arg("+%z")
|
||||
.output()
|
||||
.ok()
|
||||
.and_then(|o| String::from_utf8(o.stdout).ok())
|
||||
.and_then(|s| parse_utc_offset(s.trim()))
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Parse `date +%z` output ("+0100", "-0500") into seconds east of UTC.
|
||||
fn parse_utc_offset(s: &str) -> Option<i64> {
|
||||
let b = s.as_bytes();
|
||||
if b.len() != 5 {
|
||||
return None;
|
||||
}
|
||||
let sign = match b[0] {
|
||||
b'+' => 1,
|
||||
b'-' => -1,
|
||||
_ => return None,
|
||||
};
|
||||
let hh: i64 = s.get(1..3)?.parse().ok()?;
|
||||
let mm: i64 = s.get(3..5)?.parse().ok()?;
|
||||
Some(sign * (hh * 3600 + mm * 60))
|
||||
}
|
||||
|
||||
/// Days since 1970-01-01 -> (year, month, day). Howard Hinnant's algorithm.
|
||||
fn civil_from_days(z: i64) -> (i64, u32, u32) {
|
||||
let z = z + 719468;
|
||||
let era = if z >= 0 { z } else { z - 146096 } / 146097;
|
||||
let doe = z - era * 146097;
|
||||
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
|
||||
let y = yoe + era * 400;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
(if m <= 2 { y + 1 } else { y }, m as u32, d as u32)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn strip_speaker_tags_removes_echoed_prefixes() {
|
||||
let tag = "[SPEAKER: prato-rapido - 2026-11-25 21:09]";
|
||||
assert_eq!(strip_speaker_tags(&format!("{tag} {tag} Certo.")), "Certo.");
|
||||
assert_eq!(strip_speaker_tags(&format!("{tag}\nCerto.")), "Certo.");
|
||||
assert_eq!(strip_speaker_tags("Certo."), "Certo.");
|
||||
assert_eq!(strip_speaker_tags("[nota] testo"), "[nota] testo");
|
||||
assert_eq!(
|
||||
strip_speaker_tags("[SPEAKER: x - not-a-date] testo"),
|
||||
"[SPEAKER: x - not-a-date] testo"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_stamp_known_dates_and_offset() {
|
||||
assert_eq!(format_stamp(0, 0), "1970-01-01 00:00");
|
||||
assert_eq!(format_stamp(1_000_000_000, 0), "2001-09-09 01:46");
|
||||
assert_eq!(format_stamp(951_782_400, 0), "2000-02-29 00:00"); // leap day
|
||||
assert_eq!(format_stamp(0, 3600), "1970-01-01 01:00"); // +1h server offset
|
||||
assert_eq!(parse_utc_offset("+0100"), Some(3600));
|
||||
assert_eq!(parse_utc_offset("-0500"), Some(-18000));
|
||||
assert_eq!(parse_utc_offset("+0000"), Some(0));
|
||||
assert_eq!(parse_utc_offset("nope"), None);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user