Files
sorsfonalak/crates/analysis-prompt/src/lib.rs
T

475 lines
22 KiB
Rust
Raw Normal View History

2026-11-17 14:25:08 +00:00
//! 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 = "v3";
2026-11-17 14:25:08 +00:00
#[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,
/// One year of a natal chart: solar return, transits, progressions, profection, eclipses.
Forecast,
2026-11-17 14:25:08 +00:00
}
impl Kind {
pub const ALL: [Kind; 4] = [Kind::Summary, Kind::Natal, Kind::Synastry, Kind::Forecast];
2026-11-17 14:25:08 +00:00
pub fn as_str(self) -> &'static str {
match self {
Kind::Natal => "natal",
Kind::Synastry => "synastry",
Kind::Summary => "summary",
Kind::Forecast => "forecast",
2026-11-17 14:25:08 +00:00
}
}
pub fn parse(s: &str) -> Option<Kind> {
match s {
"natal" => Some(Kind::Natal),
"synastry" => Some(Kind::Synastry),
"summary" => Some(Kind::Summary),
"forecast" => Some(Kind::Forecast),
2026-11-17 14:25:08 +00:00
_ => 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"),
];
const FORECAST_SECTIONS: [(&str, &str); 5] = [
(
"theme",
"The main theme of the year: the solar return chart (its Ascendant, the houses of the Sun and the Moon, \
angular planets, tight aspects), the profected house and the lord of the year",
),
(
"love",
"Love, relationships, family and friendships during the year (Venus, the Moon, the 4th, 5th, 7th and 11th \
houses, and the transits and eclipses touching them)",
),
(
"work",
"Work, calling, money and daily life during the year (Midheaven, the 2nd, 6th and 10th houses, Jupiter and \
Saturn transits)",
),
(
"growth",
"Inner development: the progressed Moon's sign, house and lunation phase, the other progressions, and the \
transits of Uranus, Neptune and Pluto",
),
(
"timeline",
"The year in time order from birthday to birthday, in exactly 4 paragraphs, one for each quarter: the main \
periods and dates (transits, eclipses, progressed Moon ingresses) of that quarter",
),
];
2026-11-17 14:25:08 +00:00
fn sections(kind: Kind) -> &'static [(&'static str, &'static str)] {
match kind {
Kind::Natal => &NATAL_SECTIONS,
Kind::Synastry => &SYNASTRY_SECTIONS,
Kind::Forecast => &FORECAST_SECTIONS,
2026-11-17 14:25:08 +00:00
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();
let (strengths, challenges) = match kind {
Kind::Forecast => (
"3-5 main opportunities of the year, one sentence each",
"3-5 main challenges of the year, one sentence each",
),
_ => ("3-5 key strengths, one sentence each", "3-5 key challenges, one sentence each"),
};
2026-11-17 14:25:08 +00:00
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": strengths},
"challenges": {"type": "array", "items": {"type": "string"}, "description": challenges},
2026-11-17 14:25:08 +00:00
"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, kvinkunx (150°), szembenállás (oppozíció);
- Moon phases: újhold, növő sarló, első negyed, növő (domború) hold, telihold, fogyó (domború) hold, utolsó negyed, \
fogyó sarló; name the phase given in the data, never another one;
2026-11-17 14:25:08 +00:00
- 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.";
const HUNGARIAN_FORECAST_TERMS: &str = "\
Forecast terms in Hungarian: szolár (szoláris visszatérés, a szolár képlet), tranzit (\"a Szaturnusz tranzitja a Napod \
felett\"), progresszió (a progresszív Hold), profekció, az év ura, napfogyatkozás, holdfogyatkozás, retrográd, \
Szaturnusz-visszatérés. Write dates the Hungarian way: \"március 12.\", \"március 12-től április 30-ig\", \"2027 januárja\".";
2026-11-17 14:25:08 +00:00
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::Forecast => (
"a personal forecast for one year of life, from one birthday to the next",
"Speak to the owner of the chart directly, in the informal second person singular (in Hungarian: tegező forma, \"te\").",
),
2026-11-17 14:25:08 +00:00
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::Forecast => "Length: each section 2-4 paragraphs (about 150-250 words), the timeline exactly 4 \
paragraphs; the whole forecast about 1500-2000 words.",
2026-11-17 14:25:08 +00:00
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 kind == Kind::Forecast {
text.push_str(FORECAST_RULES);
}
2026-11-17 14:25:08 +00:00
if language == "hu" {
text.push_str("\n\n");
text.push_str(HUNGARIAN_STYLE);
if kind == Kind::Forecast {
text.push('\n');
text.push_str(HUNGARIAN_FORECAST_TERMS);
}
2026-11-17 14:25:08 +00:00
}
text
}
const FORECAST_RULES: &str = "
Forecast rules:
- Describe themes, tendencies, opportunities and the timing of periods, never certain events: \"a good time for\", \
\"may bring\", \"asks for\", not \"will happen\". Nothing about illness, death, accidents, pregnancy, lawsuits or \
gains and losses of money.
- Use only the dates in the data and do not invent any; a transit is felt during its whole period, most strongly \
around the exact dates. Retrograde planets make a contact two or three times: describe it as one process.
- Weigh the techniques as an astrologer does: the solar return Ascendant and the houses of the solar return Sun and \
Moon set the scene; the lord of the year and the profected house say which area of life is activated; exact \
transits of Saturn, Uranus, Neptune and Pluto to the Sun, Moon, Ascendant, Midheaven and personal planets are the \
main turning points; Jupiter transits are openings; eclipses matter only where they touch the natal chart; the \
progressed Moon shows the emotional season.
- A planet meeting its own natal place (marked \"cycle\") is a life milestone, e.g. the Saturn return or the \
Uranus opposition: name it as such.
- If there is no solar return chart (unknown birth time), build the year on the transits and progressions, and do \
not mention houses, the Ascendant or the Midheaven.";
2026-11-17 14:25:08 +00:00
/// 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",
Kind::Forecast => "forecast_analysis",
2026-11-17 14:25:08 +00:00
},
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) = match (language, kind) {
("hu", Kind::Forecast) => ("Lehetőségek", "Kihívások", "Útravaló"),
("hu", _) => ("Erősségek", "Kihívások", "Útravaló"),
(_, Kind::Forecast) => ("Opportunities", "Challenges", "Advice"),
_ => ("Strengths", "Challenges", "Advice"),
2026-11-17 14:25:08 +00:00
};
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 forecast_prompt() {
let p = build(Kind::Forecast, "hu", "SOLAR RETURN", None);
assert_eq!(p.schema_name, "forecast_analysis");
assert!(p.system.contains("Forecast rules") && p.system.contains("szolár") && p.system.contains("tegező"));
assert!(p.user.contains("- timeline:") && p.user.contains("- theme:"));
let keys = p.schema["properties"]["sections"]["required"].as_array().unwrap().len();
assert_eq!(keys, 5);
assert!(!default_system(Kind::Natal, "hu").contains("Forecast rules"));
}
2026-11-17 14:25:08 +00:00
#[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");
}
}