Write text analyses with OpenRouter in the worker
- analysis job: claims pending analyses (SKIP LOCKED, NOTIFY wake-up), builds a compact chart text without birth data, asks OpenRouter with a strict JSON schema, validates and stores the answer, model used, tokens and cost; retries transient errors, refunds credits on final failure, requeues interrupted jobs - prompt v1 for natal and synastry analyses, Hungarian style guide - compare-models subcommand for blind model comparison - migration 0003: attempts, next_attempt_at, model_used, cost_usd, notify trigger, one refund per analysis - db: rebuild when migrations change - compose: worker reads OPENROUTER_API_KEY from .env.secrets Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -0,0 +1,224 @@
|
||||
//! 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 = "v1";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Kind {
|
||||
Natal,
|
||||
Synastry,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
pub fn parse(s: &str) -> Option<Kind> {
|
||||
match s {
|
||||
"natal" => Some(Kind::Natal),
|
||||
"synastry" => Some(Kind::Synastry),
|
||||
_ => 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,
|
||||
}
|
||||
}
|
||||
|
||||
/// The JSON schema of the answer (strict mode: every property required).
|
||||
pub fn schema(kind: Kind) -> Value {
|
||||
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ó);
|
||||
- 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::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: each section 2-4 paragraphs (about 150-250 words); the whole analysis about 1300-1800 words.
|
||||
- Answer with a single JSON object that matches the given schema, and nothing else.",
|
||||
lang = language_name(language),
|
||||
);
|
||||
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);
|
||||
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",
|
||||
},
|
||||
schema: schema(kind),
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks an answer against our schema subset (objects with required
|
||||
/// properties, non-empty strings, string arrays with at least two items).
|
||||
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.trim().is_empty() => Ok(()),
|
||||
_ => Err(format!("{path}: expected a non-empty string")),
|
||||
},
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
walk(schema, value, "$")
|
||||
}
|
||||
|
||||
/// 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(""));
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user