feat: private Personas und Modellgrundlage ergänzen
This commit is contained in:
237
crates/nexus-api/src/ui/personas.rs
Normal file
237
crates/nexus-api/src/ui/personas.rs
Normal file
@ -0,0 +1,237 @@
|
||||
//! Private Persona-Bibliothek und grobe Kontext-Schätzung, ohne Prompt-Inhalte im Audit.
|
||||
use super::{esc, form_field, guard, html, layout, redirect, viewer};
|
||||
use crate::state::AppState;
|
||||
use axum::{
|
||||
body::Bytes,
|
||||
extract::{RawQuery, State},
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::Response,
|
||||
};
|
||||
use nexus_store::Persona;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Mehr als die Hälfte des Fensters: 3,5 Zeichen je Token (nur Schätzung).
|
||||
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 tokens = (chars as u64 * 2).div_ceil(7);
|
||||
context
|
||||
.filter(|c| tokens > u64::from(*c) / 2)
|
||||
.map(|_| tokens)
|
||||
}
|
||||
|
||||
fn fields(
|
||||
p: Option<&Persona>,
|
||||
csrf: &str,
|
||||
models: &str,
|
||||
voices: &[(String, bool)],
|
||||
initial_hint: &str,
|
||||
) -> String {
|
||||
let get = |f: fn(&Persona) -> &str| p.map(f).unwrap_or("");
|
||||
format!(
|
||||
"<form method=\"post\" action=\"/ui/personas/speichern\" class=\"formular persona-form\" data-modelle=\"{models}\">\
|
||||
<input type=\"hidden\" name=\"csrf\" value=\"{}\"><input type=\"hidden\" name=\"id\" value=\"{}\">\
|
||||
<label>Name <input name=\"name\" maxlength=\"100\" required value=\"{}\"></label>\
|
||||
<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>\
|
||||
<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(),
|
||||
esc(get(|p| &p.name)),
|
||||
esc(get(|p| &p.systemprompt)),
|
||||
esc(get(|p| &p.style)),
|
||||
voices
|
||||
.iter()
|
||||
.map(|(name, saved)| format!(
|
||||
"<option value=\"{}:{}\"{}>{}</option>",
|
||||
if *saved { 1 } else { 0 },
|
||||
esc(name),
|
||||
if p.is_some_and(|p| p.voice.as_deref() == Some(name) && p.saved_voice == *saved) {
|
||||
" selected"
|
||||
} else {
|
||||
""
|
||||
},
|
||||
esc(name)
|
||||
))
|
||||
.collect::<String>(),
|
||||
esc(initial_hint),
|
||||
if p.is_some() {
|
||||
"Neue Version speichern"
|
||||
} else {
|
||||
"Anlegen"
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) async fn page(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
RawQuery(query): RawQuery,
|
||||
) -> Response {
|
||||
let Some(user) = viewer(&state, &headers) else {
|
||||
return redirect("/ui/login");
|
||||
};
|
||||
let id = query
|
||||
.as_deref()
|
||||
.and_then(|q| form_field(q.as_bytes(), "id"))
|
||||
.and_then(|v| v.parse::<i64>().ok());
|
||||
let store = state.store();
|
||||
let list = store.personas(&user.user).unwrap_or_default();
|
||||
let selected = id.and_then(|id| store.persona(&user.user, id, None).ok().flatten());
|
||||
let versions = selected
|
||||
.as_ref()
|
||||
.map(|p| store.persona_versions(&user.user, p.id).unwrap_or_default())
|
||||
.unwrap_or_default();
|
||||
let models: Vec<_> = store
|
||||
.list_models(true)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|m| m.kind == "llm" && user.key.rights.allows(&m.name))
|
||||
.filter_map(|m| {
|
||||
store
|
||||
.model_details(&m.name)
|
||||
.ok()
|
||||
.flatten()
|
||||
.filter(|d| d.engine != "tts")
|
||||
.map(|d| {
|
||||
(
|
||||
m.name.clone(),
|
||||
d.context,
|
||||
store
|
||||
.model_systemprompt(&m.name)
|
||||
.ok()
|
||||
.flatten()
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
// JSON in einem HTML-Attribut wird escaped, nicht als Skript ausgeführt.
|
||||
let model_data = esc(&serde_json::to_string(&models).unwrap_or_default());
|
||||
let initial_hint = selected
|
||||
.as_ref()
|
||||
.and_then(|p| {
|
||||
models.first().and_then(|(_, context, basis)| {
|
||||
estimate(basis, &p.systemprompt, &p.style, *context)
|
||||
})
|
||||
})
|
||||
.map(|tokens| {
|
||||
format!(
|
||||
"Längenhinweis: geschätzt {tokens} Tokens, mehr als die Hälfte des Kontextfensters."
|
||||
)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let options: String = models
|
||||
.iter()
|
||||
.map(|(name, _, _)| format!("<option value=\"{}\">{}</option>", esc(name), esc(name)))
|
||||
.collect();
|
||||
let mut body = format!(
|
||||
"<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>",
|
||||
p.id,
|
||||
esc(&p.name),
|
||||
p.version
|
||||
))
|
||||
.collect::<String>()
|
||||
);
|
||||
body.push_str(&format!("<section class=\"card\"><h2>{}</h2><label>Modell für Längenhinweis <select id=\"persona-modell\">{options}</select></label>{}</section>",
|
||||
if selected.is_some() {"Bearbeiten"} else {"Neue Persona"}, fields(selected.as_ref(), &user.csrf, &model_data, &store.approved_voices(&user.user).unwrap_or_default(), &initial_hint)));
|
||||
if let Some(p) = selected {
|
||||
body.push_str(&format!("<section class=\"card\"><h2>Versionen von {}</h2><p class=\"klein\">Ältere Versionen bleiben lesbar und unverändert.</p>", esc(&p.name)));
|
||||
for v in versions {
|
||||
body.push_str(&format!("<details><summary>Version {} · {}</summary><dl class=\"daten\"><dt>Systemprompt</dt><dd class=\"pfad\">{}</dd><dt>Stil-Text</dt><dd class=\"pfad\">{}</dd><dt>Stimme</dt><dd>{}</dd></dl></details>",
|
||||
v.version, esc(&v.name), esc(&v.systemprompt), esc(&v.style), esc(v.voice.as_deref().unwrap_or("Keine"))));
|
||||
}
|
||||
body.push_str("</section>");
|
||||
}
|
||||
body.push_str("<script src=\"/ui/personas.js\"></script>");
|
||||
html(
|
||||
StatusCode::OK,
|
||||
layout("Personas", "/ui/personas", &user, &body),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) async fn save(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
let user = match guard(
|
||||
&state,
|
||||
&headers,
|
||||
form_field(&body, "csrf").as_deref(),
|
||||
false,
|
||||
) {
|
||||
Ok(u) => u,
|
||||
Err(e) => return *e,
|
||||
};
|
||||
let field = |name| form_field(&body, name).unwrap_or_default();
|
||||
let id_text = field("id");
|
||||
let id = if id_text.is_empty() {
|
||||
None
|
||||
} else {
|
||||
match id_text.parse::<i64>() {
|
||||
Ok(i) => Some(i),
|
||||
Err(_) => return super::refused(StatusCode::BAD_REQUEST, "Ungültige Persona."),
|
||||
}
|
||||
};
|
||||
let voice = field("stimme");
|
||||
let selected = if voice.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let Some((saved, name)) = voice.split_once(':') else {
|
||||
return super::refused(StatusCode::BAD_REQUEST, "Ungültige Stimme.");
|
||||
};
|
||||
match saved {
|
||||
"0" => Some((name, false)),
|
||||
"1" => Some((name, true)),
|
||||
_ => return super::refused(StatusCode::BAD_REQUEST, "Ungültige Stimme."),
|
||||
}
|
||||
};
|
||||
let result = state.store().save_persona(
|
||||
&user.user,
|
||||
id,
|
||||
&field("name"),
|
||||
&field("systemprompt"),
|
||||
&field("stil"),
|
||||
selected,
|
||||
);
|
||||
match result {
|
||||
Ok(Some(p)) => redirect(&format!("/ui/personas?id={}", p.id)),
|
||||
Ok(None) => super::refused(StatusCode::NOT_FOUND, "Persona nicht gefunden."),
|
||||
Err(_) => super::refused(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"Persona ungültig oder Stimme nicht freigegeben.",
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn script() -> Response {
|
||||
super::secure(Response::builder())
|
||||
.header(
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
"text/javascript; charset=utf-8",
|
||||
)
|
||||
.body(axum::body::Body::from(include_str!(
|
||||
"../../assets/personas.js"
|
||||
)))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
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));
|
||||
assert_eq!(estimate("a", "b", "", None), None);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user