Main #6

Merged
sagifer merged 4 commits from main into prod 2026-11-17 17:45:41 +01:00
25 changed files with 1051 additions and 347 deletions
Showing only changes of commit 86d5dc5503 - Show all commits
+1 -1
View File
@@ -59,7 +59,7 @@ jobs:
# astro-engine and horoscope-api need the Swiss Ephemeris sources and # astro-engine and horoscope-api need the Swiss Ephemeris sources and
# data (scripts/fetch-deps.sh); their tests run locally. # data (scripts/fetch-deps.sh); their tests run locally.
- name: Test - 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: build:
needs: test needs: test
Generated
+9
View File
@@ -17,6 +17,13 @@ version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "analysis-prompt"
version = "0.1.0"
dependencies = [
"serde_json",
]
[[package]] [[package]]
name = "anyhow" name = "anyhow"
version = "1.0.104" version = "1.0.104"
@@ -156,6 +163,7 @@ dependencies = [
name = "backend" name = "backend"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"analysis-prompt",
"anyhow", "anyhow",
"argon2", "argon2",
"axum", "axum",
@@ -2856,6 +2864,7 @@ checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
name = "worker" name = "worker"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"analysis-prompt",
"anyhow", "anyhow",
"axum", "axum",
"db", "db",
+2
View File
@@ -7,6 +7,7 @@ members = [
"crates/service-kit", "crates/service-kit",
"crates/db", "crates/db",
"crates/horoscope-client", "crates/horoscope-client",
"crates/analysis-prompt",
"services/horoscope-api", "services/horoscope-api",
"services/backend", "services/backend",
"services/worker", "services/worker",
@@ -25,6 +26,7 @@ geo-tz = { path = "crates/geo-tz" }
service-kit = { path = "crates/service-kit" } service-kit = { path = "crates/service-kit" }
db = { path = "crates/db" } db = { path = "crates/db" }
horoscope-client = { path = "crates/horoscope-client" } horoscope-client = { path = "crates/horoscope-client" }
analysis-prompt = { path = "crates/analysis-prompt" }
anyhow = "1" anyhow = "1"
argon2 = { version = "0.5", features = ["std"] } argon2 = { version = "0.5", features = ["std"] }
+10
View File
@@ -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
+383
View File
@@ -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<Kind> {
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<id>`, 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<i64>) {
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<String> {
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");
}
}
@@ -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<id>"), 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);
+1
View File
@@ -8,6 +8,7 @@ publish.workspace = true
[dependencies] [dependencies]
db.workspace = true db.workspace = true
analysis-prompt.workspace = true
horoscope-client.workspace = true horoscope-client.workspace = true
service-kit.workspace = true service-kit.workspace = true
anyhow.workspace = true anyhow.workspace = true
+2
View File
@@ -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 | | `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 | | `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 | | `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<id>` |
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. 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.
+11 -3
View File
@@ -145,8 +145,14 @@ async fn queue(
Target::Summary { chart_id, hash } => ("summary", hash, Some(*chart_id), None), Target::Summary { chart_id, hash } => ("summary", hash, Some(*chart_id), None),
Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id)), Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id)),
}; };
let prompt_version = &state.config.prompt_version; // The cache key leaves out the admin-edited prompt revision, so a chart keeps
let cache_key = sha256_hex(&format!("{kind}|{hash}|{prompt_version}|{model}|{language}")); // 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. // Already requested for this chart/synastry: return it.
let existing: Option<AnalysisRow> = sqlx::query_as(&format!( let existing: Option<AnalysisRow> = 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. // The same chart elsewhere (another user, same birth data) was already analysed: copy it.
let cached: Option<(Value, Option<i32>, Option<i32>)> = sqlx::query_as( let cached: Option<(Value, Option<i32>, Option<i32>)> = 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(&cache_key)
.bind(prompt_version)
.fetch_optional(&state.db) .fetch_optional(&state.db)
.await?; .await?;
if let Some((content, input_tokens, output_tokens)) = cached { if let Some((content, input_tokens, output_tokens)) = cached {
+3
View File
@@ -11,6 +11,7 @@ mod analyses;
mod auth; mod auth;
mod charts; mod charts;
mod payments; mod payments;
mod prompts;
mod shares; mod shares;
mod synastries; mod synastries;
@@ -89,6 +90,8 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/admin/users", get(admin::list_users)) .route("/v1/admin/users", get(admin::list_users))
.route("/v1/admin/users/{id}", patch(admin::update_user)) .route("/v1/admin/users/{id}", patch(admin::update_user))
.route("/v1/admin/users/{id}/credits", post(admin::adjust_credits)) .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(cors(&state.config.cors_allowed_origins))
.layer( .layer(
TraceLayer::new_for_http() TraceLayer::new_for_http()
+138
View File
@@ -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<Option<i64>, 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<String>, OffsetDateTime, Option<String>);
async fn entry(db: &PgPool, kind: Kind, language: &str) -> Result<Value, sqlx::Error> {
let rows: Vec<RevisionRow> = 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<Value> = 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<Json<Value>> {
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<String>,
}
fn parse_target(state: &AppState, kind: &str, language: &str) -> Result<Kind, ApiError> {
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<Path<(String, String)>, ApiError>,
WithRejection(Json(req), _): Body<SavePrompt>,
) -> ApiResult<Json<Value>> {
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<String>,)> = 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 &current {
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?))
}
+67
View File
@@ -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; let r = app.call("PATCH", &format!("/v1/charts/{pid}"), Some(&admin), Some(corrected)).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body); 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<String> =
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);
}
+2
View File
@@ -1,6 +1,7 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import { notFound } from "next/navigation"; import { notFound } from "next/navigation";
import { AdminNav } from "@/components/AdminNav";
import { requireMe } from "@/lib/server"; import { requireMe } from "@/lib/server";
import { AdminUsers } from "./AdminUsers"; import { AdminUsers } from "./AdminUsers";
@@ -13,6 +14,7 @@ export default async function AdminPage() {
if (!me.user.roles.includes("admin")) notFound(); if (!me.user.roles.includes("admin")) notFound();
return ( return (
<main className="page" style={{ maxWidth: 1180 }}> <main className="page" style={{ maxWidth: 1180 }}>
<AdminNav current="/admin" />
<div className="page-head"> <div className="page-head">
<h1>Felhasználók</h1> <h1>Felhasználók</h1>
<p className="muted">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.</p> <p className="muted">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.</p>
@@ -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<string, string> = { hu: "Magyar", en: "Angol" };
export function AdminPrompts() {
const [prompts, setPrompts] = useState<AdminPrompt[] | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
api<{ prompts: AdminPrompt[] }>("/admin/prompts")
.then((d) => setPrompts(d.prompts))
.catch((e) => setError(errorText(e)));
}, []);
if (error) {
return (
<p className="msg msg-error" role="alert">
{error}
</p>
);
}
if (!prompts) return <p className="muted">Betöltés…</p>;
const replace = (next: AdminPrompt) =>
setPrompts((all) => all?.map((p) => (p.kind === next.kind && p.language === next.language ? next : p)) ?? null);
return (
<section className="card">
<Tabs
label="Elemzésfajták"
tabs={KINDS.map((k) => ({
id: k.id,
label: k.label,
content: (
<KindPrompts about={k.about} prompts={prompts.filter((p) => p.kind === k.kind)} onSaved={replace} />
),
}))}
/>
</section>
);
}
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 (
<div className="prompt-kind">
<div className="prompt-kind-head">
<p className="muted">{about}</p>
{prompts.length > 1 && (
<div className="field prompt-lang">
<label htmlFor={`lang-${prompt.kind}`}>Nyelv</label>
<select
id={`lang-${prompt.kind}`}
className="inp"
value={language}
onChange={(e) => setLanguage(e.target.value)}
>
{prompts.map((p) => (
<option key={p.language} value={p.language}>
{LANGUAGES[p.language] ?? p.language}
{p.custom ? " (szerkesztett)" : ""}
</option>
))}
</select>
</div>
)}
</div>
<PromptEditor key={`${prompt.kind}-${prompt.language}`} prompt={prompt} onSaved={onSaved} />
</div>
);
}
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<string | null>(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<AdminPrompt>(`/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 (
<div className="prompt-editor">
<div className="prompt-status">
{prompt.custom ? (
<span className="badge badge-gold">Szerkesztett</span>
) : (
<span className="badge">Alapértelmezett</span>
)}
{prompt.updated_at && (
<span className="hint">
Utoljára mentve: {formatDate(prompt.updated_at, true)}
{prompt.updated_by ? ` · ${prompt.updated_by}` : ""}
</span>
)}
</div>
<div className="field">
<label htmlFor={id}>Utasítások a modellnek (system prompt)</label>
<textarea
id={id}
className="inp prompt-text"
value={draft}
onChange={(e) => {
setDraft(e.target.value);
setSaved(false);
}}
spellCheck={false}
rows={24}
/>
<span className="hint">
{draft.length.toLocaleString("hu-HU")} karakter
{dirty ? " · mentetlen változás" : ""}
</span>
</div>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
{saved && !dirty && (
<p className="msg msg-ok" role="status">
Elmentve. Az ezután kért elemzések már ezzel készülnek.
</p>
)}
<div className="form-actions">
<button type="button" className="btn btn-primary" onClick={() => save(draft)} disabled={busy || !dirty}>
{busy ? "Mentés…" : "Mentés"}
</button>
<button type="button" className="btn" onClick={() => setDraft(prompt.system)} disabled={busy || !dirty}>
Változások elvetése
</button>
{(prompt.custom || draft.trim() !== prompt.default.trim()) && (
<button
type="button"
className="btn btn-ghost"
onClick={() => setDraft(prompt.default)}
disabled={busy || draft.trim() === prompt.default.trim()}
>
Alapértelmezett szöveg betöltése
</button>
)}
</div>
<details className="details">
<summary>Amit a modell ezen felül kap</summary>
<div className="prompt-extra">
<p className="hint">
Ezt a kód állítja össze, nem szerkeszthető. A <code>{"{chart data}"}</code> helyére a képlet pozíciói kerülnek
(név, dátum és hely nélkül). A válasz formáját (mezők, fejezetek) egy rögzített JSON-séma írja elő.
</p>
<pre className="prompt-pre">{prompt.user_template}</pre>
</div>
</details>
{prompt.history.length > 0 && (
<details className="details">
<summary>Korábbi változatok ({prompt.history.length})</summary>
<ul className="prompt-history">
{prompt.history.map((h, i) => (
<li key={h.id}>
<span>
{formatDate(h.created_at, true)}
{h.created_by ? ` · ${h.created_by}` : ""}
</span>
<span className="hint">
{i === 0 ? "érvényben · " : ""}
{h.custom ? `${(h.system ?? "").length.toLocaleString("hu-HU")} karakter` : "alapértelmezett"}
</span>
<button
type="button"
className="btn btn-sm"
onClick={() => setDraft(h.system ?? prompt.default)}
disabled={busy}
>
Betöltés
</button>
</li>
))}
</ul>
<p className="hint">A betöltött változat a szerkesztőbe kerül; a mentéssel lesz érvényes.</p>
</details>
)}
</div>
);
}
@@ -0,0 +1,27 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { AdminNav } from "@/components/AdminNav";
import { requireMe } from "@/lib/server";
import { AdminPrompts } from "./AdminPrompts";
export const metadata: Metadata = { title: "Promptok" };
export default async function AdminPromptsPage() {
const me = await requireMe("/admin/promptok");
if (!me.user.roles.includes("admin")) notFound();
return (
<main className="page" style={{ maxWidth: 1180 }}>
<AdminNav current="/admin/promptok" />
<div className="page-head">
<h1>Promptok</h1>
<p className="muted">
Az elemzéseket író modell utasításai. A változás az ezután kért elemzésekre hat; a már elkészültek
változatlanok maradnak.
</p>
</div>
<AdminPrompts />
</main>
);
}
+37
View File
@@ -404,3 +404,40 @@ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
.legal a { color: var(--gold); } .legal a { color: var(--gold); }
.legal-table td { vertical-align: top; line-height: 1.5; } .legal-table td { vertical-align: top; line-height: 1.5; }
.danger-box { display: flex; flex-direction: column; gap: 12px; padding: 16px; border: 1px solid var(--danger); border-radius: var(--radius); } .danger-box { display: flex; flex-direction: column; gap: 12px; padding: 16px; border: 1px solid var(--danger); border-radius: var(--radius); }
/* Admin */
.admin-nav { display: flex; gap: 4px; border-bottom: 1px solid var(--line); margin-bottom: 4px; overflow-x: auto; }
.admin-nav a {
padding: 10px 14px; min-height: 44px; display: inline-flex; align-items: center; color: var(--muted);
text-decoration: none; border-bottom: 2px solid transparent; margin-bottom: -1px; white-space: nowrap;
}
.admin-nav a:hover { color: var(--ink); }
.admin-nav a[aria-current="page"] { color: var(--gold); border-bottom-color: var(--gold); }
.prompt-kind { display: flex; flex-direction: column; gap: 20px; }
.prompt-kind-head { display: flex; gap: 16px 24px; align-items: flex-end; justify-content: space-between; flex-wrap: wrap; }
.prompt-kind-head > p { flex: 1 1 360px; margin: 0; }
.prompt-lang { width: 200px; }
.prompt-editor { display: flex; flex-direction: column; gap: 16px; }
.prompt-status { display: flex; gap: 8px 12px; align-items: center; flex-wrap: wrap; }
.prompt-text {
min-height: 420px; padding: 12px 14px; resize: vertical; line-height: 1.55;
font: 400 13.5px/1.55 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.prompt-extra { display: flex; flex-direction: column; gap: 10px; }
.prompt-pre {
margin: 0; padding: 12px 14px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel-2);
white-space: pre-wrap; overflow-wrap: anywhere; font: 400 13px/1.5 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
color: var(--ink-2);
}
.prompt-history { list-style: none; margin: 0 0 8px; padding: 0; display: flex; flex-direction: column; }
.prompt-history li {
display: grid; grid-template-columns: 1fr auto auto; gap: 12px; align-items: center;
padding: 8px 0; border-bottom: 1px solid var(--line);
}
@media (max-width: 640px) {
.prompt-text { min-height: 320px; font-size: 13px; }
.prompt-lang { width: 100%; }
.prompt-history li { grid-template-columns: 1fr auto; }
.prompt-history li .hint { grid-column: 1; }
.prompt-history li .btn { grid-column: 2; grid-row: 1 / span 2; }
}
@@ -0,0 +1,19 @@
import Link from "next/link";
const PAGES = [
{ href: "/admin", label: "Felhasználók" },
{ href: "/admin/promptok", label: "Promptok" },
];
/** Switches between the admin pages. */
export function AdminNav({ current }: { current: string }) {
return (
<nav className="admin-nav" aria-label="Admin oldalak">
{PAGES.map((p) => (
<Link key={p.href} href={p.href} aria-current={p.href === current ? "page" : undefined}>
{p.label}
</Link>
))}
</nav>
);
}
+26
View File
@@ -149,6 +149,32 @@ export interface AdminUser {
analyses_left: UnitBalance; analyses_left: UnitBalance;
} }
export type PromptKind = "summary" | "natal";
export interface PromptRevision {
id: number;
custom: boolean;
/** `null`: the built-in text was restored. */
system: string | null;
created_at: string;
created_by: string | null;
}
/** An editable analysis system prompt (admin). */
export interface AdminPrompt {
kind: PromptKind;
language: string;
/** The text in force. */
system: string;
custom: boolean;
updated_at: string | null;
updated_by: string | null;
default: string;
/** The fixed user message; `{chart data}` stands for the chart. */
user_template: string;
history: PromptRevision[];
}
export interface AnalysisContent { export interface AnalysisContent {
title?: string; title?: string;
summary?: string; summary?: string;
+1
View File
@@ -8,6 +8,7 @@ publish.workspace = true
[dependencies] [dependencies]
db.workspace = true db.workspace = true
analysis-prompt.workspace = true
service-kit.workspace = true service-kit.workspace = true
anyhow.workspace = true anyhow.workspace = true
axum.workspace = true axum.workspace = true
+1 -1
View File
@@ -20,7 +20,7 @@ Háttérmunkák a közös PostgreSQL-adatbázis fölött: e-mail-küldés, szöv
**Szöveges elemzések** (`analyses`, `pending` → `running` → `done`/`failed`) **Szöveges elemzések** (`analyses`, `pending` → `running` → `done`/`failed`)
- A backend létrehozza a `pending` sort, és levon egy elemzési egységet. Egy trigger (`NOTIFY analyses`) felébreszti a workert; egyszerre `ANALYSIS_CONCURRENCY` elemzés készül. - A backend létrehozza a `pending` sort, és levon egy elemzési egységet. Egy trigger (`NOTIFY analyses`) felébreszti a workert; egyszerre `ANALYSIS_CONCURRENCY` elemzés készül.
- A prompt a tárolt képletből készül (`src/analysis/compact.rs`). Ez egy tömör szöveg, amely csak a pozíciókat tartalmazza: jegyek, fokok, házak, fényszögek, elemek. **Név, születési dátum, idő, hely és koordináta nem megy ki.** Ismeretlen születési időnél nincsenek házak, Aszcendens és MC. - A prompt a tárolt képletből készül (`src/analysis/compact.rs`). Ez egy tömör szöveg, amely csak a pozíciókat tartalmazza: jegyek, fokok, házak, fényszögek, elemek. **Név, születési dátum, idő, hely és koordináta nem megy ki.** Ismeretlen születési időnél nincsenek házak, Aszcendens és MC.
- A modell OpenRouteren keresztül válaszol, azzal a modellel, amely a sor `model` mezőjében áll. A válasznak kötött JSON-sémát kell követnie (`src/analysis/prompt.rs`, `PROMPT_VERSION = v2`): - A modell OpenRouteren keresztül válaszol, azzal a modellel, amely a sor `model` mezőjében áll. A válasznak kötött JSON-sémát kell követnie (`crates/analysis-prompt`, `PROMPT_VERSION = v2`; ha a sor `prompt_version`-je `v2-r<id>`, a system prompt az admin által szerkesztett `prompt_revisions` sorból jön):
- `title`, `summary`; - `title`, `summary`;
- `sections`, radixnál: `personality`, `emotions`, `mind`, `love`, `work`, `growth`; szinasztriánál: `attraction`, `communication`, `emotional_bond`, `friction`, `long_term`; - `sections`, radixnál: `personality`, `emotions`, `mind`, `love`, `work`, `growth`; szinasztriánál: `attraction`, `communication`, `emotional_bond`, `friction`, `long_term`;
- `strengths`, `challenges`, `advice`; - `strengths`, `challenges`, `advice`;
+13 -2
View File
@@ -101,10 +101,21 @@ impl Analyzer {
compact::synastry(&chart1, &chart2, &result) compact::synastry(&chart1, &chart2, &result)
} }
}; };
if job.prompt_version != PROMPT_VERSION { let (base, revision) = prompt::split_version(&job.prompt_version);
if base != PROMPT_VERSION {
tracing::warn!(id = %job.id, requested = %job.prompt_version, current = PROMPT_VERSION, "prompt version differs"); tracing::warn!(id = %job.id, requested = %job.prompt_version, current = PROMPT_VERSION, "prompt version differs");
} }
Ok(prompt::build(kind, &job.language, &text)) // An admin-edited system prompt; NULL (or a missing row) means the built-in one.
let system: Option<String> = match revision {
Some(id) => sqlx::query_scalar("SELECT system FROM prompt_revisions WHERE id = $1")
.bind(id)
.fetch_optional(&self.db)
.await
.map_err(db_err)?
.flatten(),
None => None,
};
Ok(prompt::build(kind, &job.language, &text, system.as_deref()))
} }
/// Writes one claimed analysis and records the outcome. /// Writes one claimed analysis and records the outcome.
+7 -2
View File
@@ -55,8 +55,13 @@ impl Serialize for Ordered<'_> {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self.0 { match self.0 {
Value::Object(map) => { Value::Object(map) => {
let order: Vec<&str> = let order: Vec<&str> = map
map.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); .get("required")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.collect();
let mut out = serializer.serialize_map(Some(map.len()))?; let mut out = serializer.serialize_map(Some(map.len()))?;
for (key, value) in map { for (key, value) in map {
match (key.as_str(), value) { match (key.as_str(), value) {
+2 -337
View File
@@ -1,338 +1,3 @@
//! Prompts and output schemas of the analyses (prompt version [`PROMPT_VERSION`]). //! Prompts and answer schemas live in the shared `analysis-prompt` crate.
//!
//! The model answers with one JSON object (OpenRouter structured output);
//! [`validate`] checks it against the same schema before it is stored.
use serde_json::{Value, json}; pub use analysis_prompt::*;
/// 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 fn parse(s: &str) -> Option<Kind> {
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",
}
}
fn rules(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
}
pub fn build(kind: Kind, language: &str, chart_text: &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: rules(kind, language),
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<String> {
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");
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 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");
}
}
+1 -1
View File
@@ -83,7 +83,7 @@ pub async fn main(args: Vec<String>) -> anyhow::Result<()> {
prompt::Kind::Synastry => compact::synastry(&input["person1"], &input["person2"], &input), prompt::Kind::Synastry => compact::synastry(&input["person1"], &input["person2"], &input),
_ => compact::natal(&input), _ => compact::natal(&input),
}; };
let built = prompt::build(args.kind, &args.language, &data); let built = prompt::build(args.kind, &args.language, &data, None);
std::fs::create_dir_all(&args.out)?; std::fs::create_dir_all(&args.out)?;
std::fs::write( std::fs::write(
+29
View File
@@ -369,6 +369,35 @@ mod analyses {
} }
} }
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn uses_the_admin_edited_system_prompt(db: PgPool) {
let s = setup(&db).await;
let (revision,): (i64,) = sqlx::query_as(
"INSERT INTO prompt_revisions (kind, language, system) VALUES ('natal', 'hu', 'Saját szabályok.') RETURNING id",
)
.fetch_one(&db)
.await
.unwrap();
// a newer revision is not used: the analysis records the one it was requested with
sqlx::query("INSERT INTO prompt_revisions (kind, language, system) VALUES ('natal', 'hu', 'Újabb.')")
.execute(&db)
.await
.unwrap();
let id = request_analysis(&db, &s).await;
sqlx::query("UPDATE analyses SET prompt_version = $1 WHERE id = $2")
.bind(format!("v1-r{revision}"))
.bind(id)
.execute(&db)
.await
.unwrap();
let (fake, url) = fake_openrouter(vec![reply(&content(Kind::Natal))]).await;
assert!(run_once(&analyzer(&db, &url)).await);
assert_eq!(row(&db, id).await.0, "done");
let requests = fake.requests.lock().unwrap();
assert_eq!(requests[0]["messages"][0]["content"], "Saját szabályok.");
assert!(requests[0]["messages"][1]["content"].as_str().unwrap().contains("- personality: "));
}
#[sqlx::test(migrator = "db::MIGRATOR")] #[sqlx::test(migrator = "db::MIGRATOR")]
async fn retries_bad_answers_then_fails_and_refunds(db: PgPool) { async fn retries_bad_answers_then_fails_and_refunds(db: PgPool) {
let s = setup(&db).await; let s = setup(&db).await;