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).
2026-11-18 11:35:07 +00:00
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 ,
2026-11-18 08:19:13 +00:00
/// One year of a natal chart: solar return, transits, progressions, profection, eclipses.
Forecast ,
2026-11-17 14:25:08 +00:00
}
impl Kind {
2026-11-18 08:19:13 +00:00
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" ,
2026-11-18 08:19:13 +00:00
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 ),
2026-11-18 08:19:13 +00:00
"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" ),
];
2026-11-18 08:19:13 +00:00
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-18 13:15:57 +00:00
/// The same sections described in Hungarian, for the Hungarian user message.
const NATAL_SECTIONS_HU : [ & str ; 6 ] = [
"Az alapvető identitás: a Nap, a Hold, az Aszcendens és a horoszkóp uralkodója együtt olvasva" ,
"Érzelmi szükségletek, biztonság és belső világ (Hold, 4. ház, a víz elem hangsúlya)" ,
"Gondolkodás, kommunikáció és tanulás (Merkúr, 3. és 9. ház)" ,
"Szerelem, vonzódás és párkapcsolat (Vénusz, Mars, 5. és 7. ház, Descendens)" ,
"Hivatás, karrier, pénz és mindennapi munka (MC, 10., 2. és 6. ház, Szaturnusz, Jupiter)" ,
"A fő belső feszültségek, életleckék és a fejlődés útja (szoros kvadrátok és szembenállások, Szaturnusz, Chiron, \
Holdcsomópontok)" ,
];
const SYNASTRY_SECTIONS_HU : [ & str ; 5 ] = [
"Ami egymáshoz vonzza őket: a Nap, a Hold, a Vénusz, a Mars és az Aszcendens kapcsolatai" ,
"Hogyan gondolkodnak és beszélgetnek együtt (Merkúr-fényszögek, a levegő elem hangsúlya, 3. házas átfedések)" ,
"Érzelmi közelség, biztonság és gondoskodás (Hold-fényszögek, 4. és 8. házas átfedések)" ,
"Ahol súrlódnak egymással, és hogyan kezelhetik (feszült fényszögek, Szaturnusz, Plútó, Mars)" ,
"Hosszú távú lehetőségek és közös cél, a kompozit képlettel együtt" ,
];
const FORECAST_SECTIONS_HU : [ & str ; 5 ] = [
"Az év fő témája: a szolár képlet (az Aszcendense, a Nap és a Hold háza, a sarkokon álló bolygók, a szoros \
fényszögek), a profekciós ház és az év ura" ,
"Szerelem, párkapcsolat, család és barátságok az évben (Vénusz, Hold, a 4., 5., 7. és 11. ház, és az ezeket érintő \
tranzitok és fogyatkozások)" ,
"Munka, hivatás, pénz és hétköznapok az évben (MC, a 2., 6. és 10. ház, Jupiter- és Szaturnusz-tranzitok)" ,
"Belső fejlődés: a progresszív Hold jegye, háza és holdfázisa, a többi progresszió, valamint az Uránusz, a \
Neptunusz és a Plútó tranzitjai" ,
"Az év időrendben, születésnaptól születésnapig, pontosan 4 bekezdésben, negyedévenként egyben: az adott negyedév \
fő időszakai és dátumai (tranzitok, fogyatkozások, a progresszív Hold jegy- és házváltásai)" ,
];
/// (key, description) of the sections in the language of the user message.
fn sections_in ( kind : Kind , language : & str ) -> Vec < ( & 'static str , & 'static str ) > {
let hu : & [ & str ] = match kind {
Kind ::Natal => & NATAL_SECTIONS_HU ,
Kind ::Synastry => & SYNASTRY_SECTIONS_HU ,
Kind ::Forecast => & FORECAST_SECTIONS_HU ,
Kind ::Summary => & [],
};
sections ( kind ). iter (). zip ( hu ). map ( | ( & ( key , en ), & hu ) | ( key , if language == "hu" { hu } else { en })). collect ()
}
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 ,
2026-11-18 08:19:13 +00:00
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 ();
2026-11-18 08:19:13 +00:00
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 },
2026-11-18 08:19:13 +00:00
"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" }
}
})
}
2026-11-18 13:15:57 +00:00
/// The built-in Hungarian system prompt, written in Hungarian so it is easy to
/// read and edit. The chart data it refers to stays in English.
fn hungarian_system ( kind : Kind ) -> String {
let ( role , reader , length ) = match kind {
Kind ::Natal => (
"személyes születési képletelemzést" ,
SECOND_PERSON_HU ,
"Terjedelem: fejezetenként 2– 4 bekezdés (kb. 150– 250 szó); az egész elemzés kb. 1300– 1800 szó." ,
),
Kind ::Summary => (
"rövid, ingyenes összefoglalót egy születési képletről (ez egy kedvcsináló, amelyet az olvasó a részletes, \
fizetős elemzés előtt lát)" ,
SECOND_PERSON_HU ,
"Terjedelem: egy bekezdés, 3– 4 mondat (60– 100 szó). Válaszd ki a Napot, a Holdat és az Aszcendenst (ha \
ismert a születési idő), valamint a képlet egyetlen legfeltűnőbb vonását (egy nagyon szoros fényszöget, \
egy bolygócsoportot, egy elem erős hangsúlyát vagy hiányát). Legyen önmagában teljes és erre a képletre \
jellemző: ne reklámozzon, és ne említsen hosszabb elemzést." ,
),
Kind ::Forecast => (
"személyes előrejelzést egy életévre, az egyik születésnaptól a következőig" ,
SECOND_PERSON_HU ,
"Terjedelem: fejezetenként 2– 4 bekezdés (kb. 150– 250 szó), az idővonal pontosan 4 bekezdés; az egész \
előrejelzés kb. 1500– 2000 szó." ,
),
Kind ::Synastry => (
"kapcsolati (szinasztria-) elemzést két ember számára" ,
"Egyszerre mindkettőjükhöz szólj, többes szám második személyben („ti”, „kettőtök”). Ha meg kell \
különböztetned őket, az adatokban Person 1 és Person 2 a nevük, a szövegben „az első fél” és „a második \
fél”. Ne feltételezd a nemüket és a kapcsolat jellegét." ,
"Terjedelem: fejezetenként 2– 4 bekezdés (kb. 150– 250 szó); az egész elemzés kb. 1300– 1800 szó." ,
),
};
let mut text = format! (
"Tapasztalt, empatikus, lélektani szemléletű asztrológus vagy. A Sorsfonalak alkalmazás számára {role} írsz.
2026-11-17 14:25:08 +00:00
2026-11-18 13:15:57 +00:00
Magyarul írj, természetes, igényes magyarsággal, ahogy egy magyar anyanyelvű szerző írna: a szöveg ne hasson fordításnak.
Szabályok:
- Minden állítás a megadott képletadatokon alapuljon. Soha ne találj ki olyan pozíciót, fényszöget vagy házat, amely \
nincs az adatok között.
- Amikor egy fényállást értelmezel, egy rövid tagmondatban nevezd meg az asztrológiai alapját, de a hangsúly az emberen \
legyen, ne a szakzsargonon.
- Szintetizálj: a jegyeket, házakat, fényszögeket és uralkodókat egységes portrévá fűzd össze, és mutasd meg, hogyan \
oldhatók fel a feszültségek. A legnagyobb súlyt a Nap, a Hold, az Aszcendens, a horoszkóp uralkodója, a szoros \
fényszögek (3° alatti hatásfok), valamint az elemek és minőségek erős hangsúlyai vagy hiányai kapják.
- Ha az adatokban egy pontnál „on the cusp” áll, az a következő ház csúcsa előtt néhány fokkal van: a megadott házban \
értelmezd, és említheted, hogy a ház kezdetén áll.
- Ha a születési idő ismeretlen, az adott képletnél ne említs házakat, Aszcendenst és MC-t, és a Hold jegyével is \
légy óvatos.
- {reader}
- Hangnem: meleg, őszinte, megerősítő és konkrét. Ne légy fatalista: ne jósolj betegséget, halált, balesetet vagy \
konkrét eseményeket, és ne adj orvosi, jogi vagy pénzügyi tanácsot.
- Kerüld az általános horoszkóp-közhelyeket és a töltelékszöveget: minden bekezdés ennek a képletnek a sajátosságairól \
szóljon.
- A szövegek egyszerű bekezdések, üres sorral elválasztva, címsor és felsorolás nélkül; **félkövért** takarékosan \
használhatsz.
- {length}
- Egyetlen, a megadott sémának megfelelő JSON-objektummal válaszolj, semmi mással."
);
if kind == Kind ::Forecast {
text . push_str ( FORECAST_RULES_HU );
}
text . push_str ( HUNGARIAN_TERMS );
if kind == Kind ::Forecast {
text . push_str ( HUNGARIAN_FORECAST_TERMS );
}
text
}
const SECOND_PERSON_HU : & str =
"Közvetlenül a képlet tulajdonosához szólj, tegező formában (egyes szám második személyben, „te”)." ;
const FORECAST_RULES_HU : & str = "
Az előrejelzés szabályai:
- Témákról, tendenciákról, lehetőségekről és az időszakok időzítéséről írj, soha ne biztos eseményekről: „jó időszak \
arra, hogy”, „hozhat”, „azt kéri tőled”, és nem „be fog következni”. Semmit betegségről, halálról, balesetről, \
terhességről, perekről, pénz nyereségéről vagy elvesztéséről.
- Csak az adatokban szereplő dátumokat használd, ne találj ki újakat. Egy tranzit a teljes hatásideje alatt érezhető, \
a pontos napok körül a legerősebben. A retrográd bolygók kétszer-háromszor is érintenek egy pontot: ezt egyetlen \
folyamatként írd le.
- Úgy súlyozd a technikákat, ahogy egy asztrológus: a szolár Aszcendens és a szolár Nap és Hold háza adja az év \
színterét; az év ura és a profekciós ház mutatja, melyik életterület aktív; a Szaturnusz, az Uránusz, a Neptunusz és a \
Plútó pontos tranzitjai a Napra, a Holdra, az Aszcendensre, az MC-re és a személyes bolygókra a fő fordulópontok; a \
Jupiter-tranzitok nyitások; a fogyatkozások csak ott számítanak, ahol a születési képletet érintik; a progresszív Hold \
az érzelmi évszakot mutatja.
- Ha egy bolygó a saját születési helyével kerül fényszögbe (az adatokban „cycle” jelöli), az az életút mérföldköve, \
például a Szaturnusz-visszatérés vagy az Uránusz-szembenállás: nevezd is így.
- Ha nincs szolár képlet (ismeretlen születési idő), az évet a tranzitokra és a progressziókra építsd, és ne említs \
házakat, Aszcendenst és MC-t." ;
const HUNGARIAN_TERMS : & str = "
Nyelvhelyesség és szakszavak:
- Ügyelj a helyes toldalékokra és a magánhangzó-illeszkedésre; magyar idézőjelet („…”) és nagykötőjelet (– ) használj.
- Az adatok angolul érkeznek, a szövegben mindig a szokásos magyar asztrológiai kifejezéseket használd:
- jegyek: 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”);
- bolygók és pontok: 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;
- fényszögek: együttállás (konjunkció), szextil, kvadrát (négyzet), trigon, kvinkunx (150°), szembenállás \
(oppozíció);
- holdfázisok: újhold, növő sarló, első negyed, növő (domború) hold, telihold, fogyó (domború) hold, utolsó negyed, \
fogyó sarló; mindig az adatokban megadott fázist nevezd meg, soha ne másikat;
- elemek és minőségek: tűz, föld, levegő, víz („tűz elem”, „a föld hiánya”); kardinális, fix, változó;
- egyéb: „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.
- Ne maradjon angol szó a szövegben (pl. fire, earth, house, cusp)." ;
const HUNGARIAN_FORECAST_TERMS : & str = "
- Előrejelzési kifejezések: 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.
- A dátumokat magyarosan írd: „március 12.”, „március 12-től április 30-ig”, „2027 januárja”." ;
2026-11-18 08:19:13 +00:00
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 {
2026-11-18 13:15:57 +00:00
if language == "hu" {
return hungarian_system ( kind );
}
2026-11-17 14:25:08 +00:00
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 \" )." ,
),
2026-11-18 08:19:13 +00:00
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.
2026-11-18 13:15:57 +00:00
- A point marked \" on the cusp \" in the data is a few degrees before the next house cusp: read it in the house given; you may say it stands at the start of that house.
2026-11-17 14:25:08 +00:00
- 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 {
2026-11-18 08:19:13 +00:00
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." ,
},
);
2026-11-18 08:19:13 +00:00
if kind == Kind ::Forecast {
text . push_str ( FORECAST_RULES );
}
2026-11-17 14:25:08 +00:00
text
}
2026-11-18 08:19:13 +00:00
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 {
2026-11-18 13:15:57 +00:00
let hu = language == "hu" ;
let mut user = String ::from ( if hu { "Képletadatok: \n\n " } else { "Chart data: \n\n " });
2026-11-17 14:25:08 +00:00
user . push_str ( chart_text );
if kind == Kind ::Summary {
2026-11-18 13:15:57 +00:00
user . push_str ( if hu { " \n Most írd meg a rövid összefoglalót." } else { " \n Write the short summary now." });
2026-11-17 14:25:08 +00:00
} else {
2026-11-18 13:15:57 +00:00
user . push_str ( if hu {
" \n A megírandó fejezetek ebben a sorrendben (JSON-kulcs: tartalom): \n "
} else {
" \n Sections to write, in this order: \n "
});
for ( key , about ) in sections_in ( kind , language ) {
2026-11-17 14:25:08 +00:00
user . push_str ( & format! ( "- {key} : {about} \n " ));
}
2026-11-18 13:15:57 +00:00
user . push_str ( if hu { " \n Most írd meg az elemzést." } else { " \n Write the analysis now." });
2026-11-17 14:25:08 +00:00
}
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" ,
2026-11-18 08:19:13 +00:00
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 {
2026-11-18 08:19:13 +00:00
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" );
2026-11-18 13:15:57 +00:00
assert! ( p . system . contains ( "3– 4 mondat" ) && p . system . contains ( "tegező" ));
assert! ( ! p . user . contains ( "fejezetek" ) && p . user . contains ( "rövid összefoglalót" ));
assert! ( default_system ( Kind ::Summary , "en" ). contains ( "3-4 sentences" ));
2026-11-17 14:25:08 +00:00
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 )));
}
2026-11-18 08:19:13 +00:00
#[test]
fn forecast_prompt () {
let p = build ( Kind ::Forecast , "hu" , "SOLAR RETURN" , None );
assert_eq! ( p . schema_name , "forecast_analysis" );
2026-11-18 13:15:57 +00:00
assert! (
p . system . contains ( "előrejelzés szabályai" ) && p . system . contains ( "szolár" ) && p . system . contains ( "tegező" )
);
assert! ( p . user . contains ( "- timeline: Az év időrendben" ) && p . user . contains ( "- theme:" ));
assert! ( default_system ( Kind ::Forecast , "en" ). contains ( "Forecast rules" ));
2026-11-18 08:19:13 +00:00
let keys = p . schema [ "properties" ][ "sections" ][ "required" ]. as_array (). unwrap (). len ();
assert_eq! ( keys , 5 );
2026-11-18 13:15:57 +00:00
assert! ( ! default_system ( Kind ::Natal , "hu" ). contains ( "előrejelzés szabályai" ));
// the Hungarian prompt has a Hungarian description for every section
for kind in Kind ::ALL {
assert_eq! ( sections_in ( kind , "hu" ). len (), sections ( kind ). len ());
}
2026-11-18 08:19:13 +00:00
}
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" );
}
}