feat: Systemprompt-Ebenen: global, je Modell, Standard-Persona, ersetzen statt stapeln, Schema 20, Version 0.1.32 (#1248, #1249)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@ -88,6 +88,17 @@ pub async fn embeddings(
|
||||
.await
|
||||
}
|
||||
|
||||
/// Trägt die Anfrage schon eine Nachricht mit der Rolle `system`?
|
||||
pub(crate) fn hat_systemprompt(request: &Value) -> bool {
|
||||
request
|
||||
.get("messages")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|m| {
|
||||
m.iter()
|
||||
.any(|n| n.get("role").and_then(Value::as_str) == Some("system"))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn prepend_basis(request: &mut Value, basis: &str) -> Result<(), ApiError> {
|
||||
if !basis.is_empty() {
|
||||
let messages = request
|
||||
@ -257,13 +268,17 @@ async fn forward_to(
|
||||
));
|
||||
}
|
||||
if path == "/v1/chat/completions" {
|
||||
// Ebenen (→ #1248): Der Text des Modells ersetzt den globalen Standard. Beide stehen nur dann vor den
|
||||
// Nachrichten, wenn die Anfrage selbst keinen Systemprompt trägt: Eine Persona im Chat oder der eigene
|
||||
// Systemprompt eines API-Clients ersetzt die Ebenen darunter, sie werden nicht gestapelt.
|
||||
let basis = state
|
||||
.store()
|
||||
.model_systemprompt(&model)
|
||||
.wirksame_grundlage(&model)
|
||||
.map_err(|_| ApiError::internal())?
|
||||
.ok_or_else(|| ApiError::model_not_found(&model))?;
|
||||
// Grundlage steht immer vor Persona und vor Nachrichten des Clients; API-Personas gibt es nicht.
|
||||
prepend_basis(&mut request, &basis)?;
|
||||
if !hat_systemprompt(&request) {
|
||||
prepend_basis(&mut request, &basis)?;
|
||||
}
|
||||
}
|
||||
// Base-Modelle klonen eine gespeicherte Stimme: ohne `voice` gleich ablehnen, bevor das Modell lädt.
|
||||
if path == "/v1/audio/speech"
|
||||
|
||||
@ -165,6 +165,10 @@ pub fn routes() -> Router<Arc<AppState>> {
|
||||
"/ui/modelle/systemprompt",
|
||||
post(verwaltung::model_systemprompt),
|
||||
)
|
||||
.route(
|
||||
"/ui/systemprompt/global",
|
||||
post(verwaltung::global_systemprompt),
|
||||
)
|
||||
.route("/ui/personas", get(personas::page))
|
||||
.route("/ui/personas/speichern", post(personas::save))
|
||||
.route("/ui/personas.js", get(personas::script))
|
||||
@ -667,7 +671,11 @@ pub(crate) fn notice(query: Option<&str>) -> String {
|
||||
),
|
||||
"grundlage" => (
|
||||
true,
|
||||
"Die Modellgrundlage ist gespeichert und gilt ab der nächsten Chat-Anfrage.",
|
||||
"Der Systemprompt des Modells ist gespeichert und gilt ab der nächsten Chat-Anfrage.",
|
||||
),
|
||||
"systemprompt_global" => (
|
||||
true,
|
||||
"Der globale Systemprompt ist gespeichert und gilt ab der nächsten Chat-Anfrage.",
|
||||
),
|
||||
"planung" => (
|
||||
true,
|
||||
|
||||
@ -67,12 +67,15 @@ pub(super) async fn page(State(state): State<Arc<AppState>>, headers: HeaderMap)
|
||||
.iter()
|
||||
.map(|p| {
|
||||
format!(
|
||||
"<option value=\"{}\" data-version=\"{}\" data-stimme=\"{}\" data-zeichen=\"{}\">{}</option>",
|
||||
"<option value=\"{}\" data-version=\"{}\" data-stimme=\"{}\" data-zeichen=\"{}\"{}>{}{}</option>",
|
||||
p.id,
|
||||
p.version,
|
||||
esc(p.voice.as_deref().unwrap_or("")),
|
||||
p.systemprompt.chars().count() + p.style.chars().count(),
|
||||
esc(&p.name)
|
||||
// Der Standard des Benutzers ist vorgewählt (→ #1248); „aus“ schaltet jede Persona ab.
|
||||
if p.standard { " selected" } else { "" },
|
||||
esc(&p.name),
|
||||
if p.standard { " (Standard)" } else { "" }
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
@ -87,7 +90,7 @@ pub(super) async fn page(State(state): State<Arc<AppState>>, headers: HeaderMap)
|
||||
.and_then(|d| d.context);
|
||||
let basis = state
|
||||
.store()
|
||||
.model_systemprompt(name)
|
||||
.wirksame_grundlage(name)
|
||||
.ok()
|
||||
.flatten()
|
||||
.unwrap_or_default();
|
||||
@ -792,9 +795,10 @@ const CHAT_JS: &str = r#"(function () {
|
||||
function laengePruefen() {
|
||||
var m = kontexte.find(function (x) { return x[0] === modell.value; });
|
||||
var p = laengen.find(function (x) { return String(x[0]) === persona.value; });
|
||||
var tokens = m ? Math.ceil((m[2] + (p ? p[1] : 0)) / 3.5) : 0;
|
||||
// Eine Persona mit Text ersetzt den Systemprompt des Modells und den globalen; sonst zählt deren Text (#1248).
|
||||
var tokens = m ? Math.ceil((p && p[1] > 0 ? p[1] : m[2]) / 3.5) : 0;
|
||||
hinweis.textContent = m && m[1] && tokens > m[1] / 2 ?
|
||||
"Längenhinweis: Grundlage und Persona belegen geschätzt " + tokens + " Tokens (mehr als die Hälfte von " + m[1] + "). Grobe Schätzung, keine Sperre." : "";
|
||||
"Längenhinweis: Der wirksame Systemprompt belegt geschätzt " + tokens + " Tokens (mehr als die Hälfte von " + m[1] + "). Grobe Schätzung, keine Sperre." : "";
|
||||
}
|
||||
// Der volle technische Name steht als Tooltip an der Auswahl; angezeigt wird der lesbare Name.
|
||||
function modellTitel() { modell.title = modell.value; }
|
||||
@ -2094,16 +2098,20 @@ mod tests {
|
||||
style: "Stil".into(),
|
||||
voice: None,
|
||||
saved_voice: false,
|
||||
standard: false,
|
||||
};
|
||||
// Ohne Persona trägt die Anfrage keinen Systemprompt: Modell oder global kommen davor.
|
||||
assert!(!crate::chat::hat_systemprompt(&request));
|
||||
apply_persona(&mut request, &p);
|
||||
crate::chat::prepend_basis(&mut request, "Grundlage").unwrap();
|
||||
// Mit Persona schon: Sie ersetzt die Ebenen darunter, die Grundlage wird nicht vorangestellt (→ #1248).
|
||||
assert!(crate::chat::hat_systemprompt(&request));
|
||||
let texts: Vec<_> = request["messages"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|m| m["content"].as_str().unwrap())
|
||||
.collect();
|
||||
assert_eq!(texts, ["Grundlage", "Persona", "Stil", "Frage"]);
|
||||
assert_eq!(texts, ["Persona", "Stil", "Frage"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@ -11,13 +11,21 @@ use nexus_store::Persona;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Mehr als die Hälfte des Fensters: 3,5 Zeichen je Token (nur Schätzung).
|
||||
/// Geschätzte Tokens des wirksamen Systemprompts (→ #1248): Hat die Persona Text, ersetzt sie die Ebenen darunter
|
||||
/// und nur ihr Text zählt; sonst zählt der Text des Modells oder des globalen Standards. Ein Hinweis erst, wenn er
|
||||
/// mehr als die Hälfte des Kontextfensters belegt.
|
||||
pub(super) fn estimate(
|
||||
basis: &str,
|
||||
prompt: &str,
|
||||
style: &str,
|
||||
context: Option<u32>,
|
||||
) -> Option<u64> {
|
||||
let chars = basis.chars().count() + prompt.chars().count() + style.chars().count();
|
||||
let persona = prompt.chars().count() + style.chars().count();
|
||||
let chars = if persona > 0 {
|
||||
persona
|
||||
} else {
|
||||
basis.chars().count()
|
||||
};
|
||||
let tokens = (chars as u64 * 2).div_ceil(7);
|
||||
context
|
||||
.filter(|c| tokens > u64::from(*c) / 2)
|
||||
@ -39,6 +47,8 @@ fn fields(
|
||||
<label>Systemprompt <textarea name=\"systemprompt\" maxlength=\"32000\" rows=\"5\">{}</textarea></label>\
|
||||
<label>Stil-Text <textarea name=\"stil\" maxlength=\"16000\" rows=\"3\">{}</textarea></label>\
|
||||
<label>Stimme (optional; nur persönlich freigegebene Stimmen) <select name=\"stimme\"><option value=\"\">Keine</option>{}</select></label>\
|
||||
<label class=\"haken\"><input type=\"checkbox\" name=\"standard\" value=\"1\"{}> Als Standard verwenden (im Chat vorgewählt)</label>\
|
||||
<p class=\"klein\">Eine Persona <b>ersetzt</b> den Systemprompt des Modells und den globalen Standard; sie wird nicht darauf gesetzt. Ohne Text in dieser Persona gelten sie weiter.</p>\
|
||||
<p class=\"klein persona-hinweis\" role=\"status\">{}</p><button class=\"primary\" type=\"submit\">{}</button></form>",
|
||||
esc(csrf),
|
||||
p.map(|p| p.id.to_string()).unwrap_or_default(),
|
||||
@ -59,6 +69,11 @@ fn fields(
|
||||
esc(name)
|
||||
))
|
||||
.collect::<String>(),
|
||||
if p.is_some_and(|p| p.standard) {
|
||||
" checked"
|
||||
} else {
|
||||
""
|
||||
},
|
||||
esc(initial_hint),
|
||||
if p.is_some() {
|
||||
"Neue Version speichern"
|
||||
@ -103,7 +118,7 @@ pub(super) async fn page(
|
||||
m.name.clone(),
|
||||
d.context,
|
||||
store
|
||||
.model_systemprompt(&m.name)
|
||||
.wirksame_grundlage(&m.name)
|
||||
.ok()
|
||||
.flatten()
|
||||
.unwrap_or_default(),
|
||||
@ -134,10 +149,15 @@ pub(super) async fn page(
|
||||
"<section class=\"card\"><h2>Meine Personas</h2><p class=\"klein\">Nur du siehst diese Texte, auch Admins nicht. Jede Bearbeitung legt eine neue Version an.</p><ul>{}</ul></section>",
|
||||
list.iter()
|
||||
.map(|p| format!(
|
||||
"<li><a href=\"/ui/personas?id={}\">{}</a> · Version {}</li>",
|
||||
"<li><a href=\"/ui/personas?id={}\">{}</a> · Version {}{}</li>",
|
||||
p.id,
|
||||
esc(&p.name),
|
||||
p.version
|
||||
p.version,
|
||||
if p.standard {
|
||||
" · <b>Standard</b>"
|
||||
} else {
|
||||
""
|
||||
}
|
||||
))
|
||||
.collect::<String>()
|
||||
);
|
||||
@ -204,7 +224,16 @@ pub(super) async fn save(
|
||||
selected,
|
||||
);
|
||||
match result {
|
||||
Ok(Some(p)) => redirect(&format!("/ui/personas?id={}", p.id)),
|
||||
Ok(Some(p)) => {
|
||||
// Standard (→ #1248): Die Markierung hängt an der Persona; ein anderer Standard löst den alten ab.
|
||||
let will = field("standard") == "1";
|
||||
if will {
|
||||
let _ = state.store().set_persona_standard(&user.user, Some(p.id));
|
||||
} else if p.standard {
|
||||
let _ = state.store().set_persona_standard(&user.user, None);
|
||||
}
|
||||
redirect(&format!("/ui/personas?id={}", p.id))
|
||||
}
|
||||
Ok(None) => super::refused(StatusCode::NOT_FOUND, "Persona nicht gefunden."),
|
||||
Err(_) => super::refused(
|
||||
StatusCode::BAD_REQUEST,
|
||||
@ -229,9 +258,14 @@ pub(super) async fn script() -> Response {
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn hinweis_erst_ueber_der_haelfte() {
|
||||
assert_eq!(estimate("a", &"x".repeat(174), "", Some(100)), None);
|
||||
assert_eq!(estimate("a", &"x".repeat(175), "", Some(100)), Some(51));
|
||||
fn hinweis_erst_ueber_der_haelfte_und_nur_fuer_die_wirksame_ebene() {
|
||||
// Mit Persona-Text zählt nur er (er ersetzt den Text des Modells).
|
||||
assert_eq!(estimate("a", &"x".repeat(175), "", Some(100)), None);
|
||||
assert_eq!(estimate("a", &"x".repeat(176), "", Some(100)), Some(51));
|
||||
assert_eq!(estimate(&"y".repeat(5000), "b", "", Some(100)), None);
|
||||
assert_eq!(estimate("a", "b", "", None), None);
|
||||
// Ohne Persona-Text gilt der Text des Modells (oder der globale).
|
||||
assert_eq!(estimate(&"y".repeat(176), "", "", Some(100)), Some(51));
|
||||
assert_eq!(estimate(&"y".repeat(175), "", "", Some(100)), None);
|
||||
}
|
||||
}
|
||||
|
||||
@ -543,7 +543,7 @@ fn edit_dialog(state: &AppState, viewer: &Viewer, m: &ModelRow) -> String {
|
||||
String::new()
|
||||
} else {
|
||||
format!(
|
||||
"<form class=\"dlg-form\" method=\"post\" action=\"/ui/modelle/systemprompt\">{}<input type=\"hidden\" name=\"name\" value=\"{}\"><label class=\"feld\">Grundlage (Systemprompt)<textarea name=\"systemprompt\" rows=\"5\" maxlength=\"32000\">{}</textarea></label><button class=\"primary\" type=\"submit\">Grundlage speichern</button></form>",
|
||||
"<form class=\"dlg-form\" method=\"post\" action=\"/ui/modelle/systemprompt\">{}<input type=\"hidden\" name=\"name\" value=\"{}\"><label class=\"feld\">Systemprompt für dieses Modell<textarea name=\"systemprompt\" rows=\"5\" maxlength=\"32000\">{}</textarea><span class=\"hilfe\">Ersetzt den globalen Systemprompt für dieses Modell; leer: der globale gilt. Ein Benutzer-Standard oder eine Persona im Chat ersetzt ihn wiederum.</span></label><button class=\"primary\" type=\"submit\">Speichern</button></form>",
|
||||
csrf_field(viewer),
|
||||
esc(&m.name),
|
||||
esc(&m.systemprompt)
|
||||
@ -650,6 +650,22 @@ pub(super) async fn models_page(
|
||||
_ => format!("<section class=\"card\" data-refresh=\"/ui/teil/modelle\" data-interval=\"3000\">{}</section><p class=\"klein\">Das Denkstufen-Symbol erscheint in „Kann“, sobald der Test am Modell (Knopf mit Haken) „ja“ ergeben hat.</p>", models_table(&state, &viewer, "llm")),
|
||||
};
|
||||
let mut body = format!("{}{nav}{content}", notice(query.as_deref()));
|
||||
if viewer.admin() && art.is_empty() {
|
||||
// Globaler Systemprompt (→ #1248): Standard für alle Modelle ohne eigenen Text.
|
||||
let global = state.store().globaler_systemprompt().unwrap_or_default();
|
||||
body.push_str(&format!(
|
||||
"<section class=\"card\" id=\"systemprompt-global\"><h2>Systemprompt (global)</h2>\
|
||||
<p class=\"klein\">Gilt für jedes Chat-Modell ohne eigenen Text (Dialog „Bearbeiten“ des Modells). \
|
||||
Die speziellere Ebene <b>ersetzt</b> die allgemeinere: Ein Text des Modells ersetzt diesen, der Standard des Benutzers \
|
||||
oder eine gewählte Persona ersetzt beide, ein Systemprompt in der Anfrage eines API-Clients ersetzt sie ebenfalls. \
|
||||
Leer lassen, damit das Modell bleibt, wie es ist.</p>\
|
||||
<form method=\"post\" action=\"/ui/systemprompt/global\" class=\"formular\">{csrf}\
|
||||
<label>Systemprompt <textarea name=\"systemprompt\" rows=\"5\" maxlength=\"32000\">{text}</textarea></label>\
|
||||
<button class=\"primary\" type=\"submit\">Speichern</button></form></section>",
|
||||
csrf = csrf_field(&viewer),
|
||||
text = esc(&global),
|
||||
));
|
||||
}
|
||||
if viewer.admin() {
|
||||
for m in model_rows(&state) {
|
||||
body.push_str(&edit_dialog(&state, &viewer, &m));
|
||||
@ -1151,6 +1167,32 @@ pub(super) async fn model_systemprompt(
|
||||
}
|
||||
}
|
||||
|
||||
/// `POST /ui/systemprompt/global`: globalen Systemprompt setzen (nur Admin; das Audit nennt die Länge, nie den Text).
|
||||
pub(super) async fn global_systemprompt(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
let viewer = match admin(&state, &headers, &body) {
|
||||
Ok(v) => v,
|
||||
Err(r) => return *r,
|
||||
};
|
||||
let prompt = form_field(&body, "systemprompt").unwrap_or_default();
|
||||
if state.store().set_globaler_systemprompt(&prompt).is_err() {
|
||||
return super::refused(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Der Systemprompt ist ungültig (höchstens 32.000 Zeichen).",
|
||||
);
|
||||
}
|
||||
audit(
|
||||
&state,
|
||||
&viewer,
|
||||
"systemprompt.global",
|
||||
&format!("{} Zeichen", prompt.chars().count()),
|
||||
);
|
||||
back("/ui/modelle", "systemprompt_global")
|
||||
}
|
||||
|
||||
// --- Warteschlange -----------------------------------------------------------
|
||||
|
||||
fn queue_html(view: &SchedulerView) -> String {
|
||||
|
||||
Reference in New Issue
Block a user