Tag model-context turns with [SPEAKER: name - datetime] provenance; add global user-name setting (default User, read live), agent name = session title
This commit is contained in:
1 parent
0754262b37
commit
95c41c2c21
8 files changed
+157
-5
No files matched your search
@@ -1,6 +1,8 @@
|
|||||||
{
|
{
|
||||||
"identity.name": "Your name is {name}.",
|
"identity.name": "Your name is {name}.",
|
||||||
"identity.folder": " Your personal folder is {folder}.",
|
"identity.folder": " Your personal folder is {folder}.",
|
||||||
|
"speaker.tag": "[SPEAKER: {name} - {when}]",
|
||||||
|
"speaker.note": " User and agent turns are prefixed with a [SPEAKER: name - date and time UTC] tag identifying who generated them and when.",
|
||||||
"error.name_locked": "The session name is immutable after the first interaction.",
|
"error.name_locked": "The session name is immutable after the first interaction.",
|
||||||
"error.name_empty": "The name must not be empty.",
|
"error.name_empty": "The name must not be empty.",
|
||||||
"error.session_not_found": "Session not found.",
|
"error.session_not_found": "Session not found.",
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
{
|
{
|
||||||
"identity.name": "Il tuo nome è {name}.",
|
"identity.name": "Il tuo nome è {name}.",
|
||||||
"identity.folder": " La tua cartella personale è {folder}.",
|
"identity.folder": " La tua cartella personale è {folder}.",
|
||||||
|
"speaker.tag": "[SPEAKER: {name} - {when}]",
|
||||||
|
"speaker.note": " I turni dell'utente e dell'agente sono preceduti da un tag [SPEAKER: nome - data e ora UTC] che identifica chi li ha generati e quando.",
|
||||||
"error.name_locked": "Il nome della sessione è immutabile dopo la prima interazione.",
|
"error.name_locked": "Il nome della sessione è immutabile dopo la prima interazione.",
|
||||||
"error.name_empty": "Il nome non può essere vuoto.",
|
"error.name_empty": "Il nome non può essere vuoto.",
|
||||||
"error.session_not_found": "Sessione non trovata.",
|
"error.session_not_found": "Sessione non trovata.",
|
||||||
|
|||||||
+136
-5
@@ -242,6 +242,44 @@ fn text_message(role: Role, text: String) -> ChatMessage {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The `[SPEAKER: name - datetime]` line prefixed to a turn's content in the
|
||||||
|
/// model prompt (provenance), followed by a newline.
|
||||||
|
fn speaker_prefix(name: &str, secs: i64) -> String {
|
||||||
|
format!(
|
||||||
|
"{}\n",
|
||||||
|
t(
|
||||||
|
"speaker.tag",
|
||||||
|
&[("name", name), ("when", &format_utc(secs))]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Format unix seconds as a compact, unambiguous UTC datetime (no chrono dep).
|
||||||
|
fn format_utc(secs: i64) -> String {
|
||||||
|
let days = secs.div_euclid(86400);
|
||||||
|
let tod = secs.rem_euclid(86400);
|
||||||
|
let (y, m, d) = civil_from_days(days);
|
||||||
|
format!(
|
||||||
|
"{y:04}-{m:02}-{d:02} {:02}:{:02} UTC",
|
||||||
|
tod / 3600,
|
||||||
|
(tod % 3600) / 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)
|
||||||
|
}
|
||||||
|
|
||||||
/// Rebuild a stateless [`ChatRequest`] from the stored history plus the new turn.
|
/// Rebuild a stateless [`ChatRequest`] from the stored history plus the new turn.
|
||||||
/// Prior `reasoning_content` is deliberately NOT replayed into the prompt.
|
/// Prior `reasoning_content` is deliberately NOT replayed into the prompt.
|
||||||
fn build_request(
|
fn build_request(
|
||||||
@@ -250,6 +288,7 @@ fn build_request(
|
|||||||
body: &SessionChat,
|
body: &SessionChat,
|
||||||
extra: &str,
|
extra: &str,
|
||||||
images: &[serde_json::Value],
|
images: &[serde_json::Value],
|
||||||
|
user_name: &str,
|
||||||
) -> ChatRequest {
|
) -> ChatRequest {
|
||||||
let mut messages = Vec::new();
|
let mut messages = Vec::new();
|
||||||
// Structural identity reminder: always present, not an editable setting. It
|
// Structural identity reminder: always present, not an editable setting. It
|
||||||
@@ -258,12 +297,22 @@ fn build_request(
|
|||||||
if let Some(folder) = &sess.folder {
|
if let Some(folder) = &sess.folder {
|
||||||
identity.push_str(&t("identity.folder", &[("folder", folder)]));
|
identity.push_str(&t("identity.folder", &[("folder", folder)]));
|
||||||
}
|
}
|
||||||
|
identity.push_str(&t("speaker.note", &[]));
|
||||||
messages.push(text_message(Role::System, identity));
|
messages.push(text_message(Role::System, identity));
|
||||||
if let Some(sp) = &sess.settings.system_prompt {
|
if let Some(sp) = &sess.settings.system_prompt {
|
||||||
messages.push(text_message(Role::System, sp.clone()));
|
messages.push(text_message(Role::System, sp.clone()));
|
||||||
}
|
}
|
||||||
for m in history {
|
for m in history {
|
||||||
let mut msg = text_message(role_of(&m.role), m.content.clone());
|
// 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. This annotates the prompt only —
|
||||||
|
// stored content stays clean (the GUI shows its own timestamp).
|
||||||
|
let content = match m.role.as_str() {
|
||||||
|
"user" => format!("{}{}", speaker_prefix(user_name, m.created_at), m.content),
|
||||||
|
"assistant" => format!("{}{}", speaker_prefix(&sess.title, m.created_at), m.content),
|
||||||
|
_ => m.content.clone(),
|
||||||
|
};
|
||||||
|
let mut msg = text_message(role_of(&m.role), content);
|
||||||
msg.tool_calls = m
|
msg.tool_calls = m
|
||||||
.tool_calls_json
|
.tool_calls_json
|
||||||
.as_deref()
|
.as_deref()
|
||||||
@@ -273,7 +322,12 @@ fn build_request(
|
|||||||
// The user turn: typed text + attachment context (inline files / path
|
// The user turn: typed text + attachment context (inline files / path
|
||||||
// reminders / image markers). Images become multipart image_url parts that
|
// reminders / image markers). Images become multipart image_url parts that
|
||||||
// the Vision bridge materializes; without images it stays a plain string.
|
// the Vision bridge materializes; without images it stays a plain string.
|
||||||
let user_text = format!("{}{}", body.content, extra);
|
let user_text = format!(
|
||||||
|
"{}{}{}",
|
||||||
|
speaker_prefix(user_name, now_unix() as i64),
|
||||||
|
body.content,
|
||||||
|
extra
|
||||||
|
);
|
||||||
if images.is_empty() {
|
if images.is_empty() {
|
||||||
messages.push(text_message(Role::User, user_text));
|
messages.push(text_message(Role::User, user_text));
|
||||||
} else {
|
} else {
|
||||||
@@ -431,7 +485,18 @@ pub(crate) async fn session_chat(
|
|||||||
}
|
}
|
||||||
let extra = uploads::context_text(&metas);
|
let extra = uploads::context_text(&metas);
|
||||||
let images = uploads::image_parts(&metas);
|
let images = uploads::image_parts(&metas);
|
||||||
let mut req = build_request(&sess, &history, &body, &extra, &images);
|
// The human speaker name is global and read live (the same person across
|
||||||
|
// every chat), not the session's copy-on-create snapshot. Empty -> "User".
|
||||||
|
let defaults = match with_store(&st, |s| s.get_defaults()).await {
|
||||||
|
Ok(d) => d,
|
||||||
|
Err(e) => return e.into_response(),
|
||||||
|
};
|
||||||
|
let user_name = defaults
|
||||||
|
.and_then(|d| d.user_name)
|
||||||
|
.map(|n| n.trim().to_string())
|
||||||
|
.filter(|n| !n.is_empty())
|
||||||
|
.unwrap_or_else(|| "User".to_string());
|
||||||
|
let mut req = build_request(&sess, &history, &body, &extra, &images, &user_name);
|
||||||
|
|
||||||
// Persist the user turn (text + attachment context) before generating.
|
// Persist the user turn (text + attachment context) before generating.
|
||||||
let user_content = format!("{}{}", body.content, extra);
|
let user_content = format!("{}{}", body.content, extra);
|
||||||
@@ -687,12 +752,78 @@ mod tests {
|
|||||||
temperature: None,
|
temperature: None,
|
||||||
top_p: None,
|
top_p: None,
|
||||||
};
|
};
|
||||||
let req = build_request(&sess, &[], &body, "", &[]);
|
let req = build_request(&sess, &[], &body, "", &[], "Federico");
|
||||||
// Identity reminder first (name + folder), then the session SP, then user.
|
// Identity reminder first (name + folder), then the session SP, then user.
|
||||||
assert!(matches!(req.messages[0].role, Role::System));
|
assert!(matches!(req.messages[0].role, Role::System));
|
||||||
let t0 = req.messages[0].text().unwrap();
|
let t0 = req.messages[0].text().unwrap();
|
||||||
assert!(t0.contains("Pippo") && t0.contains("/tmp/pippo"));
|
assert!(t0.contains("Pippo") && t0.contains("/tmp/pippo"));
|
||||||
assert_eq!(req.messages[1].text().unwrap(), "sii breve");
|
assert_eq!(req.messages[1].text().unwrap(), "sii breve");
|
||||||
assert!(matches!(req.messages.last().unwrap().role, Role::User));
|
let last = req.messages.last().unwrap();
|
||||||
|
assert!(matches!(last.role, Role::User));
|
||||||
|
// The new user turn carries the human speaker tag.
|
||||||
|
assert!(last.text().unwrap().starts_with("[SPEAKER: Federico - "));
|
||||||
|
assert!(last.text().unwrap().ends_with("ciao"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn build_request_tags_history_with_speaker_and_time() {
|
||||||
|
let sess = Session {
|
||||||
|
id: "s".into(),
|
||||||
|
title: "Nebula".into(),
|
||||||
|
model: "m".into(),
|
||||||
|
settings: SessionSettings::default(),
|
||||||
|
name_locked: true,
|
||||||
|
folder: None,
|
||||||
|
created_at: 0,
|
||||||
|
updated_at: 0,
|
||||||
|
};
|
||||||
|
let history = vec![
|
||||||
|
StoredMessage {
|
||||||
|
id: 1,
|
||||||
|
role: "user".into(),
|
||||||
|
content: "domanda".into(),
|
||||||
|
reasoning_content: None,
|
||||||
|
tool_calls_json: None,
|
||||||
|
tool_call_id: None,
|
||||||
|
prompt_tokens: 0,
|
||||||
|
completion_tokens: 0,
|
||||||
|
created_at: 1_000_000_000,
|
||||||
|
},
|
||||||
|
StoredMessage {
|
||||||
|
id: 2,
|
||||||
|
role: "assistant".into(),
|
||||||
|
content: "risposta".into(),
|
||||||
|
reasoning_content: None,
|
||||||
|
tool_calls_json: None,
|
||||||
|
tool_call_id: None,
|
||||||
|
prompt_tokens: 0,
|
||||||
|
completion_tokens: 0,
|
||||||
|
created_at: 1_000_000_001,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
let body = SessionChat {
|
||||||
|
content: "ok".into(),
|
||||||
|
stream: false,
|
||||||
|
agent: false,
|
||||||
|
attachments: Vec::new(),
|
||||||
|
max_tokens: None,
|
||||||
|
temperature: None,
|
||||||
|
top_p: None,
|
||||||
|
};
|
||||||
|
let req = build_request(&sess, &history, &body, "", &[], "User");
|
||||||
|
// messages: [identity, user(history), assistant(history), user(new)]
|
||||||
|
let u = req.messages[1].text().unwrap();
|
||||||
|
assert!(u.starts_with("[SPEAKER: User - 2001-09-09 01:46 UTC]"));
|
||||||
|
assert!(u.ends_with("domanda"));
|
||||||
|
let a = req.messages[2].text().unwrap();
|
||||||
|
assert!(a.starts_with("[SPEAKER: Nebula - "));
|
||||||
|
assert!(a.ends_with("risposta"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn format_utc_known_dates() {
|
||||||
|
assert_eq!(format_utc(0), "1970-01-01 00:00 UTC");
|
||||||
|
assert_eq!(format_utc(1_000_000_000), "2001-09-09 01:46 UTC");
|
||||||
|
assert_eq!(format_utc(951_782_400), "2000-02-29 00:00 UTC"); // leap day
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -29,6 +29,12 @@ pub struct SessionSettings {
|
|||||||
/// Free-form user notes describing the purpose of this chat.
|
/// Free-form user notes describing the purpose of this chat.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub notes: Option<String>,
|
pub notes: Option<String>,
|
||||||
|
/// The human speaker's name, shown to the model in per-turn [SPEAKER: …]
|
||||||
|
/// tags. Global-authoritative: read live from the global defaults at turn
|
||||||
|
/// time (the per-session copy is inert), so it applies to every chat.
|
||||||
|
/// Absent/empty -> "User".
|
||||||
|
#[serde(default)]
|
||||||
|
pub user_name: Option<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub temperature: Option<f64>,
|
pub temperature: Option<f64>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -57,6 +63,7 @@ impl SessionSettings {
|
|||||||
SessionSettings {
|
SessionSettings {
|
||||||
system_prompt: self.system_prompt.clone().or(base.system_prompt.clone()),
|
system_prompt: self.system_prompt.clone().or(base.system_prompt.clone()),
|
||||||
notes: self.notes.clone().or(base.notes.clone()),
|
notes: self.notes.clone().or(base.notes.clone()),
|
||||||
|
user_name: self.user_name.clone().or(base.user_name.clone()),
|
||||||
temperature: self.temperature.or(base.temperature),
|
temperature: self.temperature.or(base.temperature),
|
||||||
top_p: self.top_p.or(base.top_p),
|
top_p: self.top_p.or(base.top_p),
|
||||||
top_k: self.top_k.or(base.top_k),
|
top_k: self.top_k.or(base.top_k),
|
||||||
|
|||||||
@@ -629,6 +629,8 @@ function fillSettingsForm(data, scope) {
|
|||||||
const isSession = scope === "session";
|
const isSession = scope === "session";
|
||||||
$("#set-name-field").hidden = !isSession;
|
$("#set-name-field").hidden = !isSession;
|
||||||
$("#set-name-hint").hidden = !isSession;
|
$("#set-name-hint").hidden = !isSession;
|
||||||
|
$("#set-username-field").hidden = isSession;
|
||||||
|
$("#set-username").value = data.user_name || "";
|
||||||
if (isSession) {
|
if (isSession) {
|
||||||
const sess = currentSession();
|
const sess = currentSession();
|
||||||
$("#set-name").value = sess ? sess.title : "";
|
$("#set-name").value = sess ? sess.title : "";
|
||||||
@@ -654,6 +656,7 @@ function readSettingsForm() {
|
|||||||
const num = (v) => (v === "" ? null : Number(v));
|
const num = (v) => (v === "" ? null : Number(v));
|
||||||
const txt = (v) => (v.trim() === "" ? null : v);
|
const txt = (v) => (v.trim() === "" ? null : v);
|
||||||
return {
|
return {
|
||||||
|
user_name: txt($("#set-username").value),
|
||||||
notes: txt($("#set-notes").value),
|
notes: txt($("#set-notes").value),
|
||||||
system_prompt: txt($("#set-sp").value),
|
system_prompt: txt($("#set-sp").value),
|
||||||
temperature: num($("#set-temp").value),
|
temperature: num($("#set-temp").value),
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
"settings.title.general": "General settings",
|
"settings.title.general": "General settings",
|
||||||
"settings.scope.session": "Session",
|
"settings.scope.session": "Session",
|
||||||
"settings.scope.general": "General",
|
"settings.scope.general": "General",
|
||||||
|
"settings.username": "User name",
|
||||||
|
"settings.username.ph": "User",
|
||||||
"settings.name": "Name",
|
"settings.name": "Name",
|
||||||
"settings.notes": "Notes (chat purpose)",
|
"settings.notes": "Notes (chat purpose)",
|
||||||
"settings.sp": "System Prompt",
|
"settings.sp": "System Prompt",
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
"settings.title.general": "Impostazioni generali",
|
"settings.title.general": "Impostazioni generali",
|
||||||
"settings.scope.session": "Sessione",
|
"settings.scope.session": "Sessione",
|
||||||
"settings.scope.general": "Generali",
|
"settings.scope.general": "Generali",
|
||||||
|
"settings.username": "Nome utente",
|
||||||
|
"settings.username.ph": "User",
|
||||||
"settings.name": "Nome",
|
"settings.name": "Nome",
|
||||||
"settings.notes": "Note (scopo della chat)",
|
"settings.notes": "Note (scopo della chat)",
|
||||||
"settings.sp": "System Prompt",
|
"settings.sp": "System Prompt",
|
||||||
|
|||||||
@@ -81,6 +81,9 @@
|
|||||||
<button id="set-scope-general" class="btn ghost" data-i18n="settings.scope.general">Generali</button>
|
<button id="set-scope-general" class="btn ghost" data-i18n="settings.scope.general">Generali</button>
|
||||||
</div>
|
</div>
|
||||||
<p id="set-hint" class="muted"></p>
|
<p id="set-hint" class="muted"></p>
|
||||||
|
<label class="field" id="set-username-field"><span data-i18n="settings.username">Nome utente</span>
|
||||||
|
<input id="set-username" type="text" autocomplete="off" data-i18n-ph="settings.username.ph" />
|
||||||
|
</label>
|
||||||
<label class="field" id="set-name-field"><span data-i18n="settings.name">Nome</span>
|
<label class="field" id="set-name-field"><span data-i18n="settings.name">Nome</span>
|
||||||
<input id="set-name" type="text" autocomplete="off" />
|
<input id="set-name" type="text" autocomplete="off" />
|
||||||
</label>
|
</label>
|
||||||
|
|||||||
Reference in new issue
Block a user