diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 9c976db..40da6f7 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -59,7 +59,7 @@ jobs: # astro-engine and horoscope-api need the Swiss Ephemeris sources and # data (scripts/fetch-deps.sh); their tests run locally. - name: Test - run: cargo test --locked -p backend -p worker -p db -p horoscope-client -p service-kit + run: cargo test --locked -p backend -p worker -p db -p horoscope-client -p service-kit -p analysis-prompt build: needs: test diff --git a/Cargo.lock b/Cargo.lock index db51107..b25cdf5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -17,6 +17,13 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" +[[package]] +name = "analysis-prompt" +version = "0.1.0" +dependencies = [ + "serde_json", +] + [[package]] name = "anyhow" version = "1.0.104" @@ -156,6 +163,7 @@ dependencies = [ name = "backend" version = "0.1.0" dependencies = [ + "analysis-prompt", "anyhow", "argon2", "axum", @@ -2856,6 +2864,7 @@ checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" name = "worker" version = "0.1.0" dependencies = [ + "analysis-prompt", "anyhow", "axum", "db", diff --git a/Cargo.toml b/Cargo.toml index eca0d9f..3d53720 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ members = [ "crates/service-kit", "crates/db", "crates/horoscope-client", + "crates/analysis-prompt", "services/horoscope-api", "services/backend", "services/worker", @@ -25,6 +26,7 @@ geo-tz = { path = "crates/geo-tz" } service-kit = { path = "crates/service-kit" } db = { path = "crates/db" } horoscope-client = { path = "crates/horoscope-client" } +analysis-prompt = { path = "crates/analysis-prompt" } anyhow = "1" argon2 = { version = "0.5", features = ["std"] } diff --git a/crates/analysis-prompt/Cargo.toml b/crates/analysis-prompt/Cargo.toml new file mode 100644 index 0000000..8126c3f --- /dev/null +++ b/crates/analysis-prompt/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "analysis-prompt" +description = "Prompts and answer schemas of the Sorsfonalak LLM analyses (shared by backend and worker)" +edition.workspace = true +version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +serde_json.workspace = true diff --git a/crates/analysis-prompt/src/lib.rs b/crates/analysis-prompt/src/lib.rs new file mode 100644 index 0000000..4cbc483 --- /dev/null +++ b/crates/analysis-prompt/src/lib.rs @@ -0,0 +1,383 @@ +//! Prompts and output schemas of the analyses (prompt version [`PROMPT_VERSION`]). +//! +//! The model answers with one JSON object (OpenRouter structured output); +//! [`validate`] checks it against the same schema before it is stored. +//! +//! The system prompt ([`default_system`]) can be replaced by an admin-edited +//! text; the user message (chart data, section list) and the schema stay fixed. + +use serde_json::{Value, json}; + +/// Matches the backend's `ANALYSIS_PROMPT_VERSION` (part of the cache key). +pub const PROMPT_VERSION: &str = "v2"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Kind { + Natal, + Synastry, + /// A free teaser of a natal chart: a title and a few sentences. + Summary, +} + +impl Kind { + pub const ALL: [Kind; 3] = [Kind::Summary, Kind::Natal, Kind::Synastry]; + + pub fn as_str(self) -> &'static str { + match self { + Kind::Natal => "natal", + Kind::Synastry => "synastry", + Kind::Summary => "summary", + } + } + + pub fn parse(s: &str) -> Option { + match s { + "natal" => Some(Kind::Natal), + "synastry" => Some(Kind::Synastry), + "summary" => Some(Kind::Summary), + _ => None, + } + } +} + +pub struct Prompt { + pub system: String, + pub user: String, + pub schema_name: &'static str, + pub schema: Value, +} + +/// (key, what the section covers) in reading order. +const NATAL_SECTIONS: [(&str, &str); 6] = [ + ("personality", "Core identity: the Sun, Moon, Ascendant and chart ruler read together"), + ("emotions", "Emotional needs, security and inner life (Moon, 4th house, water emphasis)"), + ("mind", "Thinking, communication and learning (Mercury, 3rd and 9th houses)"), + ("love", "Love, attraction and relationships (Venus, Mars, 5th and 7th houses, Descendant)"), + ("work", "Calling, career, money and daily work (MC, 10th, 2nd and 6th houses, Saturn, Jupiter)"), + ( + "growth", + "Main inner tensions, life lessons and the path of growth (tight squares and oppositions, Saturn, Chiron, Nodes)", + ), +]; + +const SYNASTRY_SECTIONS: [(&str, &str); 5] = [ + ("attraction", "What draws them together: Sun, Moon, Venus, Mars and Ascendant contacts"), + ("communication", "How they think and talk together (Mercury contacts, air emphasis, 3rd house overlays)"), + ("emotional_bond", "Emotional closeness, safety and care (Moon contacts, 4th and 8th house overlays)"), + ("friction", "Where they rub against each other and how to handle it (challenging aspects, Saturn, Pluto, Mars)"), + ("long_term", "Long-term potential and shared purpose, including the composite chart"), +]; + +fn sections(kind: Kind) -> &'static [(&'static str, &'static str)] { + match kind { + Kind::Natal => &NATAL_SECTIONS, + Kind::Synastry => &SYNASTRY_SECTIONS, + Kind::Summary => &[], + } +} + +/// The JSON schema of the answer (strict mode: every property required). +pub fn schema(kind: Kind) -> Value { + if kind == Kind::Summary { + return json!({ + "type": "object", + "additionalProperties": false, + "required": ["title", "summary"], + "properties": { + "title": {"type": "string", "description": "Short, evocative title for this chart (at most 6 words)"}, + "summary": {"type": "string", "description": "3-4 sentences, 60-100 words, one paragraph"} + } + }); + } + let mut props = serde_json::Map::new(); + for (key, about) in sections(kind) { + props.insert( + (*key).into(), + json!({ + "type": "object", + "description": about, + "additionalProperties": false, + "required": ["title", "body"], + "properties": { + "title": {"type": "string", "description": "Short, specific section title (not just the topic name)"}, + "body": {"type": "string", "description": "2-4 paragraphs separated by a blank line"} + } + }), + ); + } + let keys: Vec<&str> = sections(kind).iter().map(|(k, _)| *k).collect(); + json!({ + "type": "object", + "additionalProperties": false, + "required": ["title", "summary", "sections", "strengths", "challenges", "advice"], + "properties": { + "title": {"type": "string", "description": "Short, evocative title for this analysis (at most 8 words)"}, + "summary": {"type": "string", "description": "3-4 sentence overview"}, + "sections": {"type": "object", "additionalProperties": false, "required": keys, "properties": props}, + "strengths": {"type": "array", "items": {"type": "string"}, "description": "3-5 key strengths, one sentence each"}, + "challenges": {"type": "array", "items": {"type": "string"}, "description": "3-5 key challenges, one sentence each"}, + "advice": {"type": "string", "description": "A closing, encouraging paragraph with concrete guidance"} + } + }) +} + +const HUNGARIAN_STYLE: &str = "\ +Write natural, idiomatic Hungarian, as a native Hungarian author would; it must not read like a translation from English. \ +Use correct Hungarian suffixes and vowel harmony, Hungarian quotation marks („…”) and the en dash (–). \ +Use the usual Hungarian astrological terms: +- signs: Kos, Bika, Ikrek, Rák, Oroszlán, Szűz, Mérleg, Skorpió, Nyilas, Bak, Vízöntő, Halak (\"a Nap a Rák jegyében\", \"Kos Aszcendens\"); +- planets and points: Nap, Hold, Merkúr, Vénusz, Mars, Jupiter, Szaturnusz, Uránusz, Neptunusz, Plútó, Chiron (Kiron), \ +Észak-Holdcsomópont, Dél-Holdcsomópont, Lilith (Fekete Hold), Aszcendens, Descendens, Medium Coeli (MC), Imum Coeli (IC), Szerencsepont; +- aspects: együttállás (konjunkció), szextil, kvadrát (négyzet), trigon, szembenállás (oppozíció); +- elements and modalities: tűz, föld, levegő, víz (\"tűz elem\", \"a föld hiánya\"); kardinális, fix, változó; +Never leave English words (e.g. fire, earth, air, water) in the Hungarian text. +- other: \"a 3. házban\", \"a horoszkóp uralkodója\", retrográd, uralom (domicilium), száműzetés, exaltáció, esés, nappali/éjszakai horoszkóp."; + +fn language_name(language: &str) -> &'static str { + match language { + "hu" => "Hungarian", + _ => "English", + } +} + +/// The built-in system prompt of an analysis kind in a language. +pub fn default_system(kind: Kind, language: &str) -> String { + let (role, reader) = match kind { + Kind::Natal => ( + "a personal natal chart interpretation", + "Speak to the owner of the chart directly, in the informal second person singular (in Hungarian: tegező forma, \"te\").", + ), + Kind::Summary => ( + "a short free summary of a natal chart (a teaser shown before the detailed, paid analysis)", + "Speak to the owner of the chart directly, in the informal second person singular (in Hungarian: tegező forma, \"te\").", + ), + Kind::Synastry => ( + "a relationship (synastry) interpretation for two people", + "Write for both people at once, in the informal second person plural (in Hungarian: \"ti\", \"kettőtök\"). \ + When you must tell them apart, call them Person 1 and Person 2 (in Hungarian: \"az első fél\" and \"a második fél\"). \ + Do not assume their genders or the type of relationship.", + ), + }; + let mut text = format!( + "You are an experienced, warm and psychologically minded astrologer. You write {role} for the Sorsfonalak app. + +Write in {lang}. + +Rules: +- Base every statement on the chart data given. Never invent positions, aspects or houses that are not listed. +- When you interpret a placement, name its astrological basis in a short clause, but keep the focus on the person, not on jargon. +- Synthesize: weave signs, houses, aspects and rulers into one coherent portrait; show how tensions can be integrated. \ +Give the most weight to the Sun, Moon, Ascendant, chart ruler, tight aspects (orb under 3°) and strong emphases or gaps in elements and modalities. +- If a birth time is unknown, do not mention houses, the Ascendant or the Midheaven for that chart, and be careful with the Moon's sign. +- {reader} +- Tone: warm, honest, empowering and concrete. Not fatalistic: no predictions of illness, death, accidents or specific events, \ +and no medical, legal or financial advice. +- Avoid generic horoscope clichés and filler: every paragraph must say something specific to this chart. +- Texts are plain paragraphs separated by a blank line, without headings or lists inside; **bold** may be used sparingly. +- {length} +- Answer with a single JSON object that matches the given schema, and nothing else.", + lang = language_name(language), + length = match kind { + Kind::Summary => "Length: one paragraph of 3-4 sentences (60-100 words). Pick the Sun, Moon and Ascendant \ + (if the birth time is known) and the single most striking feature of the chart (a very tight aspect, \ + a stellium, a strong element emphasis or gap). It must be complete in itself and specific to this chart: \ + no sales talk, and do not mention a longer analysis.", + _ => "Length: each section 2-4 paragraphs (about 150-250 words); the whole analysis about 1300-1800 words.", + }, + ); + if language == "hu" { + text.push_str("\n\n"); + text.push_str(HUNGARIAN_STYLE); + } + text +} + +/// Splits a stored prompt version (`v2` or `v2-r`, the id of an admin-edited +/// system prompt in `prompt_revisions`) into the code version and the revision id. +pub fn split_version(version: &str) -> (&str, Option) { + match version.rsplit_once("-r") { + Some((base, id)) => match id.parse() { + Ok(id) => (base, Some(id)), + Err(_) => (version, None), + }, + None => (version, None), + } +} + +/// The built-in text of the user message around the chart data, for showing +/// next to the editable system prompt (`{chart data}` stands for the data). +pub fn user_template(kind: Kind) -> String { + build(kind, "hu", "{chart data}\n", None).user +} + +/// The prompt for one analysis; `system` replaces [`default_system`]. +pub fn build(kind: Kind, language: &str, chart_text: &str, system: Option<&str>) -> Prompt { + let mut user = String::from("Chart data:\n\n"); + user.push_str(chart_text); + if kind == Kind::Summary { + user.push_str("\nWrite the short summary now."); + } else { + user.push_str("\nSections to write, in this order:\n"); + for (key, about) in sections(kind) { + user.push_str(&format!("- {key}: {about}\n")); + } + user.push_str("\nWrite the analysis now."); + } + Prompt { + system: system.map_or_else(|| default_system(kind, language), str::to_owned), + user, + schema_name: match kind { + Kind::Natal => "natal_analysis", + Kind::Synastry => "synastry_analysis", + Kind::Summary => "chart_summary", + }, + schema: schema(kind), + } +} + +/// Checks an answer against our schema subset (objects with required +/// properties, strings with at least three letters, string arrays with at +/// least two items). A placeholder such as "x" counts as missing. +pub fn validate(schema: &Value, value: &Value) -> Result<(), String> { + fn walk(schema: &Value, value: &Value, path: &str) -> Result<(), String> { + match schema["type"].as_str() { + Some("object") => { + let obj = value.as_object().ok_or_else(|| format!("{path}: expected an object"))?; + for key in schema["required"].as_array().into_iter().flatten().filter_map(Value::as_str) { + let child = obj.get(key).ok_or_else(|| format!("{path}.{key}: missing"))?; + walk(&schema["properties"][key], child, &format!("{path}.{key}"))?; + } + Ok(()) + } + Some("array") => { + let items = value.as_array().ok_or_else(|| format!("{path}: expected an array"))?; + if items.len() < 2 { + return Err(format!("{path}: too few items")); + } + items.iter().enumerate().try_for_each(|(i, v)| walk(&schema["items"], v, &format!("{path}[{i}]"))) + } + Some("string") => match value.as_str() { + Some(s) if s.chars().filter(|c| c.is_alphabetic()).nth(2).is_some() => Ok(()), + _ => Err(format!("{path}: expected a non-empty string")), + }, + _ => Ok(()), + } + } + walk(schema, value, "$") +} + +/// Fixes typography the models often get wrong. In Hungarian, pairs of +/// straight double quotes become „…” (only when they pair up evenly). +pub fn polish(language: &str, content: &mut Value) { + fn hungarian_quotes(text: &str) -> Option { + if !text.contains('"') || !text.matches('"').count().is_multiple_of(2) { + return None; + } + let mut open = true; + Some( + text.chars() + .map(|c| match c { + '"' => { + let q = if open { '„' } else { '”' }; + open = !open; + q + } + c => c, + }) + .collect(), + ) + } + match content { + Value::String(s) if language == "hu" => { + if let Some(fixed) = hungarian_quotes(s) { + *s = fixed; + } + } + Value::Array(items) => items.iter_mut().for_each(|v| polish(language, v)), + Value::Object(map) => map.values_mut().for_each(|v| polish(language, v)), + _ => {} + } +} + +/// The analysis as Markdown (for reading and comparing outputs). +pub fn to_markdown(kind: Kind, language: &str, content: &Value) -> String { + let (strengths, challenges, advice) = if language == "hu" { + ("Erősségek", "Kihívások", "Útravaló") + } else { + ("Strengths", "Challenges", "Advice") + }; + let mut md = + format!("# {}\n\n_{}_\n\n", content["title"].as_str().unwrap_or(""), content["summary"].as_str().unwrap_or("")); + if kind == Kind::Summary { + return md; + } + for (key, _) in sections(kind) { + let s = &content["sections"][*key]; + md.push_str(&format!("## {}\n\n{}\n\n", s["title"].as_str().unwrap_or(key), s["body"].as_str().unwrap_or(""))); + } + for (title, key) in [(strengths, "strengths"), (challenges, "challenges")] { + md.push_str(&format!("## {title}\n\n")); + for item in content[key].as_array().into_iter().flatten().filter_map(Value::as_str) { + md.push_str(&format!("- {item}\n")); + } + md.push('\n'); + } + md.push_str(&format!("## {advice}\n\n{}\n", content["advice"].as_str().unwrap_or(""))); + md +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn summary_prompt_is_short() { + let p = build(Kind::Summary, "hu", "SUN: Cancer", None); + assert_eq!(p.schema_name, "chart_summary"); + assert!(p.system.contains("3-4 sentences") && p.system.contains("tegező")); + assert!(!p.user.contains("Sections to write")); + assert_eq!(validate(&p.schema, &json!({"title": "Érzékeny mag", "summary": "Rövid szöveg."})), Ok(())); + assert!(validate(&p.schema, &json!({"title": "Érzékeny mag"})).is_err()); + let md = to_markdown(Kind::Summary, "hu", &json!({"title": "Cím", "summary": "Szöveg."})); + assert_eq!(md, "# Cím\n\n_Szöveg._\n\n"); + } + + #[test] + fn custom_system_replaces_only_the_rules() { + let p = build(Kind::Natal, "hu", "SUN: Cancer", Some("Saját szabályok.")); + assert_eq!(p.system, "Saját szabályok."); + assert!(p.user.contains("SUN: Cancer") && p.user.contains("- personality:")); + assert_eq!(p.schema, schema(Kind::Natal)); + assert!(user_template(Kind::Natal).contains("{chart data}")); + assert_eq!(split_version("v2-r12"), ("v2", Some(12))); + assert_eq!(split_version("v2"), ("v2", None)); + assert!(Kind::ALL.iter().all(|k| Kind::parse(k.as_str()) == Some(*k))); + } + + #[test] + fn validate_rejects_placeholder_titles() { + let schema = schema(Kind::Synastry); + let section = json!({"title": "Rák-szívek", "body": "Két bekezdés szöveg."}); + let mut answer = json!({ + "title": "Két Rák-szív", "summary": "Összefoglaló.", "advice": "Útravaló.", + "strengths": ["Egyik erősség.", "Másik erősség."], "challenges": ["Egy kihívás.", "Még egy."], + "sections": {"attraction": section, "communication": section, "emotional_bond": section, + "friction": section, "long_term": section}, + }); + assert_eq!(validate(&schema, &answer), Ok(())); + answer["sections"]["attraction"]["title"] = json!("x"); + assert_eq!(validate(&schema, &answer), Err("$.sections.attraction.title: expected a non-empty string".into())); + } + + #[test] + fn polish_turns_straight_quotes_hungarian() { + let mut v = json!({"a": "a \"hazai pálya\" és a \"sorok\"", "b": ["egy \" pár nélkül"], "c": {"d": "nincs"}}); + polish("hu", &mut v); + assert_eq!(v["a"], "a „hazai pálya” és a „sorok”"); + assert_eq!(v["b"][0], "egy \" pár nélkül"); + assert_eq!(v["c"]["d"], "nincs"); + let mut en = json!({"a": "the \"home\" ground"}); + polish("en", &mut en); + assert_eq!(en["a"], "the \"home\" ground"); + } +} diff --git a/crates/db/migrations/0009_prompt_revisions.sql b/crates/db/migrations/0009_prompt_revisions.sql new file mode 100644 index 0000000..d0505fe --- /dev/null +++ b/crates/db/migrations/0009_prompt_revisions.sql @@ -0,0 +1,14 @@ +-- Admin-edited system prompts of the analyses. The newest row of a +-- (kind, language) is in force; system NULL means the built-in default. +-- An analysis records the revision it was written with in prompt_version +-- ("v2-r"), so the worker uses exactly that text. +CREATE TABLE prompt_revisions ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + kind text NOT NULL CHECK (kind IN ('summary', 'natal', 'synastry')), + language text NOT NULL, + system text CHECK (system IS NULL OR length(system) BETWEEN 1 AND 50000), + created_by uuid REFERENCES users ON DELETE SET NULL, + created_at timestamptz NOT NULL DEFAULT now() +); + +CREATE INDEX prompt_revisions_current ON prompt_revisions (kind, language, id DESC); diff --git a/services/backend/Cargo.toml b/services/backend/Cargo.toml index c568fa3..4ba6e9f 100644 --- a/services/backend/Cargo.toml +++ b/services/backend/Cargo.toml @@ -8,6 +8,7 @@ publish.workspace = true [dependencies] db.workspace = true +analysis-prompt.workspace = true horoscope-client.workspace = true service-kit.workspace = true anyhow.workspace = true diff --git a/services/backend/README.md b/services/backend/README.md index 30b7363..85e9c60 100644 --- a/services/backend/README.md +++ b/services/backend/README.md @@ -77,6 +77,8 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh | `GET /v1/admin/users?q=` | admin | felhasználók kereséssel, szerepekkel, megmaradt elemzésekkel | | `PATCH /v1/admin/users/{id}` | admin | `{roles: [...]}`; a saját admin szerep nem vehető el | | `POST /v1/admin/users/{id}/credits` | admin | `{unit: natal\|synastry, delta, note?}`: elemzések jóváírása vagy levonása | +| `GET /v1/admin/prompts` | admin | a tömör és a részletes elemzés system promptja nyelvenként: érvényes szöveg, alapértelmezett, változatok | +| `PUT /v1/admin/prompts/{kind}/{language}` | admin | `{system}` új változatként menti (`null` vagy az alapértelmezett szöveg: vissza a beépítettre); az új elemzések `prompt_version`-je `v2-r` | Hibák formátuma: `{"error": {"code", "message"}}`. A születési adatok hibái (például ismeretlen hely, javaslatokkal együtt) változatlanul jönnek tovább a horoscope-api-ból. diff --git a/services/backend/src/routes/analyses.rs b/services/backend/src/routes/analyses.rs index f5d1417..47bc027 100644 --- a/services/backend/src/routes/analyses.rs +++ b/services/backend/src/routes/analyses.rs @@ -145,8 +145,14 @@ async fn queue( Target::Summary { chart_id, hash } => ("summary", hash, Some(*chart_id), None), Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id)), }; - let prompt_version = &state.config.prompt_version; - let cache_key = sha256_hex(&format!("{kind}|{hash}|{prompt_version}|{model}|{language}")); + // The cache key leaves out the admin-edited prompt revision, so a chart keeps + // its analysis when the prompt changes; copying from another chart needs the same revision. + let base_version = &state.config.prompt_version; + let cache_key = sha256_hex(&format!("{kind}|{hash}|{base_version}|{model}|{language}")); + let prompt_version = &match super::prompts::current_revision(&state.db, kind, language).await? { + Some(id) => format!("{base_version}-r{id}"), + None => base_version.clone(), + }; // Already requested for this chart/synastry: return it. let existing: Option = sqlx::query_as(&format!( @@ -172,9 +178,11 @@ async fn queue( // The same chart elsewhere (another user, same birth data) was already analysed: copy it. let cached: Option<(Value, Option, Option)> = sqlx::query_as( - "SELECT content, input_tokens, output_tokens FROM analyses WHERE cache_key = $1 AND status = 'done' LIMIT 1", + "SELECT content, input_tokens, output_tokens FROM analyses \ + WHERE cache_key = $1 AND prompt_version = $2 AND status = 'done' LIMIT 1", ) .bind(&cache_key) + .bind(prompt_version) .fetch_optional(&state.db) .await?; if let Some((content, input_tokens, output_tokens)) = cached { diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index 382c8d9..e005967 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -11,6 +11,7 @@ mod analyses; mod auth; mod charts; mod payments; +mod prompts; mod shares; mod synastries; @@ -89,6 +90,8 @@ pub fn router(state: Arc) -> Router { .route("/v1/admin/users", get(admin::list_users)) .route("/v1/admin/users/{id}", patch(admin::update_user)) .route("/v1/admin/users/{id}/credits", post(admin::adjust_credits)) + .route("/v1/admin/prompts", get(prompts::list)) + .route("/v1/admin/prompts/{kind}/{language}", axum::routing::put(prompts::save)) .layer(cors(&state.config.cors_allowed_origins)) .layer( TraceLayer::new_for_http() diff --git a/services/backend/src/routes/prompts.rs b/services/backend/src/routes/prompts.rs new file mode 100644 index 0000000..d62759e --- /dev/null +++ b/services/backend/src/routes/prompts.rs @@ -0,0 +1,138 @@ +//! Editable system prompts of the analyses (admin only). +//! +//! Every save adds a row to `prompt_revisions`; the newest row of a +//! (kind, language) is in force, `system` NULL meaning the built-in text. +//! New analyses record the revision in `prompt_version`, so analyses that +//! are already written or queued keep the text they were started with. + +use analysis_prompt::{Kind, default_system, user_template}; +use axum::Json; +use axum::extract::{Path, State}; +use axum_extra::extract::WithRejection; +use serde::Deserialize; +use serde_json::{Value, json}; +use sqlx::PgPool; +use time::OffsetDateTime; + +use super::{Body, St}; +use crate::AppState; +use crate::auth::AdminUser; +use crate::error::{ApiError, ApiResult}; +use crate::views::rfc3339; + +/// The kinds whose prompt the admin page edits. +const EDITABLE: [Kind; 2] = [Kind::Summary, Kind::Natal]; +const MAX_CHARS: usize = 50_000; +const HISTORY: i64 = 20; + +/// The revision id of an admin-edited prompt in force, `None` for the built-in one. +pub async fn current_revision(db: &PgPool, kind: &str, language: &str) -> Result, sqlx::Error> { + let row: Option<(i64, bool)> = sqlx::query_as( + "SELECT id, system IS NOT NULL FROM prompt_revisions WHERE kind = $1 AND language = $2 ORDER BY id DESC LIMIT 1", + ) + .bind(kind) + .bind(language) + .fetch_optional(db) + .await?; + Ok(row.filter(|(_, custom)| *custom).map(|(id, _)| id)) +} + +type RevisionRow = (i64, Option, OffsetDateTime, Option); + +async fn entry(db: &PgPool, kind: Kind, language: &str) -> Result { + let rows: Vec = sqlx::query_as( + "SELECT r.id, r.system, r.created_at, u.email FROM prompt_revisions r \ + LEFT JOIN users u ON u.id = r.created_by \ + WHERE r.kind = $1 AND r.language = $2 ORDER BY r.id DESC LIMIT $3", + ) + .bind(kind.as_str()) + .bind(language) + .bind(HISTORY) + .fetch_all(db) + .await?; + let default = default_system(kind, language); + let current = rows.first(); + let history: Vec = rows + .iter() + .map(|(id, system, at, by)| { + json!({"id": id, "custom": system.is_some(), "system": system, "created_at": rfc3339(*at), "created_by": by}) + }) + .collect(); + Ok(json!({ + "kind": kind.as_str(), + "language": language, + "system": current.and_then(|r| r.1.clone()).unwrap_or_else(|| default.clone()), + "custom": current.is_some_and(|r| r.1.is_some()), + "updated_at": current.map(|r| rfc3339(r.2)), + "updated_by": current.and_then(|r| r.3.clone()), + "default": default, + "user_template": user_template(kind), + "history": history, + })) +} + +pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult> { + let mut prompts = Vec::new(); + for kind in EDITABLE { + for language in &state.config.supported_locales { + prompts.push(entry(&state.db, kind, language).await?); + } + } + Ok(Json(json!({ "prompts": prompts }))) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SavePrompt { + /// The new system prompt; `null` restores the built-in one. + system: Option, +} + +fn parse_target(state: &AppState, kind: &str, language: &str) -> Result { + let kind = Kind::parse(kind).filter(|k| EDITABLE.contains(k)).ok_or(ApiError::NotFound("prompt"))?; + if !state.config.supported_locales.iter().any(|l| l == language) { + return Err(ApiError::NotFound("prompt")); + } + Ok(kind) +} + +pub async fn save( + State(state): St, + AdminUser(admin): AdminUser, + WithRejection(Path((kind, language)), _): WithRejection, ApiError>, + WithRejection(Json(req), _): Body, +) -> ApiResult> { + let kind = parse_target(&state, &kind, &language)?; + let default = default_system(kind, &language); + // The built-in text is stored as NULL, so later code changes reach it. + let system = match req.system.map(|s| s.trim().replace("\r\n", "\n")) { + Some(s) if s.is_empty() => return Err(ApiError::BadRequest("the prompt must not be empty".into())), + Some(s) if s.chars().count() > MAX_CHARS => { + return Err(ApiError::BadRequest(format!("the prompt is longer than {MAX_CHARS} characters"))); + } + Some(s) if s == default.trim() => None, + other => other, + }; + let current: Option<(Option,)> = sqlx::query_as( + "SELECT system FROM prompt_revisions WHERE kind = $1 AND language = $2 ORDER BY id DESC LIMIT 1", + ) + .bind(kind.as_str()) + .bind(&language) + .fetch_optional(&state.db) + .await?; + let unchanged = match ¤t { + Some((text,)) => *text == system, + None => system.is_none(), + }; + if !unchanged { + sqlx::query("INSERT INTO prompt_revisions (kind, language, system, created_by) VALUES ($1, $2, $3, $4)") + .bind(kind.as_str()) + .bind(&language) + .bind(&system) + .bind(admin.id()) + .execute(&state.db) + .await?; + tracing::info!(admin = %admin.id(), kind = kind.as_str(), %language, custom = system.is_some(), "prompt changed"); + } + Ok(Json(entry(&state.db, kind, &language).await?)) +} diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index f985a86..82feebd 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -827,3 +827,70 @@ async fn persons_use_package_slots(pool: PgPool) { let r = app.call("PATCH", &format!("/v1/charts/{pid}"), Some(&admin), Some(corrected)).await; assert_eq!(r.status, StatusCode::OK, "{}", r.body); } + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn admins_edit_analysis_prompts(pool: PgPool) { + let app = TestApp::new(pool.clone()).await; + let admin = app.register("admin@example.com", "Admin").await; + let anna = app.register("anna@example.com", "Anna").await; + assert_eq!(app.get("/v1/admin/prompts", Some(&anna)).await.status, StatusCode::FORBIDDEN); + + let r = app.get("/v1/admin/prompts", Some(&admin)).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + let prompts = r.body["prompts"].as_array().unwrap(); + let keys: Vec = + prompts.iter().map(|p| format!("{}/{}", p["kind"], p["language"]).replace('"', "")).collect(); + assert_eq!(keys, ["summary/hu", "summary/en", "natal/hu", "natal/en"]); + let natal = &prompts[2]; + assert_eq!((&natal["custom"], &natal["system"]), (&json!(false), &natal["default"])); + assert!(natal["user_template"].as_str().unwrap().contains("{chart data}")); + let default = natal["default"].as_str().unwrap().to_string(); + + let put = |body: Value, uri: &'static str| app.call("PUT", uri, Some(&admin), Some(body)); + assert_eq!(put(json!({"system": " "}), "/v1/admin/prompts/natal/hu").await.status, StatusCode::BAD_REQUEST); + assert_eq!(put(json!({"system": "x"}), "/v1/admin/prompts/synastry/hu").await.status, StatusCode::NOT_FOUND); + assert_eq!(put(json!({"system": "x"}), "/v1/admin/prompts/natal/de").await.status, StatusCode::NOT_FOUND); + // saving the built-in text keeps the built-in prompt + let r = put(json!({"system": default}), "/v1/admin/prompts/natal/hu").await; + assert_eq!( + (r.status, &r.body["custom"], r.body["history"].as_array().unwrap().len()), + (StatusCode::OK, &json!(false), 0) + ); + + // an analysis written with the built-in prompt + let chart = app.chart(&anna, "Saját", true, "1990-03-15").await; + let uri = format!("/v1/charts/{}/analyses", chart["id"].as_str().unwrap()); + grant_units(&app, &anna, "natal", 1).await; + let r = app.call("POST", &uri, Some(&anna), None).await; + assert_eq!((r.status, r.body["prompt_version"].as_str()), (StatusCode::ACCEPTED, Some("v1"))); + let first = r.body["id"].as_str().unwrap().to_string(); + sqlx::query("UPDATE analyses SET status = 'done', content = '{}', completed_at = now() WHERE id = $1::uuid") + .bind(&first) + .execute(&pool) + .await + .unwrap(); + + let r = put(json!({"system": "Saját szabályok.\r\n"}), "/v1/admin/prompts/natal/hu").await; + assert_eq!( + (&r.body["custom"], r.body["system"].as_str(), r.body["updated_by"].as_str()), + (&json!(true), Some("Saját szabályok."), Some("admin@example.com")) + ); + let revision = r.body["history"][0]["id"].as_i64().unwrap(); + let r = put(json!({"system": "Saját szabályok."}), "/v1/admin/prompts/natal/hu").await; + assert_eq!(r.body["history"].as_array().unwrap().len(), 1); // unchanged: no new revision + + // the chart keeps its analysis; the same birth data elsewhere is written anew with the edited prompt + let r = app.call("POST", &uri, Some(&anna), None).await; + assert_eq!((r.status, r.body["id"].as_str()), (StatusCode::OK, Some(first.as_str()))); + let bela = app.register("bela@example.com", "Béla").await; + let same = app.chart(&bela, "Saját", true, "1990-03-15").await; + grant_units(&app, &bela, "natal", 1).await; + let r = app.call("POST", &format!("/v1/charts/{}/analyses", same["id"].as_str().unwrap()), Some(&bela), None).await; + let expected = format!("v1-r{revision}"); + assert_eq!((r.status, r.body["prompt_version"].as_str()), (StatusCode::ACCEPTED, Some(expected.as_str()))); + + // back to the built-in prompt + let r = put(json!({"system": null}), "/v1/admin/prompts/natal/hu").await; + assert_eq!((&r.body["custom"], r.body["system"].as_str()), (&json!(false), Some(default.as_str()))); + assert_eq!(r.body["history"].as_array().unwrap().len(), 2); +} diff --git a/services/frontend/src/app/admin/page.tsx b/services/frontend/src/app/admin/page.tsx index 9f65c2e..0be844b 100644 --- a/services/frontend/src/app/admin/page.tsx +++ b/services/frontend/src/app/admin/page.tsx @@ -1,6 +1,7 @@ import type { Metadata } from "next"; import { notFound } from "next/navigation"; +import { AdminNav } from "@/components/AdminNav"; import { requireMe } from "@/lib/server"; import { AdminUsers } from "./AdminUsers"; @@ -13,6 +14,7 @@ export default async function AdminPage() { if (!me.user.roles.includes("admin")) notFound(); return (
+

Felhasználók

Szerepkörök kezelése és részletes elemzések jóváírása (ajándék, reklamáció). A vásárlások is ide könyvelődnek majd.

diff --git a/services/frontend/src/app/admin/promptok/AdminPrompts.tsx b/services/frontend/src/app/admin/promptok/AdminPrompts.tsx new file mode 100644 index 0000000..e0e589e --- /dev/null +++ b/services/frontend/src/app/admin/promptok/AdminPrompts.tsx @@ -0,0 +1,245 @@ +"use client"; + +import { useEffect, useState } from "react"; + +import { Tabs } from "@/components/Tabs"; +import { api, errorText } from "@/lib/api"; +import { formatDate } from "@/lib/astro"; +import type { AdminPrompt, PromptKind } from "@/lib/types"; + +const KINDS: { kind: PromptKind; id: string; label: string; about: string }[] = [ + { + kind: "summary", + id: "osszefoglalo", + label: "Tömör összefoglaló", + about: "Ingyenes, a képlet oldalán a „Röviden” blokk: egy cím és 3–4 mondat. Minden új képlethez magától elkészül.", + }, + { + kind: "natal", + id: "reszletes", + label: "Részletes elemzés", + about: "Fizetős, hat fejezet, erősségek, kihívások és útravaló. Kérésre készül.", + }, +]; + +const LANGUAGES: Record = { hu: "Magyar", en: "Angol" }; + +export function AdminPrompts() { + const [prompts, setPrompts] = useState(null); + const [error, setError] = useState(null); + + useEffect(() => { + api<{ prompts: AdminPrompt[] }>("/admin/prompts") + .then((d) => setPrompts(d.prompts)) + .catch((e) => setError(errorText(e))); + }, []); + + if (error) { + return ( +

+ {error} +

+ ); + } + if (!prompts) return

Betöltés…

; + + const replace = (next: AdminPrompt) => + setPrompts((all) => all?.map((p) => (p.kind === next.kind && p.language === next.language ? next : p)) ?? null); + + return ( +
+ ({ + id: k.id, + label: k.label, + content: ( + p.kind === k.kind)} onSaved={replace} /> + ), + }))} + /> +
+ ); +} + +function KindPrompts({ + about, + prompts, + onSaved, +}: { + about: string; + prompts: AdminPrompt[]; + onSaved: (p: AdminPrompt) => void; +}) { + const [language, setLanguage] = useState(prompts[0]?.language ?? "hu"); + const prompt = prompts.find((p) => p.language === language) ?? prompts[0]; + if (!prompt) return null; + return ( +
+
+

{about}

+ {prompts.length > 1 && ( +
+ + +
+ )} +
+ +
+ ); +} + +function PromptEditor({ prompt, onSaved }: { prompt: AdminPrompt; onSaved: (p: AdminPrompt) => void }) { + const [draft, setDraft] = useState(prompt.system); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [saved, setSaved] = useState(false); + const dirty = draft.trim() !== prompt.system.trim(); + const id = `prompt-${prompt.kind}-${prompt.language}`; + + useEffect(() => { + if (!dirty) return; + const warn = (e: BeforeUnloadEvent) => e.preventDefault(); + window.addEventListener("beforeunload", warn); + return () => window.removeEventListener("beforeunload", warn); + }, [dirty]); + + async function save(system: string | null) { + setBusy(true); + setError(null); + setSaved(false); + try { + const next = await api(`/admin/prompts/${prompt.kind}/${prompt.language}`, { + method: "PUT", + body: { system }, + }); + onSaved(next); + setDraft(next.system); + setSaved(true); + } catch (e) { + setError(errorText(e)); + } finally { + setBusy(false); + } + } + + return ( +
+
+ {prompt.custom ? ( + Szerkesztett + ) : ( + Alapértelmezett + )} + {prompt.updated_at && ( + + Utoljára mentve: {formatDate(prompt.updated_at, true)} + {prompt.updated_by ? ` · ${prompt.updated_by}` : ""} + + )} +
+ +
+ +