Files
sorsfonalak/services/worker/src/analysis/prompt.rs
T

339 lines
15 KiB
Rust
Raw Normal View History

//! 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.
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 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");
}
}