Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4ee40f45d | ||
|
|
27de820091 | ||
|
|
422078545e | ||
|
|
23975a8369 | ||
|
|
2a7cb467cf | ||
|
|
62df5c2764 | ||
|
|
e2cf1d7118 | ||
|
|
b0e35433ac |
+1
-1
@@ -49,7 +49,7 @@ jiff = { version = "0.2", default-features = false, features = ["std", "tzdb-zon
|
|||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
thiserror = "2"
|
thiserror = "2"
|
||||||
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "signal"] }
|
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "signal", "sync"] }
|
||||||
tower-http = { version = "0.6", features = ["trace", "cors"] }
|
tower-http = { version = "0.6", features = ["trace", "cors"] }
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
|
tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }
|
||||||
|
|||||||
@@ -112,7 +112,7 @@ Környezeti változók: `ASTRO_DATA_DIR` (alapérték: `data`), `BIND_ADDR` (`0.
|
|||||||
| `ayanamsa` | **`lahiri`**, `fagan_bradley`, `raman`, `krishnamurti`, `de_luce`, `yukteshwar`, `true_citra`, `galactic_center0_sag` (csak sziderikus zodiákusnál) |
|
| `ayanamsa` | **`lahiri`**, `fagan_bradley`, `raman`, `krishnamurti`, `de_luce`, `yukteshwar`, `true_citra`, `galactic_center0_sag` (csak sziderikus zodiákusnál) |
|
||||||
| `node_type` | **`true`**, `mean`: holdcsomópont |
|
| `node_type` | **`true`**, `mean`: holdcsomópont |
|
||||||
| `lilith_type` | **`mean`**, `true`: Fekete Hold |
|
| `lilith_type` | **`mean`**, `true`: Fekete Hold |
|
||||||
| `aspect_set` | **`major`** (együttállás, szextil, kvadrát, trigon, oppozíció), `extended` (+ félszextil, félkvadrát, kvintil, másfélkvadrát, bikvintil, kvinkunx) |
|
| `aspect_set` | `major` (együttállás, szextil, kvadrát, trigon, oppozíció), **`standard`** (a fők + kvinkunx 150°), `extended` (+ félszextil, félkvadrát, kvintil, másfélkvadrát, bikvintil) |
|
||||||
| `orb_multiplier` | **`1.0`** (0 < x ≤ 3) |
|
| `orb_multiplier` | **`1.0`** (0 < x ≤ 3) |
|
||||||
| `topocentric` | **`false`** |
|
| `topocentric` | **`false`** |
|
||||||
| `include_asteroids` | **`true`** (Ceres, Pallas, Juno, Vesta) |
|
| `include_asteroids` | **`true`** (Ceres, Pallas, Juno, Vesta) |
|
||||||
@@ -156,6 +156,8 @@ Környezeti változók: `ASTRO_DATA_DIR` (alapérték: `data`), `BIND_ADDR` (`0.
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
A holdfázis fő fázisai (újhold, első negyed, telihold, utolsó negyed) a pontos fényszögtől legfeljebb 12°-ig tartanak, és csak a megfelelő jegyek között: telihold csak szemben álló jegyekben (Kos–Mérleg, Bika–Skorpió …), újhold egy jegyben. Minden más helyzet sarló vagy domború hold.
|
||||||
|
|
||||||
Minden azonosító (bolygó, jegy, fényszög, fázis) angol `snake_case`; a magyar fordítás a frontend feladata.
|
Minden azonosító (bolygó, jegy, fényszög, fázis) angol `snake_case`; a magyar fordítás a frontend feladata.
|
||||||
|
|
||||||
### `POST /v1/synastry`: kérés
|
### `POST /v1/synastry`: kérés
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
/// Matches the backend's `ANALYSIS_PROMPT_VERSION` (part of the cache key).
|
/// Matches the backend's `ANALYSIS_PROMPT_VERSION` (part of the cache key).
|
||||||
pub const PROMPT_VERSION: &str = "v2";
|
pub const PROMPT_VERSION: &str = "v3";
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum Kind {
|
pub enum Kind {
|
||||||
@@ -100,6 +100,48 @@ const FORECAST_SECTIONS: [(&str, &str); 5] = [
|
|||||||
),
|
),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/// 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()
|
||||||
|
}
|
||||||
|
|
||||||
fn sections(kind: Kind) -> &'static [(&'static str, &'static str)] {
|
fn sections(kind: Kind) -> &'static [(&'static str, &'static str)] {
|
||||||
match kind {
|
match kind {
|
||||||
Kind::Natal => &NATAL_SECTIONS,
|
Kind::Natal => &NATAL_SECTIONS,
|
||||||
@@ -161,22 +203,121 @@ pub fn schema(kind: Kind) -> Value {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const HUNGARIAN_STYLE: &str = "\
|
/// The built-in Hungarian system prompt, written in Hungarian so it is easy to
|
||||||
Write natural, idiomatic Hungarian, as a native Hungarian author would; it must not read like a translation from English. \
|
/// read and edit. The chart data it refers to stays in English.
|
||||||
Use correct Hungarian suffixes and vowel harmony, Hungarian quotation marks („…”) and the en dash (–). \
|
fn hungarian_system(kind: Kind) -> String {
|
||||||
Use the usual Hungarian astrological terms:
|
let (role, reader, length) = match kind {
|
||||||
- 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\");
|
Kind::Natal => (
|
||||||
- planets and points: Nap, Hold, Merkúr, Vénusz, Mars, Jupiter, Szaturnusz, Uránusz, Neptunusz, Plútó, Chiron (Kiron), \
|
"személyes születési képletelemzést",
|
||||||
Észak-Holdcsomópont, Dél-Holdcsomópont, Lilith (Fekete Hold), Aszcendens, Descendens, Medium Coeli (MC), Imum Coeli (IC), Szerencsepont;
|
SECOND_PERSON_HU,
|
||||||
- aspects: együttállás (konjunkció), szextil, kvadrát (négyzet), trigon, szembenállás (oppozíció);
|
"Terjedelem: fejezetenként 2–4 bekezdés (kb. 150–250 szó); az egész elemzés kb. 1300–1800 szó.",
|
||||||
- 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.
|
Kind::Summary => (
|
||||||
- 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.";
|
"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.
|
||||||
|
|
||||||
const HUNGARIAN_FORECAST_TERMS: &str = "\
|
Magyarul írj, természetes, igényes magyarsággal, ahogy egy magyar anyanyelvű szerző írna: a szöveg ne hasson fordításnak.
|
||||||
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, \
|
Szabályok:
|
||||||
Szaturnusz-visszatérés. Write dates the Hungarian way: \"március 12.\", \"március 12-től április 30-ig\", \"2027 januárja\".";
|
- 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”.";
|
||||||
|
|
||||||
fn language_name(language: &str) -> &'static str {
|
fn language_name(language: &str) -> &'static str {
|
||||||
match language {
|
match language {
|
||||||
@@ -187,6 +328,9 @@ fn language_name(language: &str) -> &'static str {
|
|||||||
|
|
||||||
/// The built-in system prompt of an analysis kind in a language.
|
/// The built-in system prompt of an analysis kind in a language.
|
||||||
pub fn default_system(kind: Kind, language: &str) -> String {
|
pub fn default_system(kind: Kind, language: &str) -> String {
|
||||||
|
if language == "hu" {
|
||||||
|
return hungarian_system(kind);
|
||||||
|
}
|
||||||
let (role, reader) = match kind {
|
let (role, reader) = match kind {
|
||||||
Kind::Natal => (
|
Kind::Natal => (
|
||||||
"a personal natal chart interpretation",
|
"a personal natal chart interpretation",
|
||||||
@@ -217,6 +361,7 @@ Rules:
|
|||||||
- When you interpret a placement, name its astrological basis in a short clause, but keep the focus on the person, not on jargon.
|
- 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. \
|
- 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.
|
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.
|
||||||
|
- 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.
|
||||||
- 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.
|
- 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}
|
- {reader}
|
||||||
- Tone: warm, honest, empowering and concrete. Not fatalistic: no predictions of illness, death, accidents or specific events, \
|
- Tone: warm, honest, empowering and concrete. Not fatalistic: no predictions of illness, death, accidents or specific events, \
|
||||||
@@ -239,14 +384,6 @@ and no medical, legal or financial advice.
|
|||||||
if kind == Kind::Forecast {
|
if kind == Kind::Forecast {
|
||||||
text.push_str(FORECAST_RULES);
|
text.push_str(FORECAST_RULES);
|
||||||
}
|
}
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
text
|
text
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -288,16 +425,21 @@ pub fn user_template(kind: Kind) -> String {
|
|||||||
|
|
||||||
/// The prompt for one analysis; `system` replaces [`default_system`].
|
/// The prompt for one analysis; `system` replaces [`default_system`].
|
||||||
pub fn build(kind: Kind, language: &str, chart_text: &str, system: Option<&str>) -> Prompt {
|
pub fn build(kind: Kind, language: &str, chart_text: &str, system: Option<&str>) -> Prompt {
|
||||||
let mut user = String::from("Chart data:\n\n");
|
let hu = language == "hu";
|
||||||
|
let mut user = String::from(if hu { "Képletadatok:\n\n" } else { "Chart data:\n\n" });
|
||||||
user.push_str(chart_text);
|
user.push_str(chart_text);
|
||||||
if kind == Kind::Summary {
|
if kind == Kind::Summary {
|
||||||
user.push_str("\nWrite the short summary now.");
|
user.push_str(if hu { "\nMost írd meg a rövid összefoglalót." } else { "\nWrite the short summary now." });
|
||||||
} else {
|
} else {
|
||||||
user.push_str("\nSections to write, in this order:\n");
|
user.push_str(if hu {
|
||||||
for (key, about) in sections(kind) {
|
"\nA megírandó fejezetek ebben a sorrendben (JSON-kulcs: tartalom):\n"
|
||||||
|
} else {
|
||||||
|
"\nSections to write, in this order:\n"
|
||||||
|
});
|
||||||
|
for (key, about) in sections_in(kind, language) {
|
||||||
user.push_str(&format!("- {key}: {about}\n"));
|
user.push_str(&format!("- {key}: {about}\n"));
|
||||||
}
|
}
|
||||||
user.push_str("\nWrite the analysis now.");
|
user.push_str(if hu { "\nMost írd meg az elemzést." } else { "\nWrite the analysis now." });
|
||||||
}
|
}
|
||||||
Prompt {
|
Prompt {
|
||||||
system: system.map_or_else(|| default_system(kind, language), str::to_owned),
|
system: system.map_or_else(|| default_system(kind, language), str::to_owned),
|
||||||
@@ -412,8 +554,9 @@ mod tests {
|
|||||||
fn summary_prompt_is_short() {
|
fn summary_prompt_is_short() {
|
||||||
let p = build(Kind::Summary, "hu", "SUN: Cancer", None);
|
let p = build(Kind::Summary, "hu", "SUN: Cancer", None);
|
||||||
assert_eq!(p.schema_name, "chart_summary");
|
assert_eq!(p.schema_name, "chart_summary");
|
||||||
assert!(p.system.contains("3-4 sentences") && p.system.contains("tegező"));
|
assert!(p.system.contains("3–4 mondat") && p.system.contains("tegező"));
|
||||||
assert!(!p.user.contains("Sections to write"));
|
assert!(!p.user.contains("fejezetek") && p.user.contains("rövid összefoglalót"));
|
||||||
|
assert!(default_system(Kind::Summary, "en").contains("3-4 sentences"));
|
||||||
assert_eq!(validate(&p.schema, &json!({"title": "Érzékeny mag", "summary": "Rövid szöveg."})), Ok(()));
|
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());
|
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."}));
|
let md = to_markdown(Kind::Summary, "hu", &json!({"title": "Cím", "summary": "Szöveg."}));
|
||||||
@@ -436,11 +579,18 @@ mod tests {
|
|||||||
fn forecast_prompt() {
|
fn forecast_prompt() {
|
||||||
let p = build(Kind::Forecast, "hu", "SOLAR RETURN", None);
|
let p = build(Kind::Forecast, "hu", "SOLAR RETURN", None);
|
||||||
assert_eq!(p.schema_name, "forecast_analysis");
|
assert_eq!(p.schema_name, "forecast_analysis");
|
||||||
assert!(p.system.contains("Forecast rules") && p.system.contains("szolár") && p.system.contains("tegező"));
|
assert!(
|
||||||
assert!(p.user.contains("- timeline:") && p.user.contains("- theme:"));
|
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"));
|
||||||
let keys = p.schema["properties"]["sections"]["required"].as_array().unwrap().len();
|
let keys = p.schema["properties"]["sections"]["required"].as_array().unwrap().len();
|
||||||
assert_eq!(keys, 5);
|
assert_eq!(keys, 5);
|
||||||
assert!(!default_system(Kind::Natal, "hu").contains("Forecast rules"));
|
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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -616,7 +616,7 @@ pub fn calculate_chart(engine: &dyn Ephemeris, input: &ChartInput) -> Result<Nat
|
|||||||
let elongation = normalize(moon - sun);
|
let elongation = normalize(moon - sun);
|
||||||
let moon_phase = MoonPhase {
|
let moon_phase = MoonPhase {
|
||||||
elongation,
|
elongation,
|
||||||
phase: phase_name(elongation),
|
phase: phase_name(sun, moon),
|
||||||
illumination: engine.illumination(Body::Moon, jd)?,
|
illumination: engine.illumination(Body::Moon, jd)?,
|
||||||
waxing: elongation < 180.0,
|
waxing: elongation < 180.0,
|
||||||
};
|
};
|
||||||
@@ -720,10 +720,28 @@ fn above_horizon(lon: f64, ascendant: f64) -> bool {
|
|||||||
angle::arc(ascendant, lon) >= 180.0
|
angle::arc(ascendant, lon) >= 180.0
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn phase_name(elongation: f64) -> MoonPhaseName {
|
/// At most this far from the exact new moon, quarter or full moon is the
|
||||||
|
/// Moon still in that phase, as astrologers read it.
|
||||||
|
const LUNATION_ORB: f64 = 12.0;
|
||||||
|
|
||||||
|
/// The Moon's phase from the longitudes of the Sun and the Moon. A main phase
|
||||||
|
/// (new, first quarter, full, last quarter) is the exact aspect of the lights
|
||||||
|
/// within [`LUNATION_ORB`] and in the matching signs: a full moon only between
|
||||||
|
/// opposite signs (Aries–Libra, Taurus–Scorpio, ...), a new moon in one sign.
|
||||||
|
/// Otherwise the Moon is crescent or gibbous, so a Moon 150° from the Sun (a
|
||||||
|
/// quincunx) or 30° past the opposition is not full.
|
||||||
|
pub(crate) fn phase_name(sun: f64, moon: f64) -> MoonPhaseName {
|
||||||
use MoonPhaseName::*;
|
use MoonPhaseName::*;
|
||||||
[NewMoon, WaxingCrescent, FirstQuarter, WaxingGibbous, FullMoon, WaningGibbous, LastQuarter, WaningCrescent]
|
let elongation = (moon - sun).rem_euclid(360.0);
|
||||||
[((elongation / 45.0).floor() as usize).min(7)]
|
let signs_apart = (ZodiacSign::from_longitude(moon).index() + 12 - ZodiacSign::from_longitude(sun).index()) % 12;
|
||||||
|
let main = [NewMoon, FirstQuarter, FullMoon, LastQuarter];
|
||||||
|
for (k, phase) in main.into_iter().enumerate() {
|
||||||
|
let off = (elongation - 90.0 * k as f64 + 180.0).rem_euclid(360.0) - 180.0;
|
||||||
|
if off.abs() <= LUNATION_ORB && signs_apart == 3 * k {
|
||||||
|
return phase;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[WaxingCrescent, WaxingGibbous, WaningGibbous, WaningCrescent][((elongation / 90.0) as usize).min(3)]
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Points taking part in aspects as `(id, longitude, speed)`: everything but
|
/// Points taking part in aspects as `(id, longitude, speed)`: everything but
|
||||||
@@ -744,8 +762,10 @@ pub(crate) fn aspect_points(points: &[Point], angles: Option<&Angles>) -> Vec<(P
|
|||||||
|
|
||||||
pub(crate) fn aspect_kinds(set: AspectSet) -> Vec<AspectKind> {
|
pub(crate) fn aspect_kinds(set: AspectSet) -> Vec<AspectKind> {
|
||||||
let mut kinds = AspectKind::MAJOR.to_vec();
|
let mut kinds = AspectKind::MAJOR.to_vec();
|
||||||
if set == AspectSet::Extended {
|
match set {
|
||||||
kinds.extend(AspectKind::MINOR);
|
AspectSet::Major => {}
|
||||||
|
AspectSet::Standard => kinds.push(AspectKind::Quincunx),
|
||||||
|
AspectSet::Extended => kinds.extend(AspectKind::MINOR),
|
||||||
}
|
}
|
||||||
kinds
|
kinds
|
||||||
}
|
}
|
||||||
@@ -888,9 +908,31 @@ mod tests {
|
|||||||
// Ascendant at 0° Aries: Cancer (90°) is below (IC side), Capricorn (270°) above.
|
// Ascendant at 0° Aries: Cancer (90°) is below (IC side), Capricorn (270°) above.
|
||||||
assert!(!above_horizon(90.0, 0.0));
|
assert!(!above_horizon(90.0, 0.0));
|
||||||
assert!(above_horizon(270.0, 0.0));
|
assert!(above_horizon(270.0, 0.0));
|
||||||
assert_eq!(phase_name(0.0), MoonPhaseName::NewMoon);
|
use MoonPhaseName::*;
|
||||||
assert_eq!(phase_name(185.0), MoonPhaseName::FullMoon);
|
// (Sun, Moon) longitudes
|
||||||
assert_eq!(phase_name(359.9), MoonPhaseName::WaningCrescent);
|
assert_eq!(phase_name(10.0, 10.0), NewMoon);
|
||||||
|
assert_eq!(phase_name(15.0, 5.0), NewMoon); // 10° before, both in Aries
|
||||||
|
assert_eq!(phase_name(3.0, 355.0), WaningCrescent); // 8° before, but Pisces–Aries
|
||||||
|
assert_eq!(phase_name(28.0, 359.0), WaningCrescent); // 29° before, and in Pisces
|
||||||
|
assert_eq!(phase_name(10.0, 195.0), FullMoon); // Aries–Libra, 5° past
|
||||||
|
assert_eq!(phase_name(2.0, 170.0), WaxingGibbous); // 12° before, but Aries–Virgo
|
||||||
|
assert_eq!(phase_name(25.0, 199.0), FullMoon); // 6° before, Aries–Libra
|
||||||
|
assert_eq!(phase_name(10.0, 203.0), WaningGibbous); // 13° past: beyond the orb
|
||||||
|
// a quincunx between the lights is not a full moon
|
||||||
|
assert_eq!(phase_name(10.0, 159.0), WaxingGibbous);
|
||||||
|
assert_eq!(phase_name(10.0, 221.1), WaningGibbous);
|
||||||
|
assert_eq!(phase_name(10.0, 100.0), FirstQuarter); // Aries–Cancer
|
||||||
|
assert_eq!(phase_name(10.0, 285.0), LastQuarter); // Aries–Capricorn
|
||||||
|
assert_eq!(phase_name(10.0, 340.0), WaningCrescent);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_default_aspects_include_the_quincunx() {
|
||||||
|
let pts = [(PointId::Sun, 10.0, 1.0), (PointId::Moon, 159.0, 13.0)]; // 149° apart
|
||||||
|
assert_eq!(AspectSet::default(), AspectSet::Standard);
|
||||||
|
let found = find_aspects(&pts, AspectSet::Standard, 1.0);
|
||||||
|
assert_eq!(found.iter().map(|a| a.aspect).collect::<Vec<_>>(), [AspectKind::Quincunx]);
|
||||||
|
assert!(find_aspects(&pts, AspectSet::Major, 1.0).is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -37,8 +37,15 @@ const NEAR_DAYS: f64 = 200.0;
|
|||||||
|
|
||||||
const TRANSITING: [Body; 5] = [Body::Jupiter, Body::Saturn, Body::Uranus, Body::Neptune, Body::Pluto];
|
const TRANSITING: [Body; 5] = [Body::Jupiter, Body::Saturn, Body::Uranus, Body::Neptune, Body::Pluto];
|
||||||
const PROGRESSED: [Body; 5] = [Body::Sun, Body::Moon, Body::Mercury, Body::Venus, Body::Mars];
|
const PROGRESSED: [Body; 5] = [Body::Sun, Body::Moon, Body::Mercury, Body::Venus, Body::Mars];
|
||||||
const ASPECTS: [AspectKind; 5] =
|
/// The aspects of the default chart (`AspectSet::Standard`): the major ones and the quincunx.
|
||||||
[AspectKind::Conjunction, AspectKind::Sextile, AspectKind::Square, AspectKind::Trine, AspectKind::Opposition];
|
const ASPECTS: [AspectKind; 6] = [
|
||||||
|
AspectKind::Conjunction,
|
||||||
|
AspectKind::Sextile,
|
||||||
|
AspectKind::Square,
|
||||||
|
AspectKind::Trine,
|
||||||
|
AspectKind::Quincunx,
|
||||||
|
AspectKind::Opposition,
|
||||||
|
];
|
||||||
|
|
||||||
type Result<T> = std::result::Result<T, EngineError>;
|
type Result<T> = std::result::Result<T, EngineError>;
|
||||||
|
|
||||||
@@ -409,7 +416,7 @@ impl Year<'_> {
|
|||||||
|
|
||||||
// The progressed lunation phase: the progressed Moon's distance from the progressed Sun.
|
// The progressed lunation phase: the progressed Moon's distance from the progressed Sun.
|
||||||
let (sun, moon) = (&samples[0], &samples[1]);
|
let (sun, moon) = (&samples[0], &samples[1]);
|
||||||
let phase_at = |i: usize| phase_name((moon.lon[i] - sun.lon[i]).rem_euclid(360.0));
|
let phase_at = |i: usize| phase_name(sun.lon[i], moon.lon[i]);
|
||||||
let lunar_phase = phase_at(0);
|
let lunar_phase = phase_at(0);
|
||||||
let lunar_phase_change = if known {
|
let lunar_phase_change = if known {
|
||||||
(1..moon.lon.len())
|
(1..moon.lon.len())
|
||||||
|
|||||||
@@ -96,8 +96,10 @@ pub enum Ayanamsa {
|
|||||||
#[serde(rename_all = "snake_case")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub enum AspectSet {
|
pub enum AspectSet {
|
||||||
/// Conjunction, sextile, square, trine, opposition.
|
/// Conjunction, sextile, square, trine, opposition.
|
||||||
#[default]
|
|
||||||
Major,
|
Major,
|
||||||
|
/// The major aspects plus the quincunx (150°), which most astrologers read.
|
||||||
|
#[default]
|
||||||
|
Standard,
|
||||||
/// Major aspects plus semisextile, semisquare, quintile, sesquiquadrate, biquintile, quincunx.
|
/// Major aspects plus semisextile, semisquare, quintile, sesquiquadrate, biquintile, quincunx.
|
||||||
Extended,
|
Extended,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
-- The yearly forecast prompt is editable on the admin page too, and can be
|
||||||
|
-- tried on one of the admin's own forecasts.
|
||||||
|
ALTER TABLE prompt_revisions DROP CONSTRAINT prompt_revisions_kind_check;
|
||||||
|
ALTER TABLE prompt_revisions ADD CONSTRAINT prompt_revisions_kind_check
|
||||||
|
CHECK (kind IN ('summary', 'natal', 'synastry', 'forecast'));
|
||||||
|
|
||||||
|
ALTER TABLE prompt_previews DROP CONSTRAINT prompt_previews_target;
|
||||||
|
ALTER TABLE prompt_previews
|
||||||
|
ADD COLUMN forecast_id uuid REFERENCES forecasts ON DELETE CASCADE,
|
||||||
|
ADD CONSTRAINT prompt_previews_target CHECK (
|
||||||
|
(kind IN ('summary', 'natal') AND chart_id IS NOT NULL AND synastry_id IS NULL AND forecast_id IS NULL)
|
||||||
|
OR (kind = 'synastry' AND synastry_id IS NOT NULL AND chart_id IS NULL AND forecast_id IS NULL)
|
||||||
|
OR (kind = 'forecast' AND forecast_id IS NOT NULL AND chart_id IS NULL AND synastry_id IS NULL)
|
||||||
|
);
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- The model writing each kind of analysis, chosen on the admin page. Without
|
||||||
|
-- a row the backend's default (ANALYSIS_MODEL, SUMMARY_MODEL) is used.
|
||||||
|
CREATE TABLE model_settings (
|
||||||
|
kind text PRIMARY KEY CHECK (kind IN ('summary', 'natal', 'synastry', 'forecast')),
|
||||||
|
model text NOT NULL CHECK (length(model) BETWEEN 3 AND 200),
|
||||||
|
updated_by uuid REFERENCES users ON DELETE SET NULL,
|
||||||
|
updated_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
+3
-2
@@ -7,7 +7,7 @@ Egy év születésnaptól születésnapig, több bevett előrejelző módszerbő
|
|||||||
| Módszer | Mit ad | Hol számolódik |
|
| Módszer | Mit ad | Hol számolódik |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| **Szolár** (szoláris visszatérés) | Az a pillanat, amikor a Nap visszatér a születéskori hosszúságára; az erre a pillanatra és a születésnapi tartózkodási helyre felállított képlet „az év képlete”. | `astro_engine::forecast::solar_return`, a képlet a horoscope-api-ban |
|
| **Szolár** (szoláris visszatérés) | Az a pillanat, amikor a Nap visszatér a születéskori hosszúságára; az erre a pillanatra és a születésnapi tartózkodási helyre felállított képlet „az év képlete”. | `astro_engine::forecast::solar_return`, a képlet a horoscope-api-ban |
|
||||||
| **Tranzitok** | A Jupiter, Szaturnusz, Uránusz, Neptunusz és Plútó fő fényszögei (együttállás, szextil, kvadrát, trigon, szembenállás) a tíz bolygóhoz, az Aszcendenshez és az MC-hez, 1° hatásfokkal: pontos dátumok (retrográd áthaladásokkal) és hatásidők. A lassú bolygók házai és házváltásai. | `forecast.rs`, `Year::transits` |
|
| **Tranzitok** | A Jupiter, Szaturnusz, Uránusz, Neptunusz és Plútó fő fényszögei (együttállás, szextil, kvadrát, trigon, szembenállás) és a kvinkunx (150°) a tíz bolygóhoz, az Aszcendenshez és az MC-hez, 1° hatásfokkal: pontos dátumok (retrográd áthaladásokkal) és hatásidők. A lassú bolygók házai és házváltásai. | `forecast.rs`, `Year::transits` |
|
||||||
| **Szekunder direkció** | „Egy nap = egy év”: a progresszív Nap, Hold, Merkúr, Vénusz, Mars helye, jegy- és házváltásai, fényszögei a születési képlethez, a progresszív holdfázis. | `Year::progressions` |
|
| **Szekunder direkció** | „Egy nap = egy év”: a progresszív Nap, Hold, Merkúr, Vénusz, Mars helye, jegy- és házváltásai, fényszögei a születési képlethez, a progresszív holdfázis. | `Year::progressions` |
|
||||||
| **Éves profekció** | Minden életév egy házat aktivál (egész jegyes házak az Aszcendenstől); a jegy hagyományos uralkodója „az év ura”. | `Year::profection` |
|
| **Éves profekció** | Minden életév egy házat aktivál (egész jegyes házak az Aszcendenstől); a jegy hagyományos uralkodója „az év ura”. | `Year::profection` |
|
||||||
| **Fogyatkozások** | Az év nap- és holdfogyatkozásai (a félárnyékos holdfogyatkozás nélkül), a születési házuk, és ha 3°-on belül érintenek egy születési pontot. | Swiss Ephemeris `swe_sol_eclipse_when_glob`, `swe_lun_eclipse_when` |
|
| **Fogyatkozások** | Az év nap- és holdfogyatkozásai (a félárnyékos holdfogyatkozás nélkül), a születési házuk, és ha 3°-on belül érintenek egy születési pontot. | Swiss Ephemeris `swe_sol_eclipse_when_glob`, `swe_lun_eclipse_when` |
|
||||||
@@ -31,8 +31,9 @@ A modellhez nem megy születési dátum, hely vagy pontos életkor (csak évtize
|
|||||||
|
|
||||||
Trendekről, lehetőségekről és időzítésről szól, nem biztos eseményekről. Betegségről, halálról, balesetről, terhességről, perekről és pénzügyi nyereségről vagy veszteségről nem jósol (`FORECAST_RULES` a promptban).
|
Trendekről, lehetőségekről és időzítésről szól, nem biztos eseményekről. Betegségről, halálról, balesetről, terhességről, perekről és pénzügyi nyereségről vagy veszteségről nem jósol (`FORECAST_RULES` a promptban).
|
||||||
|
|
||||||
|
A rendszerprompt az admin felületen (Promptok → Éves előrejelzés) szerkeszthető, és mentés előtt kipróbálható az admin egyik saját, már kiszámolt évén. A változás csak az ezután kért elemzésekre hat. A modell kapta adatsor (`compact::forecast`) és a kimeneti séma a kódban van.
|
||||||
|
|
||||||
## Később
|
## Később
|
||||||
|
|
||||||
- Havi előrejelzés: holdvisszatérés és a hónap gyorsabb tranzitjai (Mars, Vénusz, Nap).
|
- Havi előrejelzés: holdvisszatérés és a hónap gyorsabb tranzitjai (Mars, Vénusz, Nap).
|
||||||
- Tranzitok a kompozit képletre: „mi vár rátok idén”.
|
- Tranzitok a kompozit képletre: „mi vár rátok idén”.
|
||||||
- Az admin promptszerkesztőben az előrejelzés promptja is szerkeszthető legyen.
|
|
||||||
|
|||||||
@@ -20,9 +20,10 @@ Felhasználók, belépés, mentett születési képletek, szinasztriák és megh
|
|||||||
| `GOOGLE_CLIENT_IDS` | – | Google OAuth kliens-azonosító(k); üresen a Google-belépés ki van kapcsolva |
|
| `GOOGLE_CLIENT_IDS` | – | Google OAuth kliens-azonosító(k); üresen a Google-belépés ki van kapcsolva |
|
||||||
| `BOOTSTRAP_ADMIN_EMAILS` | – | ezek a címek regisztrációkor vagy belépéskor admin szerepet kapnak (így lesz meg az első admin) |
|
| `BOOTSTRAP_ADMIN_EMAILS` | – | ezek a címek regisztrációkor vagy belépéskor admin szerepet kapnak (így lesz meg az első admin) |
|
||||||
| `SUPPORTED_LOCALES` | `hu,en` | felület- és elemzésnyelvek; az első az alapértelmezett |
|
| `SUPPORTED_LOCALES` | `hu,en` | felület- és elemzésnyelvek; az első az alapértelmezett |
|
||||||
| `ANALYSIS_MODEL` | `anthropic/claude-opus-5.5` | ez írja a fizetős részletes elemzéseket |
|
| `ANALYSIS_MODEL` | `anthropic/claude-opus-5.5` | alapból ez írja a fizetős részletes elemzéseket (az admin felületen funkciónként felülírható) |
|
||||||
| `SUMMARY_MODEL` | `anthropic/claude-sonnet-5.5` | ez írja minden mentett képlet ingyenes rövid összefoglalóját (kb. 1 cent darabonként) |
|
| `SUMMARY_MODEL` | `anthropic/claude-sonnet-5.5` | alapból ez írja minden mentett képlet ingyenes rövid összefoglalóját (kb. 1 cent darabonként) |
|
||||||
| `ANALYSIS_PROMPT_VERSION` | `v2` | a prompt verziója (az elemzés-gyorsítótár kulcsának része) |
|
| `OPENROUTER_MODELS_URL` | `https://openrouter.ai/api/v1/models` | az admin modellválasztó listája árakkal (óránként egyszer kérdezi le) |
|
||||||
|
| `ANALYSIS_PROMPT_VERSION` | `v3` | a prompt verziója (az elemzés-gyorsítótár kulcsának része) |
|
||||||
| `MAX_CHARTS_PER_USER` | `1000` | biztonsági felső korlát a képletek számára |
|
| `MAX_CHARTS_PER_USER` | `1000` | biztonsági felső korlát a képletek számára |
|
||||||
| `BIND_ADDR`, `LOG_FORMAT`, `RUST_LOG` | `0.0.0.0:8081`, `text`, `info` | |
|
| `BIND_ADDR`, `LOG_FORMAT`, `RUST_LOG` | `0.0.0.0:8081`, `text`, `info` | |
|
||||||
|
|
||||||
@@ -124,7 +125,9 @@ Hibák formátuma: `{"error": {"code", "message"}}`. A születési adatok hibái
|
|||||||
|
|
||||||
- **Ingyenes rész:** minden mentett képlethez elkészül egy rövid összefoglaló (`summary`, `SUMMARY_MODEL`), ezért nem kell fizetni.
|
- **Ingyenes rész:** minden mentett képlethez elkészül egy rövid összefoglaló (`summary`, `SUMMARY_MODEL`), ezért nem kell fizetni.
|
||||||
- **Fizetős rész:** a részletes elemzés darabra megy. A képletelemzés egy `natal`, a szinasztria-elemzés egy `synastry` egységet von le (`credit_ledger.unit`). Az egységek csomagvásárlásból (Stripe, később) vagy admin jóváírásból jönnek. Havi ingyenes keret nincs.
|
- **Fizetős rész:** a részletes elemzés darabra megy. A képletelemzés egy `natal`, a szinasztria-elemzés egy `synastry` egységet von le (`credit_ledger.unit`). Az egységek csomagvásárlásból (Stripe, később) vagy admin jóváírásból jönnek. Havi ingyenes keret nincs.
|
||||||
- **Modell:** egyetlen, az `ANALYSIS_MODEL` (alapból Opus 5.5, a 2026-11-es összevetés legjobbja, lásd `services/worker/README.md`). A kliens nem választ modellt.
|
- **Modell:** funkciónként (összefoglaló, képletelemzés, kapcsolati elemzés, előrejelzés) az admin felületen választható az OpenRouter listájából (`model_settings` tábla); ha nincs beállítva, az `ANALYSIS_MODEL` / `SUMMARY_MODEL` (alapból Opus 5.5, a 2026-11-es összevetés legjobbja, lásd `services/worker/README.md`). Csak kötött JSON-választ adó modell választható. A kliens nem választ modellt, és a modell neve felhasználónak sehol nem jelenik meg.
|
||||||
|
- **Újragenerálás:** admin minden elemzést egyenként újraírathat (`POST /v1/admin/analyses/{id}/regenerate`): ugyanaz a sor (az azonosító és a megosztások maradnak), a jelenlegi prompttal és modellel, egységlevonás nélkül.
|
||||||
|
- **Újraszámolás:** számítási változás után a `backend recalculate` parancs minden mentett képletet, összevetést és előrejelzést újraszámol, majd minden elemzést újra sorba állít (egységlevonás nélkül).
|
||||||
- **Kérés:** a `POST .../analyses` (`{language?}`) létrehoz egy `pending` elemzést, és levon egy egységet; a szöveget a worker írja meg, általában 1–2 perc alatt. A kliens a `GET /v1/analyses/{id}` végponton kérdezi le az állapotát. Ha nincs egység, 402 `insufficient_credits` a válasz (`unit`, `balance` részletekkel). Hiba esetén a worker visszaadja az egységet.
|
- **Kérés:** a `POST .../analyses` (`{language?}`) létrehoz egy `pending` elemzést, és levon egy egységet; a szöveget a worker írja meg, általában 1–2 perc alatt. A kliens a `GET /v1/analyses/{id}` végponton kérdezi le az állapotát. Ha nincs egység, 402 `insufficient_credits` a válasz (`unit`, `balance` részletekkel). Hiba esetén a worker visszaadja az egységet.
|
||||||
- **Gyorsítótár:** a kulcs `sha256(típus | képlet- vagy szinasztria-hash | promptverzió | modell | nyelv)`.
|
- **Gyorsítótár:** a kulcs `sha256(típus | képlet- vagy szinasztria-hash | promptverzió | modell | nyelv)`.
|
||||||
- Ha ugyanarra a képletre már kértek ilyet, ugyanazt adja vissza (200).
|
- Ha ugyanarra a képletre már kértek ilyet, ugyanazt adja vissza (200).
|
||||||
|
|||||||
@@ -61,7 +61,10 @@ pub struct Config {
|
|||||||
/// `SUMMARY_MODEL`: writes the free short summary of every saved chart
|
/// `SUMMARY_MODEL`: writes the free short summary of every saved chart
|
||||||
/// (default `anthropic/claude-sonnet-5.5`, about 1 US cent each).
|
/// (default `anthropic/claude-sonnet-5.5`, about 1 US cent each).
|
||||||
pub summary_model: String,
|
pub summary_model: String,
|
||||||
/// `ANALYSIS_PROMPT_VERSION` (default `v2`); part of the analysis cache key.
|
/// `OPENROUTER_MODELS_URL` (default `https://openrouter.ai/api/v1/models`):
|
||||||
|
/// the model list with prices for the admin page.
|
||||||
|
pub openrouter_models_url: String,
|
||||||
|
/// `ANALYSIS_PROMPT_VERSION` (default `v3`); part of the analysis cache key.
|
||||||
pub prompt_version: String,
|
pub prompt_version: String,
|
||||||
/// `MAX_CHARTS_PER_USER` (default 1000): a safety cap.
|
/// `MAX_CHARTS_PER_USER` (default 1000): a safety cap.
|
||||||
pub max_charts_per_user: i64,
|
pub max_charts_per_user: i64,
|
||||||
@@ -121,7 +124,9 @@ impl Config {
|
|||||||
supported_locales,
|
supported_locales,
|
||||||
analysis_model: var("ANALYSIS_MODEL").unwrap_or_else(|| "anthropic/claude-opus-5.5".into()),
|
analysis_model: var("ANALYSIS_MODEL").unwrap_or_else(|| "anthropic/claude-opus-5.5".into()),
|
||||||
summary_model: var("SUMMARY_MODEL").unwrap_or_else(|| "anthropic/claude-sonnet-5.5".into()),
|
summary_model: var("SUMMARY_MODEL").unwrap_or_else(|| "anthropic/claude-sonnet-5.5".into()),
|
||||||
prompt_version: var("ANALYSIS_PROMPT_VERSION").unwrap_or_else(|| "v2".into()),
|
openrouter_models_url: var("OPENROUTER_MODELS_URL")
|
||||||
|
.unwrap_or_else(|| "https://openrouter.ai/api/v1/models".into()),
|
||||||
|
prompt_version: var("ANALYSIS_PROMPT_VERSION").unwrap_or_else(|| "v3".into()),
|
||||||
max_charts_per_user: parsed("MAX_CHARTS_PER_USER", 1000)?,
|
max_charts_per_user: parsed("MAX_CHARTS_PER_USER", 1000)?,
|
||||||
free_person_slots: parsed("FREE_PERSON_SLOTS", 0)?,
|
free_person_slots: parsed("FREE_PERSON_SLOTS", 0)?,
|
||||||
signup_mode: match var("SIGNUP_MODE").as_deref() {
|
signup_mode: match var("SIGNUP_MODE").as_deref() {
|
||||||
@@ -141,7 +146,7 @@ impl Config {
|
|||||||
pub fn for_tests(database_url: String, horoscope_api_url: String, google_jwks_url: String) -> Self {
|
pub fn for_tests(database_url: String, horoscope_api_url: String, google_jwks_url: String) -> Self {
|
||||||
Self {
|
Self {
|
||||||
database_url,
|
database_url,
|
||||||
horoscope_api_url,
|
horoscope_api_url: horoscope_api_url.clone(),
|
||||||
public_base_url: "https://sorsfonalak.test".into(),
|
public_base_url: "https://sorsfonalak.test".into(),
|
||||||
cors_allowed_origins: vec!["https://sorsfonalak.test".into()],
|
cors_allowed_origins: vec!["https://sorsfonalak.test".into()],
|
||||||
cookie_secure: true,
|
cookie_secure: true,
|
||||||
@@ -155,6 +160,7 @@ impl Config {
|
|||||||
supported_locales: vec!["hu".into(), "en".into()],
|
supported_locales: vec!["hu".into(), "en".into()],
|
||||||
analysis_model: "anthropic/claude-test".into(),
|
analysis_model: "anthropic/claude-test".into(),
|
||||||
summary_model: "anthropic/claude-summary".into(),
|
summary_model: "anthropic/claude-summary".into(),
|
||||||
|
openrouter_models_url: format!("{horoscope_api_url}/openrouter/models"),
|
||||||
prompt_version: "v1".into(),
|
prompt_version: "v1".into(),
|
||||||
max_charts_per_user: 50,
|
max_charts_per_user: 50,
|
||||||
free_person_slots: 5,
|
free_person_slots: 5,
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ mod config;
|
|||||||
mod credits;
|
mod credits;
|
||||||
mod error;
|
mod error;
|
||||||
mod google;
|
mod google;
|
||||||
|
mod models;
|
||||||
mod packages;
|
mod packages;
|
||||||
mod persons;
|
mod persons;
|
||||||
mod routes;
|
mod routes;
|
||||||
@@ -39,6 +40,7 @@ pub struct AppState {
|
|||||||
pub horoscope: HoroscopeClient,
|
pub horoscope: HoroscopeClient,
|
||||||
pub google: GoogleVerifier,
|
pub google: GoogleVerifier,
|
||||||
pub login_limiter: LoginLimiter,
|
pub login_limiter: LoginLimiter,
|
||||||
|
pub models: models::Catalog,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AppState {
|
impl AppState {
|
||||||
@@ -47,6 +49,7 @@ impl AppState {
|
|||||||
horoscope: HoroscopeClient::new(&config.horoscope_api_url),
|
horoscope: HoroscopeClient::new(&config.horoscope_api_url),
|
||||||
google: GoogleVerifier::new(config.google_client_ids.clone(), config.google_jwks_url.clone()),
|
google: GoogleVerifier::new(config.google_client_ids.clone(), config.google_jwks_url.clone()),
|
||||||
login_limiter: LoginLimiter::new(10, Duration::from_secs(15 * 60)),
|
login_limiter: LoginLimiter::new(10, Duration::from_secs(15 * 60)),
|
||||||
|
models: models::Catalog::new(&config.openrouter_models_url),
|
||||||
db,
|
db,
|
||||||
config,
|
config,
|
||||||
}
|
}
|
||||||
@@ -68,6 +71,9 @@ async fn main() -> anyhow::Result<()> {
|
|||||||
horoscope_api = %config.horoscope_api_url,
|
horoscope_api = %config.horoscope_api_url,
|
||||||
"database ready"
|
"database ready"
|
||||||
);
|
);
|
||||||
|
if std::env::args().nth(1).as_deref() == Some("recalculate") {
|
||||||
|
return routes::recalculate(&AppState::new(pool, config)).await;
|
||||||
|
}
|
||||||
let app = routes::router(Arc::new(AppState::new(pool, config)));
|
let app = routes::router(Arc::new(AppState::new(pool, config)));
|
||||||
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
|
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
|
||||||
tracing::info!(%addr, "listening");
|
tracing::info!(%addr, "listening");
|
||||||
|
|||||||
@@ -0,0 +1,117 @@
|
|||||||
|
//! Which model writes which kind of analysis, and the models OpenRouter
|
||||||
|
//! offers (with prices) for the admin page.
|
||||||
|
//!
|
||||||
|
//! The choice is in `model_settings`; without a row the configured default
|
||||||
|
//! is used (`SUMMARY_MODEL` for the short summary, `ANALYSIS_MODEL` else).
|
||||||
|
//! The model is never shown to users (a business secret).
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use analysis_prompt::Kind;
|
||||||
|
use serde::Serialize;
|
||||||
|
use serde_json::Value;
|
||||||
|
use tokio::sync::Mutex;
|
||||||
|
|
||||||
|
use crate::AppState;
|
||||||
|
|
||||||
|
/// The OpenRouter list is fetched at most this often.
|
||||||
|
const CATALOG_TTL: Duration = Duration::from_secs(3600);
|
||||||
|
|
||||||
|
/// The configured default model of a kind.
|
||||||
|
pub fn default_model(state: &AppState, kind: Kind) -> &str {
|
||||||
|
match kind {
|
||||||
|
Kind::Summary => &state.config.summary_model,
|
||||||
|
_ => &state.config.analysis_model,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The model new analyses of this kind are written with.
|
||||||
|
pub async fn model_for(state: &AppState, kind: Kind) -> Result<String, sqlx::Error> {
|
||||||
|
let chosen: Option<String> = sqlx::query_scalar("SELECT model FROM model_settings WHERE kind = $1")
|
||||||
|
.bind(kind.as_str())
|
||||||
|
.fetch_optional(&state.db)
|
||||||
|
.await?;
|
||||||
|
Ok(chosen.unwrap_or_else(|| default_model(state, kind).to_owned()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One model OpenRouter offers, with its price in USD per million tokens.
|
||||||
|
#[derive(Debug, Clone, Serialize)]
|
||||||
|
pub struct ModelInfo {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub input_per_million: f64,
|
||||||
|
pub output_per_million: f64,
|
||||||
|
pub context_length: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Catalog {
|
||||||
|
url: String,
|
||||||
|
http: reqwest::Client,
|
||||||
|
cache: Mutex<Option<(Instant, Arc<Vec<ModelInfo>>)>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Catalog {
|
||||||
|
pub fn new(url: &str) -> Self {
|
||||||
|
let http = reqwest::Client::builder().timeout(Duration::from_secs(15)).build().expect("static configuration");
|
||||||
|
Self { url: url.to_owned(), http, cache: Mutex::default() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The models that can write an analysis (they support the structured
|
||||||
|
/// output the worker asks for), by name; a stale list when OpenRouter is down.
|
||||||
|
pub async fn models(&self) -> Result<Arc<Vec<ModelInfo>>, String> {
|
||||||
|
let mut cache = self.cache.lock().await;
|
||||||
|
if let Some((at, list)) = cache.as_ref()
|
||||||
|
&& at.elapsed() < CATALOG_TTL
|
||||||
|
{
|
||||||
|
return Ok(list.clone());
|
||||||
|
}
|
||||||
|
match self.fetch().await {
|
||||||
|
Ok(list) => {
|
||||||
|
let list = Arc::new(list);
|
||||||
|
*cache = Some((Instant::now(), list.clone()));
|
||||||
|
Ok(list)
|
||||||
|
}
|
||||||
|
Err(e) => match cache.as_ref() {
|
||||||
|
Some((_, list)) => {
|
||||||
|
tracing::warn!(error = %e, "OpenRouter model list unavailable, using the cached one");
|
||||||
|
Ok(list.clone())
|
||||||
|
}
|
||||||
|
None => Err(e),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch(&self) -> Result<Vec<ModelInfo>, String> {
|
||||||
|
let body: Value = self
|
||||||
|
.http
|
||||||
|
.get(&self.url)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.and_then(reqwest::Response::error_for_status)
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
let price = |v: &Value| v.as_str().and_then(|s| s.parse::<f64>().ok()).map(|p| p * 1e6);
|
||||||
|
let mut list: Vec<ModelInfo> = body["data"]
|
||||||
|
.as_array()
|
||||||
|
.ok_or("unexpected OpenRouter answer")?
|
||||||
|
.iter()
|
||||||
|
.filter(|m| {
|
||||||
|
m["supported_parameters"].as_array().is_some_and(|p| p.iter().any(|x| x == "structured_outputs"))
|
||||||
|
})
|
||||||
|
.filter_map(|m| {
|
||||||
|
Some(ModelInfo {
|
||||||
|
id: m["id"].as_str()?.to_owned(),
|
||||||
|
name: m["name"].as_str().unwrap_or_default().to_owned(),
|
||||||
|
input_per_million: price(&m["pricing"]["prompt"])?,
|
||||||
|
output_per_million: price(&m["pricing"]["completion"])?,
|
||||||
|
context_length: m["context_length"].as_u64(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
list.sort_by(|a, b| a.name.cmp(&b.name));
|
||||||
|
Ok(list)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
//! Every saved chart also gets a free short summary (`summary` kind, written
|
//! Every saved chart also gets a free short summary (`summary` kind, written
|
||||||
//! by `SUMMARY_MODEL`); the detailed analyses are paid.
|
//! by `SUMMARY_MODEL`); the detailed analyses are paid.
|
||||||
|
|
||||||
|
use analysis_prompt::Kind;
|
||||||
use axum::Json;
|
use axum::Json;
|
||||||
use axum::body::Bytes;
|
use axum::body::Bytes;
|
||||||
use axum::extract::{Path, State};
|
use axum::extract::{Path, State};
|
||||||
@@ -113,7 +114,7 @@ fn optional_body(body: &[u8]) -> Result<AnalysisRequest, ApiError> {
|
|||||||
serde_json::from_slice(body).map_err(|e| ApiError::BadRequest(format!("invalid request body: {e}")))
|
serde_json::from_slice(body).map_err(|e| ApiError::BadRequest(format!("invalid request body: {e}")))
|
||||||
}
|
}
|
||||||
|
|
||||||
enum Target {
|
pub(super) enum Target {
|
||||||
Natal { chart_id: Uuid, hash: String },
|
Natal { chart_id: Uuid, hash: String },
|
||||||
Summary { chart_id: Uuid, hash: String },
|
Summary { chart_id: Uuid, hash: String },
|
||||||
Synastry { synastry_id: Uuid, hash: String },
|
Synastry { synastry_id: Uuid, hash: String },
|
||||||
@@ -135,20 +136,37 @@ async fn request(
|
|||||||
Target::Forecast { .. } => Some(Unit::Forecast),
|
Target::Forecast { .. } => Some(Unit::Forecast),
|
||||||
_ => Some(Unit::Natal),
|
_ => Some(Unit::Natal),
|
||||||
};
|
};
|
||||||
let model = state.config.analysis_model.clone();
|
let (status, row) = queue(state, auth.id(), &target, &language, unit).await?;
|
||||||
let (status, row) = queue(state, auth.id(), &target, &language, &model, unit).await?;
|
|
||||||
Ok((status, Json(row.view())))
|
Ok((status, Json(row.view())))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the existing analysis with the same cache key for this target,
|
/// Returns the existing analysis with the same cache key for this target,
|
||||||
/// copies a finished one from another chart with the same data, or queues a
|
/// copies a finished one from another chart with the same data, or queues a
|
||||||
/// new one (spending one `unit`, if given). 200, 201 and 202 respectively.
|
/// new one (spending one `unit`, if given). 200, 201 and 202 respectively.
|
||||||
async fn queue(
|
/// The cache key and the prompt version of a new analysis. The cache key leaves
|
||||||
|
/// out the admin-edited prompt revision, so a chart keeps its analysis when the
|
||||||
|
/// prompt changes; copying from another chart needs the same revision.
|
||||||
|
async fn versions(
|
||||||
|
state: &AppState,
|
||||||
|
kind: &str,
|
||||||
|
hash: &str,
|
||||||
|
model: &str,
|
||||||
|
language: &str,
|
||||||
|
) -> Result<(String, String), sqlx::Error> {
|
||||||
|
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(),
|
||||||
|
};
|
||||||
|
Ok((cache_key, prompt_version))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn queue(
|
||||||
state: &AppState,
|
state: &AppState,
|
||||||
user: Uuid,
|
user: Uuid,
|
||||||
target: &Target,
|
target: &Target,
|
||||||
language: &str,
|
language: &str,
|
||||||
model: &str,
|
|
||||||
unit: Option<Unit>,
|
unit: Option<Unit>,
|
||||||
) -> Result<(StatusCode, AnalysisRow), ApiError> {
|
) -> Result<(StatusCode, AnalysisRow), ApiError> {
|
||||||
let (kind, hash, chart_id, synastry_id, forecast_id) = match target {
|
let (kind, hash, chart_id, synastry_id, forecast_id) = match target {
|
||||||
@@ -157,14 +175,8 @@ async fn queue(
|
|||||||
Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id), None),
|
Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id), None),
|
||||||
Target::Forecast { forecast_id, hash } => ("forecast", hash, None, None, Some(*forecast_id)),
|
Target::Forecast { forecast_id, hash } => ("forecast", hash, None, None, Some(*forecast_id)),
|
||||||
};
|
};
|
||||||
// The cache key leaves out the admin-edited prompt revision, so a chart keeps
|
let model = &crate::models::model_for(state, Kind::parse(kind).expect("known kind")).await?;
|
||||||
// its analysis when the prompt changes; copying from another chart needs the same revision.
|
let (cache_key, prompt_version) = &versions(state, kind, hash, model, language).await?;
|
||||||
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!(
|
||||||
@@ -174,7 +186,7 @@ async fn queue(
|
|||||||
))
|
))
|
||||||
.bind(chart_id)
|
.bind(chart_id)
|
||||||
.bind(synastry_id)
|
.bind(synastry_id)
|
||||||
.bind(&cache_key)
|
.bind(cache_key)
|
||||||
.bind(forecast_id)
|
.bind(forecast_id)
|
||||||
.fetch_optional(&state.db)
|
.fetch_optional(&state.db)
|
||||||
.await?;
|
.await?;
|
||||||
@@ -195,7 +207,7 @@ async fn queue(
|
|||||||
"SELECT content, input_tokens, output_tokens FROM analyses \
|
"SELECT content, input_tokens, output_tokens FROM analyses \
|
||||||
WHERE cache_key = $1 AND prompt_version = $2 AND status = 'done' LIMIT 1",
|
WHERE cache_key = $1 AND prompt_version = $2 AND status = 'done' LIMIT 1",
|
||||||
)
|
)
|
||||||
.bind(&cache_key)
|
.bind(cache_key)
|
||||||
.bind(prompt_version)
|
.bind(prompt_version)
|
||||||
.fetch_optional(&state.db)
|
.fetch_optional(&state.db)
|
||||||
.await?;
|
.await?;
|
||||||
@@ -209,7 +221,7 @@ async fn queue(
|
|||||||
.bind(language)
|
.bind(language)
|
||||||
.bind(model)
|
.bind(model)
|
||||||
.bind(prompt_version)
|
.bind(prompt_version)
|
||||||
.bind(&cache_key)
|
.bind(cache_key)
|
||||||
.bind("done")
|
.bind("done")
|
||||||
.bind(content)
|
.bind(content)
|
||||||
.bind(input_tokens)
|
.bind(input_tokens)
|
||||||
@@ -233,7 +245,7 @@ async fn queue(
|
|||||||
.bind(language)
|
.bind(language)
|
||||||
.bind(model)
|
.bind(model)
|
||||||
.bind(prompt_version)
|
.bind(prompt_version)
|
||||||
.bind(&cache_key)
|
.bind(cache_key)
|
||||||
.bind("pending")
|
.bind("pending")
|
||||||
.bind(None::<Value>)
|
.bind(None::<Value>)
|
||||||
.bind(None::<i32>)
|
.bind(None::<i32>)
|
||||||
@@ -254,8 +266,7 @@ async fn queue(
|
|||||||
/// it does not exist yet or the last attempt failed.
|
/// it does not exist yet or the last attempt failed.
|
||||||
pub async fn ensure_summary(state: &AppState, owner: &AuthUser, chart: &ChartRow) -> Result<AnalysisRow, ApiError> {
|
pub async fn ensure_summary(state: &AppState, owner: &AuthUser, chart: &ChartRow) -> Result<AnalysisRow, ApiError> {
|
||||||
let target = Target::Summary { chart_id: chart.id, hash: chart.chart_hash.clone() };
|
let target = Target::Summary { chart_id: chart.id, hash: chart.chart_hash.clone() };
|
||||||
let model = state.config.summary_model.clone();
|
Ok(queue(state, owner.id(), &target, &owner.user.locale, None).await?.1)
|
||||||
Ok(queue(state, owner.id(), &target, &owner.user.locale, &model, None).await?.1)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn summary_for_chart(
|
pub async fn summary_for_chart(
|
||||||
@@ -345,3 +356,59 @@ pub async fn request_for_forecast(
|
|||||||
let req = optional_body(&body)?;
|
let req = optional_body(&body)?;
|
||||||
request(&state, &auth, Target::Forecast { forecast_id: forecast.id, hash: forecast.forecast_hash }, req).await
|
request(&state, &auth, Target::Forecast { forecast_id: forecast.id, hash: forecast.forecast_hash }, req).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Admin: writes an analysis again in place (same id, so links stay), with the
|
||||||
|
/// current prompt and model. Nobody is charged.
|
||||||
|
pub async fn regenerate(
|
||||||
|
State(state): St,
|
||||||
|
_admin: crate::auth::AdminUser,
|
||||||
|
WithRejection(Path(id), _): IdPath,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
let row = find_analysis(&state.db, id).await?.ok_or(ApiError::NotFound("analysis"))?;
|
||||||
|
if row.status == "pending" || row.status == "running" {
|
||||||
|
return Err(ApiError::conflict("analysis_in_progress", "Ez az elemzés éppen készül."));
|
||||||
|
}
|
||||||
|
let kind = Kind::parse(&row.kind).ok_or_else(|| ApiError::Internal(format!("unknown kind {}", row.kind)))?;
|
||||||
|
let hash: Option<String> = match kind {
|
||||||
|
Kind::Natal | Kind::Summary => {
|
||||||
|
sqlx::query_scalar("SELECT chart_hash FROM charts WHERE id = $1")
|
||||||
|
.bind(row.chart_id)
|
||||||
|
.fetch_optional(&state.db)
|
||||||
|
.await?
|
||||||
|
}
|
||||||
|
Kind::Synastry => {
|
||||||
|
sqlx::query_scalar("SELECT synastry_hash FROM synastries WHERE id = $1")
|
||||||
|
.bind(row.synastry_id)
|
||||||
|
.fetch_optional(&state.db)
|
||||||
|
.await?
|
||||||
|
}
|
||||||
|
Kind::Forecast => {
|
||||||
|
sqlx::query_scalar("SELECT forecast_hash FROM forecasts WHERE id = $1")
|
||||||
|
.bind(row.forecast_id)
|
||||||
|
.fetch_optional(&state.db)
|
||||||
|
.await?
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let hash = hash.ok_or(ApiError::NotFound("analysis"))?;
|
||||||
|
let model = crate::models::model_for(&state, kind).await?;
|
||||||
|
let (cache_key, prompt_version) = versions(&state, kind.as_str(), &hash, &model, &row.language).await?;
|
||||||
|
let mut tx = state.db.begin().await?;
|
||||||
|
let row: AnalysisRow = sqlx::query_as(&format!(
|
||||||
|
"UPDATE analyses SET status = 'pending', content = NULL, error = NULL, model_used = NULL, \
|
||||||
|
input_tokens = NULL, output_tokens = NULL, cost_usd = NULL, attempts = 0, next_attempt_at = now(), \
|
||||||
|
started_at = NULL, completed_at = NULL, model = $2, prompt_version = $3, cache_key = $4 \
|
||||||
|
WHERE id = $1 AND status IN ('done', 'failed') RETURNING {ANALYSIS_COLUMNS}"
|
||||||
|
))
|
||||||
|
.bind(id)
|
||||||
|
.bind(&model)
|
||||||
|
.bind(&prompt_version)
|
||||||
|
.bind(&cache_key)
|
||||||
|
.fetch_optional(&mut *tx)
|
||||||
|
.await?
|
||||||
|
.ok_or_else(|| ApiError::conflict("analysis_in_progress", "Ez az elemzés éppen készül."))?;
|
||||||
|
// Wakes the worker, as a new analysis does.
|
||||||
|
sqlx::query("SELECT pg_notify('analyses', '')").execute(&mut *tx).await?;
|
||||||
|
tx.commit().await?;
|
||||||
|
tracing::info!(%id, kind = kind.as_str(), "analysis regenerated");
|
||||||
|
Ok(Json(row.view()))
|
||||||
|
}
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ pub struct ChartRow {
|
|||||||
pub updated_at: OffsetDateTime,
|
pub updated_at: OffsetDateTime,
|
||||||
}
|
}
|
||||||
|
|
||||||
const CHART_COLUMNS: &str =
|
pub(super) const CHART_COLUMNS: &str =
|
||||||
"id, owner_id, label, is_primary, kind, birth_data, result, chart_hash, created_at, updated_at";
|
"id, owner_id, label, is_primary, kind, birth_data, result, chart_hash, created_at, updated_at";
|
||||||
|
|
||||||
impl ChartRow {
|
impl ChartRow {
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ use uuid::Uuid;
|
|||||||
|
|
||||||
use super::charts::{ChartRow, find_chart, owned_chart};
|
use super::charts::{ChartRow, find_chart, owned_chart};
|
||||||
use super::{Body, IdPath, St};
|
use super::{Body, IdPath, St};
|
||||||
|
use crate::AppState;
|
||||||
use crate::auth::AuthUser;
|
use crate::auth::AuthUser;
|
||||||
use crate::error::{ApiError, ApiResult};
|
use crate::error::{ApiError, ApiResult};
|
||||||
use crate::views::{rfc3339, sha256_hex};
|
use crate::views::{rfc3339, sha256_hex};
|
||||||
@@ -224,15 +225,7 @@ pub async fn create(
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut request = json!({ "birth": chart.birth_data, "year": year });
|
let (result, forecast_hash) = calculate(&state, &chart, year, location.as_ref(), &location_key).await?;
|
||||||
if let Some(l) = &location {
|
|
||||||
request["location"] = l.clone();
|
|
||||||
}
|
|
||||||
let mut result = state.horoscope.forecast(&request).await?;
|
|
||||||
if let Some(obj) = result.as_object_mut() {
|
|
||||||
obj.remove("meta");
|
|
||||||
}
|
|
||||||
let forecast_hash = forecast_hash(&chart.chart_hash, year, &location_key, &result);
|
|
||||||
let row: ForecastRow = sqlx::query_as(&format!(
|
let row: ForecastRow = sqlx::query_as(&format!(
|
||||||
"INSERT INTO forecasts (id, chart_id, chart_hash, year, location, location_key, result, forecast_hash, created_by) \
|
"INSERT INTO forecasts (id, chart_id, chart_hash, year, location, location_key, result, forecast_hash, created_by) \
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) \
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) \
|
||||||
@@ -253,6 +246,26 @@ pub async fn create(
|
|||||||
Ok((StatusCode::CREATED, Json(row.view())))
|
Ok((StatusCode::CREATED, Json(row.view())))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One year of a stored chart as stored: `(result, forecast_hash)`.
|
||||||
|
pub(super) async fn calculate(
|
||||||
|
state: &AppState,
|
||||||
|
chart: &ChartRow,
|
||||||
|
year: i32,
|
||||||
|
location: Option<&Value>,
|
||||||
|
location_key: &str,
|
||||||
|
) -> Result<(Value, String), ApiError> {
|
||||||
|
let mut request = json!({ "birth": chart.birth_data, "year": year });
|
||||||
|
if let Some(l) = location {
|
||||||
|
request["location"] = l.clone();
|
||||||
|
}
|
||||||
|
let mut result = state.horoscope.forecast(&request).await?;
|
||||||
|
if let Some(obj) = result.as_object_mut() {
|
||||||
|
obj.remove("meta");
|
||||||
|
}
|
||||||
|
let hash = forecast_hash(&chart.chart_hash, year, location_key, &result);
|
||||||
|
Ok((result, hash))
|
||||||
|
}
|
||||||
|
|
||||||
/// Identifies a forecast independently of how the place was entered: the
|
/// Identifies a forecast independently of how the place was entered: the
|
||||||
/// chart, the year and the resolved place and time zone of the solar return.
|
/// chart, the year and the resolved place and time zone of the solar return.
|
||||||
fn forecast_hash(chart_hash: &str, year: i32, location_key: &str, result: &Value) -> String {
|
fn forecast_hash(chart_hash: &str, year: i32, location_key: &str, result: &Value) -> String {
|
||||||
|
|||||||
@@ -12,11 +12,15 @@ mod auth;
|
|||||||
mod charts;
|
mod charts;
|
||||||
mod forecasts;
|
mod forecasts;
|
||||||
mod invitations;
|
mod invitations;
|
||||||
|
mod models;
|
||||||
mod payments;
|
mod payments;
|
||||||
mod prompts;
|
mod prompts;
|
||||||
|
mod recalculate;
|
||||||
mod shares;
|
mod shares;
|
||||||
mod synastries;
|
mod synastries;
|
||||||
|
|
||||||
|
pub use recalculate::run as recalculate;
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use axum::extract::{Path, State};
|
use axum::extract::{Path, State};
|
||||||
@@ -109,6 +113,10 @@ pub fn router(state: Arc<AppState>) -> Router {
|
|||||||
.route("/v1/admin/prompts/{kind}/{language}", axum::routing::put(prompts::save))
|
.route("/v1/admin/prompts/{kind}/{language}", axum::routing::put(prompts::save))
|
||||||
.route("/v1/admin/prompts/{kind}/{language}/preview", post(prompts::start_preview))
|
.route("/v1/admin/prompts/{kind}/{language}/preview", post(prompts::start_preview))
|
||||||
.route("/v1/admin/previews/{id}", get(prompts::get_preview))
|
.route("/v1/admin/previews/{id}", get(prompts::get_preview))
|
||||||
|
.route("/v1/admin/models", get(models::list))
|
||||||
|
.route("/v1/admin/models/catalog", get(models::catalog))
|
||||||
|
.route("/v1/admin/models/{kind}", axum::routing::put(models::save))
|
||||||
|
.route("/v1/admin/analyses/{id}/regenerate", post(analyses::regenerate))
|
||||||
.layer(cors(&state.config.cors_allowed_origins))
|
.layer(cors(&state.config.cors_allowed_origins))
|
||||||
.layer(
|
.layer(
|
||||||
TraceLayer::new_for_http()
|
TraceLayer::new_for_http()
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
//! Admin: which model writes which kind of analysis, chosen from the models
|
||||||
|
//! OpenRouter offers. A change applies to analyses requested after it.
|
||||||
|
|
||||||
|
use analysis_prompt::Kind;
|
||||||
|
use axum::Json;
|
||||||
|
use axum::extract::{Path, State};
|
||||||
|
use axum_extra::extract::WithRejection;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
|
||||||
|
use super::{Body, St};
|
||||||
|
use crate::AppState;
|
||||||
|
use crate::auth::AdminUser;
|
||||||
|
use crate::error::{ApiError, ApiResult};
|
||||||
|
use crate::models::default_model;
|
||||||
|
use crate::views::rfc3339;
|
||||||
|
|
||||||
|
fn catalog_error(e: String) -> ApiError {
|
||||||
|
ApiError::Conflict {
|
||||||
|
code: "model_list_unavailable",
|
||||||
|
message: format!("Az OpenRouter modell-listája most nem érhető el: {e}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn entry(state: &AppState, kind: Kind) -> Result<Value, sqlx::Error> {
|
||||||
|
let chosen: Option<(String, OffsetDateTime, Option<String>)> = sqlx::query_as(
|
||||||
|
"SELECT m.model, m.updated_at, u.email FROM model_settings m LEFT JOIN users u ON u.id = m.updated_by \
|
||||||
|
WHERE m.kind = $1",
|
||||||
|
)
|
||||||
|
.bind(kind.as_str())
|
||||||
|
.fetch_optional(&state.db)
|
||||||
|
.await?;
|
||||||
|
// Typical size of this kind of analysis, from the latest ones: for the cost estimate.
|
||||||
|
let (input, output, samples): (Option<f64>, Option<f64>, i64) = sqlx::query_as(
|
||||||
|
"SELECT avg(input_tokens)::float8, avg(output_tokens)::float8, count(*) FROM ( \
|
||||||
|
SELECT input_tokens, output_tokens FROM analyses \
|
||||||
|
WHERE kind = $1 AND status = 'done' AND input_tokens IS NOT NULL AND output_tokens IS NOT NULL \
|
||||||
|
ORDER BY completed_at DESC LIMIT 50) recent",
|
||||||
|
)
|
||||||
|
.bind(kind.as_str())
|
||||||
|
.fetch_one(&state.db)
|
||||||
|
.await?;
|
||||||
|
let default = default_model(state, kind);
|
||||||
|
Ok(json!({
|
||||||
|
"kind": kind.as_str(),
|
||||||
|
"model": chosen.as_ref().map_or(default, |c| c.0.as_str()),
|
||||||
|
"default": default,
|
||||||
|
"custom": chosen.is_some(),
|
||||||
|
"updated_at": chosen.as_ref().map(|c| rfc3339(c.1)),
|
||||||
|
"updated_by": chosen.as_ref().and_then(|c| c.2.clone()),
|
||||||
|
"avg_input_tokens": input,
|
||||||
|
"avg_output_tokens": output,
|
||||||
|
"samples": samples,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult<Json<Value>> {
|
||||||
|
let mut functions = Vec::new();
|
||||||
|
for kind in Kind::ALL {
|
||||||
|
functions.push(entry(&state, kind).await?);
|
||||||
|
}
|
||||||
|
Ok(Json(json!({ "functions": functions })))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn catalog(State(state): St, _admin: AdminUser) -> ApiResult<Json<Value>> {
|
||||||
|
let models = state.models.models().await.map_err(catalog_error)?;
|
||||||
|
Ok(Json(json!({ "models": *models })))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct SaveModel {
|
||||||
|
/// An OpenRouter model id; `null` restores the default.
|
||||||
|
model: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn save(
|
||||||
|
State(state): St,
|
||||||
|
AdminUser(admin): AdminUser,
|
||||||
|
WithRejection(Path(kind), _): WithRejection<Path<String>, ApiError>,
|
||||||
|
WithRejection(Json(req), _): Body<SaveModel>,
|
||||||
|
) -> ApiResult<Json<Value>> {
|
||||||
|
let kind = Kind::parse(&kind).ok_or(ApiError::NotFound("function"))?;
|
||||||
|
match req.model.as_deref().map(str::trim) {
|
||||||
|
Some(model) if model != default_model(&state, kind) => {
|
||||||
|
let models = state.models.models().await.map_err(catalog_error)?;
|
||||||
|
if !models.iter().any(|m| m.id == model) {
|
||||||
|
return Err(ApiError::BadRequest(format!(
|
||||||
|
"unknown model, or it cannot give structured answers: {model}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
sqlx::query(
|
||||||
|
"INSERT INTO model_settings (kind, model, updated_by) VALUES ($1, $2, $3) \
|
||||||
|
ON CONFLICT (kind) DO UPDATE SET model = EXCLUDED.model, updated_by = EXCLUDED.updated_by, \
|
||||||
|
updated_at = now()",
|
||||||
|
)
|
||||||
|
.bind(kind.as_str())
|
||||||
|
.bind(model)
|
||||||
|
.bind(admin.id())
|
||||||
|
.execute(&state.db)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
sqlx::query("DELETE FROM model_settings WHERE kind = $1").bind(kind.as_str()).execute(&state.db).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tracing::info!(admin = %admin.id(), kind = kind.as_str(), "analysis model changed");
|
||||||
|
Ok(Json(entry(&state, kind).await?))
|
||||||
|
}
|
||||||
@@ -27,7 +27,7 @@ use crate::error::{ApiError, ApiResult};
|
|||||||
use crate::views::{rfc3339, rfc3339_opt};
|
use crate::views::{rfc3339, rfc3339_opt};
|
||||||
|
|
||||||
/// The kinds whose prompt the admin page edits.
|
/// The kinds whose prompt the admin page edits.
|
||||||
const EDITABLE: [Kind; 3] = [Kind::Summary, Kind::Natal, Kind::Synastry];
|
const EDITABLE: [Kind; 4] = [Kind::Summary, Kind::Natal, Kind::Synastry, Kind::Forecast];
|
||||||
const MAX_CHARS: usize = 50_000;
|
const MAX_CHARS: usize = 50_000;
|
||||||
const HISTORY: i64 = 20;
|
const HISTORY: i64 = 20;
|
||||||
/// Test runs of one admin waiting or being written at the same time.
|
/// Test runs of one admin waiting or being written at the same time.
|
||||||
@@ -162,6 +162,8 @@ pub struct StartPreview {
|
|||||||
chart_id: Option<Uuid>,
|
chart_id: Option<Uuid>,
|
||||||
/// One of the admin's own comparisons, for a synastry analysis.
|
/// One of the admin's own comparisons, for a synastry analysis.
|
||||||
synastry_id: Option<Uuid>,
|
synastry_id: Option<Uuid>,
|
||||||
|
/// A yearly forecast of one of the admin's own charts, for a forecast analysis.
|
||||||
|
forecast_id: Option<Uuid>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(sqlx::FromRow)]
|
#[derive(sqlx::FromRow)]
|
||||||
@@ -170,6 +172,7 @@ struct PreviewRow {
|
|||||||
kind: String,
|
kind: String,
|
||||||
chart_id: Option<Uuid>,
|
chart_id: Option<Uuid>,
|
||||||
synastry_id: Option<Uuid>,
|
synastry_id: Option<Uuid>,
|
||||||
|
forecast_id: Option<Uuid>,
|
||||||
language: String,
|
language: String,
|
||||||
model: String,
|
model: String,
|
||||||
status: String,
|
status: String,
|
||||||
@@ -184,7 +187,7 @@ struct PreviewRow {
|
|||||||
completed_at: Option<OffsetDateTime>,
|
completed_at: Option<OffsetDateTime>,
|
||||||
}
|
}
|
||||||
|
|
||||||
const PREVIEW_COLUMNS: &str = "id, kind, chart_id, synastry_id, language, model, status, content, error, model_used, \
|
const PREVIEW_COLUMNS: &str = "id, kind, chart_id, synastry_id, forecast_id, language, model, status, content, error, model_used, \
|
||||||
input_tokens, output_tokens, cost_usd, created_at, started_at, completed_at";
|
input_tokens, output_tokens, cost_usd, created_at, started_at, completed_at";
|
||||||
|
|
||||||
impl PreviewRow {
|
impl PreviewRow {
|
||||||
@@ -192,6 +195,7 @@ impl PreviewRow {
|
|||||||
let seconds = self.started_at.zip(self.completed_at).map(|(s, c)| (c - s).whole_seconds());
|
let seconds = self.started_at.zip(self.completed_at).map(|(s, c)| (c - s).whole_seconds());
|
||||||
json!({
|
json!({
|
||||||
"id": self.id, "kind": self.kind, "chart_id": self.chart_id, "synastry_id": self.synastry_id,
|
"id": self.id, "kind": self.kind, "chart_id": self.chart_id, "synastry_id": self.synastry_id,
|
||||||
|
"forecast_id": self.forecast_id,
|
||||||
"language": self.language, "model": self.model, "status": self.status, "content": self.content,
|
"language": self.language, "model": self.model, "status": self.status, "content": self.content,
|
||||||
"error": self.error, "model_used": self.model_used, "input_tokens": self.input_tokens,
|
"error": self.error, "model_used": self.model_used, "input_tokens": self.input_tokens,
|
||||||
"output_tokens": self.output_tokens, "cost_usd": self.cost_usd, "created_at": rfc3339(self.created_at),
|
"output_tokens": self.output_tokens, "cost_usd": self.cost_usd, "created_at": rfc3339(self.created_at),
|
||||||
@@ -208,29 +212,27 @@ pub async fn start_preview(
|
|||||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||||
let kind = parse_target(&state, &kind, &language)?;
|
let kind = parse_target(&state, &kind, &language)?;
|
||||||
let system = clean_system(&req.system)?;
|
let system = clean_system(&req.system)?;
|
||||||
// The target must be the admin's own: a chart, or for a synastry analysis a comparison.
|
// The target must be the admin's own: a chart, a comparison or a forecast.
|
||||||
let (chart_id, synastry_id, found) = match (kind, req.chart_id, req.synastry_id) {
|
let (chart_id, synastry_id, forecast_id) = (req.chart_id, req.synastry_id, req.forecast_id);
|
||||||
(Kind::Synastry, None, Some(id)) => {
|
let (query, id, what) = match (kind, chart_id, synastry_id, forecast_id) {
|
||||||
let row: Option<(Uuid,)> = sqlx::query_as("SELECT id FROM synastries WHERE id = $1 AND owner_id = $2")
|
(Kind::Summary | Kind::Natal, Some(id), None, None) => {
|
||||||
.bind(id)
|
("SELECT id FROM charts WHERE id = $1 AND owner_id = $2", id, "chart")
|
||||||
.bind(admin.id())
|
|
||||||
.fetch_optional(&state.db)
|
|
||||||
.await?;
|
|
||||||
(None, Some(id), row.map(|_| "synastry"))
|
|
||||||
}
|
}
|
||||||
(Kind::Summary | Kind::Natal, Some(id), None) => {
|
(Kind::Synastry, None, Some(id), None) => {
|
||||||
let row: Option<(Uuid,)> = sqlx::query_as("SELECT id FROM charts WHERE id = $1 AND owner_id = $2")
|
("SELECT id FROM synastries WHERE id = $1 AND owner_id = $2", id, "synastry")
|
||||||
.bind(id)
|
|
||||||
.bind(admin.id())
|
|
||||||
.fetch_optional(&state.db)
|
|
||||||
.await?;
|
|
||||||
(Some(id), None, row.map(|_| "chart"))
|
|
||||||
}
|
}
|
||||||
|
(Kind::Forecast, None, None, Some(id)) => (
|
||||||
|
"SELECT f.id FROM forecasts f JOIN charts c ON c.id = f.chart_id WHERE f.id = $1 AND c.owner_id = $2",
|
||||||
|
id,
|
||||||
|
"forecast",
|
||||||
|
),
|
||||||
(Kind::Synastry, ..) => return Err(ApiError::BadRequest("a synastry analysis needs synastry_id".into())),
|
(Kind::Synastry, ..) => return Err(ApiError::BadRequest("a synastry analysis needs synastry_id".into())),
|
||||||
|
(Kind::Forecast, ..) => return Err(ApiError::BadRequest("a forecast analysis needs forecast_id".into())),
|
||||||
_ => return Err(ApiError::BadRequest("this analysis needs chart_id".into())),
|
_ => return Err(ApiError::BadRequest("this analysis needs chart_id".into())),
|
||||||
};
|
};
|
||||||
|
let found: Option<(Uuid,)> = sqlx::query_as(query).bind(id).bind(admin.id()).fetch_optional(&state.db).await?;
|
||||||
if found.is_none() {
|
if found.is_none() {
|
||||||
return Err(ApiError::NotFound(if synastry_id.is_some() { "synastry" } else { "chart" }));
|
return Err(ApiError::NotFound(what));
|
||||||
}
|
}
|
||||||
let (open,): (i64,) = sqlx::query_as(
|
let (open,): (i64,) = sqlx::query_as(
|
||||||
"SELECT count(*) FROM prompt_previews WHERE created_by = $1 AND status IN ('pending', 'running')",
|
"SELECT count(*) FROM prompt_previews WHERE created_by = $1 AND status IN ('pending', 'running')",
|
||||||
@@ -244,18 +246,16 @@ pub async fn start_preview(
|
|||||||
"Egyszerre legfeljebb három próba futhat. Várd meg, amíg valamelyik elkészül.",
|
"Egyszerre legfeljebb három próba futhat. Várd meg, amíg valamelyik elkészül.",
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let model = match kind {
|
let model = &crate::models::model_for(&state, kind).await?;
|
||||||
Kind::Summary => &state.config.summary_model,
|
|
||||||
_ => &state.config.analysis_model,
|
|
||||||
};
|
|
||||||
let row: PreviewRow = sqlx::query_as(&format!(
|
let row: PreviewRow = sqlx::query_as(&format!(
|
||||||
"INSERT INTO prompt_previews (id, kind, chart_id, synastry_id, language, model, system, created_by) \
|
"INSERT INTO prompt_previews (id, kind, chart_id, synastry_id, forecast_id, language, model, system, created_by) \
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING {PREVIEW_COLUMNS}"
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING {PREVIEW_COLUMNS}"
|
||||||
))
|
))
|
||||||
.bind(Uuid::now_v7())
|
.bind(Uuid::now_v7())
|
||||||
.bind(kind.as_str())
|
.bind(kind.as_str())
|
||||||
.bind(chart_id)
|
.bind(chart_id)
|
||||||
.bind(synastry_id)
|
.bind(synastry_id)
|
||||||
|
.bind(forecast_id)
|
||||||
.bind(&language)
|
.bind(&language)
|
||||||
.bind(model)
|
.bind(model)
|
||||||
.bind(&system)
|
.bind(&system)
|
||||||
|
|||||||
@@ -0,0 +1,115 @@
|
|||||||
|
//! `backend recalculate`: after a change in the calculation, recalculates
|
||||||
|
//! every stored chart, comparison and forecast with the horoscope service,
|
||||||
|
//! then deletes all analyses and queues them again: a short summary and a
|
||||||
|
//! detailed analysis for every chart, one analysis for every comparison and
|
||||||
|
//! every forecast. Nobody is charged; each analysis is requested in the name
|
||||||
|
//! of the owner, in the owner's language.
|
||||||
|
|
||||||
|
use anyhow::Context;
|
||||||
|
use serde_json::Value;
|
||||||
|
use sqlx::PgPool;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use super::analyses::{Target, queue};
|
||||||
|
use super::charts::{CHART_COLUMNS, ChartRow};
|
||||||
|
use crate::AppState;
|
||||||
|
|
||||||
|
async fn all_charts(db: &PgPool) -> Result<Vec<ChartRow>, sqlx::Error> {
|
||||||
|
sqlx::query_as(&format!("SELECT {CHART_COLUMNS} FROM charts ORDER BY created_at")).fetch_all(db).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn locale(db: &PgPool, user: Uuid) -> Result<String, sqlx::Error> {
|
||||||
|
sqlx::query_scalar("SELECT locale FROM users WHERE id = $1").bind(user).fetch_one(db).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn run(state: &AppState) -> anyhow::Result<()> {
|
||||||
|
let db = &state.db;
|
||||||
|
|
||||||
|
let charts = all_charts(db).await?;
|
||||||
|
for chart in &charts {
|
||||||
|
let (_, result, hash) = super::charts::calculate(state, chart.birth_data.clone())
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("chart {}: {e:?}", chart.id))?;
|
||||||
|
sqlx::query("UPDATE charts SET result = $1, chart_hash = $2 WHERE id = $3")
|
||||||
|
.bind(&result)
|
||||||
|
.bind(&hash)
|
||||||
|
.bind(chart.id)
|
||||||
|
.execute(db)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
tracing::info!(count = charts.len(), "charts recalculated");
|
||||||
|
let charts = all_charts(db).await?;
|
||||||
|
let chart = |id: Uuid| charts.iter().find(|c| c.id == id).context("missing chart");
|
||||||
|
|
||||||
|
let synastries: Vec<(Uuid, Uuid, Uuid, Uuid)> =
|
||||||
|
sqlx::query_as("SELECT id, owner_id, chart1_id, chart2_id FROM synastries ORDER BY created_at")
|
||||||
|
.fetch_all(db)
|
||||||
|
.await?;
|
||||||
|
let mut synastry_hashes = Vec::new();
|
||||||
|
for &(id, owner, chart1, chart2) in &synastries {
|
||||||
|
let (result, hash) = super::synastries::calculate(state, chart(chart1)?, chart(chart2)?)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("synastry {id}: {e:?}"))?;
|
||||||
|
sqlx::query("UPDATE synastries SET result = $1, synastry_hash = $2 WHERE id = $3")
|
||||||
|
.bind(&result)
|
||||||
|
.bind(&hash)
|
||||||
|
.bind(id)
|
||||||
|
.execute(db)
|
||||||
|
.await?;
|
||||||
|
synastry_hashes.push((id, owner, hash));
|
||||||
|
}
|
||||||
|
tracing::info!(count = synastries.len(), "comparisons recalculated");
|
||||||
|
|
||||||
|
let forecasts: Vec<(Uuid, Uuid, i32, Option<Value>, String)> =
|
||||||
|
sqlx::query_as("SELECT id, chart_id, year, location, location_key FROM forecasts ORDER BY created_at")
|
||||||
|
.fetch_all(db)
|
||||||
|
.await?;
|
||||||
|
let mut forecast_hashes = Vec::new();
|
||||||
|
for (id, chart_id, year, location, location_key) in &forecasts {
|
||||||
|
let c = chart(*chart_id)?;
|
||||||
|
let (result, hash) = super::forecasts::calculate(state, c, *year, location.as_ref(), location_key)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("forecast {id}: {e:?}"))?;
|
||||||
|
let updated =
|
||||||
|
sqlx::query("UPDATE forecasts SET chart_hash = $1, result = $2, forecast_hash = $3 WHERE id = $4")
|
||||||
|
.bind(&c.chart_hash)
|
||||||
|
.bind(&result)
|
||||||
|
.bind(&hash)
|
||||||
|
.bind(id)
|
||||||
|
.execute(db)
|
||||||
|
.await;
|
||||||
|
match updated {
|
||||||
|
Ok(_) => forecast_hashes.push((*id, c.owner_id, hash)),
|
||||||
|
// The same year and place from an earlier version of the birth data: a duplicate now.
|
||||||
|
Err(sqlx::Error::Database(e)) if e.is_unique_violation() => {
|
||||||
|
sqlx::query("DELETE FROM forecasts WHERE id = $1").bind(id).execute(db).await?;
|
||||||
|
tracing::warn!(%id, "duplicate forecast removed");
|
||||||
|
}
|
||||||
|
Err(e) => return Err(e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tracing::info!(count = forecast_hashes.len(), "forecasts recalculated");
|
||||||
|
|
||||||
|
let deleted = sqlx::query("DELETE FROM analyses").execute(db).await?.rows_affected();
|
||||||
|
let mut queued = 0;
|
||||||
|
for c in &charts {
|
||||||
|
let language = locale(db, c.owner_id).await?;
|
||||||
|
let summary = Target::Summary { chart_id: c.id, hash: c.chart_hash.clone() };
|
||||||
|
queue(state, c.owner_id, &summary, &language, None).await?;
|
||||||
|
let natal = Target::Natal { chart_id: c.id, hash: c.chart_hash.clone() };
|
||||||
|
queue(state, c.owner_id, &natal, &language, None).await?;
|
||||||
|
queued += 2;
|
||||||
|
}
|
||||||
|
for (synastry_id, owner, hash) in synastry_hashes {
|
||||||
|
let target = Target::Synastry { synastry_id, hash };
|
||||||
|
queue(state, owner, &target, &locale(db, owner).await?, None).await?;
|
||||||
|
queued += 1;
|
||||||
|
}
|
||||||
|
for (forecast_id, owner, hash) in forecast_hashes {
|
||||||
|
let target = Target::Forecast { forecast_id, hash };
|
||||||
|
queue(state, owner, &target, &locale(db, owner).await?, None).await?;
|
||||||
|
queued += 1;
|
||||||
|
}
|
||||||
|
tracing::info!(deleted, queued, "analyses queued again");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -108,6 +108,23 @@ fn without(value: &Value, keys: &[&str]) -> Value {
|
|||||||
Value::Object(map)
|
Value::Object(map)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The comparison of two stored charts as stored: `(result, synastry_hash)`.
|
||||||
|
pub(super) async fn calculate(
|
||||||
|
state: &AppState,
|
||||||
|
chart1: &ChartRow,
|
||||||
|
chart2: &ChartRow,
|
||||||
|
) -> Result<(Value, String), ApiError> {
|
||||||
|
let request = json!({
|
||||||
|
"person1": without(&chart1.birth_data, &["options"]),
|
||||||
|
"person2": without(&chart2.birth_data, &["options"]),
|
||||||
|
"options": chart1.birth_data.get("options").cloned().unwrap_or_else(|| json!({})),
|
||||||
|
});
|
||||||
|
let response = state.horoscope.synastry(&request).await?;
|
||||||
|
let result = without(&response, &["person1", "person2", "meta"]);
|
||||||
|
let hash = synastry_hash(&chart1.chart_hash, &chart2.chart_hash, &result["settings"]);
|
||||||
|
Ok((result, hash))
|
||||||
|
}
|
||||||
|
|
||||||
/// Returns the synastry of the two charts, calculating and storing it when
|
/// Returns the synastry of the two charts, calculating and storing it when
|
||||||
/// it does not exist yet (in either order). `bool` = newly created.
|
/// it does not exist yet (in either order). `bool` = newly created.
|
||||||
pub async fn compute_synastry(
|
pub async fn compute_synastry(
|
||||||
@@ -130,14 +147,7 @@ pub async fn compute_synastry(
|
|||||||
return Ok((row, false));
|
return Ok((row, false));
|
||||||
}
|
}
|
||||||
|
|
||||||
let request = json!({
|
let (result, hash) = calculate(state, chart1, chart2).await?;
|
||||||
"person1": without(&chart1.birth_data, &["options"]),
|
|
||||||
"person2": without(&chart2.birth_data, &["options"]),
|
|
||||||
"options": chart1.birth_data.get("options").cloned().unwrap_or_else(|| json!({})),
|
|
||||||
});
|
|
||||||
let response = state.horoscope.synastry(&request).await?;
|
|
||||||
let result = without(&response, &["person1", "person2", "meta"]);
|
|
||||||
let hash = synastry_hash(&chart1.chart_hash, &chart2.chart_hash, &result["settings"]);
|
|
||||||
|
|
||||||
let inserted: Option<SynastryRow> = sqlx::query_as(&format!(
|
let inserted: Option<SynastryRow> = sqlx::query_as(&format!(
|
||||||
"INSERT INTO synastries (id, owner_id, chart1_id, chart2_id, result, synastry_hash) \
|
"INSERT INTO synastries (id, owner_id, chart1_id, chart2_id, result, synastry_hash) \
|
||||||
|
|||||||
@@ -96,8 +96,24 @@ async fn fake_jwks() -> Json<Value> {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn fake_openrouter_models() -> Json<Value> {
|
||||||
|
let model = |id: &str, name: &str, structured: bool| {
|
||||||
|
json!({
|
||||||
|
"id": id, "name": name, "context_length": 200000,
|
||||||
|
"pricing": {"prompt": "0.000003", "completion": "0.000015"},
|
||||||
|
"supported_parameters": if structured { json!(["tools", "structured_outputs"]) } else { json!(["tools"]) },
|
||||||
|
})
|
||||||
|
};
|
||||||
|
Json(json!({"data": [
|
||||||
|
model("anthropic/claude-test", "Claude Test", true),
|
||||||
|
model("vendor/plain", "Plain (no JSON)", false),
|
||||||
|
model("openai/gpt-x", "GPT X", true),
|
||||||
|
]}))
|
||||||
|
}
|
||||||
|
|
||||||
async fn fake_services() -> String {
|
async fn fake_services() -> String {
|
||||||
let app = Router::new()
|
let app = Router::new()
|
||||||
|
.route("/openrouter/models", get(fake_openrouter_models))
|
||||||
.route("/v1/natal", post(fake_natal))
|
.route("/v1/natal", post(fake_natal))
|
||||||
.route("/v1/synastry", post(fake_synastry))
|
.route("/v1/synastry", post(fake_synastry))
|
||||||
.route("/v1/forecast", post(fake_forecast))
|
.route("/v1/forecast", post(fake_forecast))
|
||||||
@@ -124,6 +140,7 @@ fn google_token(sub: &str, email: &str, audience: &str) -> String {
|
|||||||
struct TestApp {
|
struct TestApp {
|
||||||
router: Router,
|
router: Router,
|
||||||
pool: PgPool,
|
pool: PgPool,
|
||||||
|
state: Arc<AppState>,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Response {
|
struct Response {
|
||||||
@@ -141,7 +158,8 @@ impl TestApp {
|
|||||||
let fake = fake_services().await;
|
let fake = fake_services().await;
|
||||||
let mut config = Config::for_tests(String::new(), fake.clone(), format!("{fake}/jwks"));
|
let mut config = Config::for_tests(String::new(), fake.clone(), format!("{fake}/jwks"));
|
||||||
change(&mut config);
|
change(&mut config);
|
||||||
Self { router: routes::router(Arc::new(AppState::new(pool.clone(), config))), pool }
|
let state = Arc::new(AppState::new(pool.clone(), config));
|
||||||
|
Self { router: routes::router(state.clone()), pool, state }
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn call(&self, method: &str, uri: &str, token: Option<&str>, body: Option<Value>) -> Response {
|
async fn call(&self, method: &str, uri: &str, token: Option<&str>, body: Option<Value>) -> Response {
|
||||||
@@ -929,7 +947,8 @@ async fn admins_edit_analysis_prompts(pool: PgPool) {
|
|||||||
let prompts = r.body["prompts"].as_array().unwrap();
|
let prompts = r.body["prompts"].as_array().unwrap();
|
||||||
let keys: Vec<String> =
|
let keys: Vec<String> =
|
||||||
prompts.iter().map(|p| format!("{}/{}", p["kind"], p["language"]).replace('"', "")).collect();
|
prompts.iter().map(|p| format!("{}/{}", p["kind"], p["language"]).replace('"', "")).collect();
|
||||||
assert_eq!(keys, ["summary/hu", "summary/en", "natal/hu", "natal/en", "synastry/hu", "synastry/en"]);
|
let expected = ["summary", "natal", "synastry", "forecast"].map(|k| [format!("{k}/hu"), format!("{k}/en")]);
|
||||||
|
assert_eq!(keys, expected.concat());
|
||||||
let natal = &prompts[2];
|
let natal = &prompts[2];
|
||||||
assert_eq!((&natal["custom"], &natal["system"]), (&json!(false), &natal["default"]));
|
assert_eq!((&natal["custom"], &natal["system"]), (&json!(false), &natal["default"]));
|
||||||
assert!(natal["user_template"].as_str().unwrap().contains("{chart data}"));
|
assert!(natal["user_template"].as_str().unwrap().contains("{chart data}"));
|
||||||
@@ -1048,6 +1067,32 @@ async fn admins_try_prompt_drafts_on_own_charts(pool: PgPool) {
|
|||||||
"{}",
|
"{}",
|
||||||
r.body
|
r.body
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// a yearly forecast is tried on a forecast of one of the admin's charts
|
||||||
|
sqlx::query("UPDATE prompt_previews SET status = 'done'").execute(&pool).await.unwrap();
|
||||||
|
let own_id = own["id"].as_str().unwrap();
|
||||||
|
let forecast = app.post(&format!("/v1/charts/{own_id}/forecasts"), Some(&admin), json!({})).await;
|
||||||
|
assert_eq!(forecast.status, StatusCode::CREATED, "{}", forecast.body);
|
||||||
|
let annas_id = annas["id"].as_str().unwrap();
|
||||||
|
let annas_forecast = app.post(&format!("/v1/charts/{annas_id}/forecasts"), Some(&anna), json!({})).await;
|
||||||
|
let uri = "/v1/admin/prompts/forecast/hu/preview";
|
||||||
|
let r = app.call("POST", uri, Some(&admin), Some(json!({"system": "Próba.", "chart_id": own["id"]}))).await;
|
||||||
|
assert_eq!(r.status, StatusCode::BAD_REQUEST);
|
||||||
|
let body = json!({"system": "Próba.", "forecast_id": annas_forecast.body["id"]});
|
||||||
|
assert_eq!(app.call("POST", uri, Some(&admin), Some(body)).await.status, StatusCode::NOT_FOUND);
|
||||||
|
let body = json!({"system": "Próba.", "forecast_id": forecast.body["id"]});
|
||||||
|
let r = app.call("POST", uri, Some(&admin), Some(body)).await;
|
||||||
|
assert_eq!(
|
||||||
|
(r.status, r.body["forecast_id"].as_str()),
|
||||||
|
(StatusCode::ACCEPTED, forecast.body["id"].as_str()),
|
||||||
|
"{}",
|
||||||
|
r.body
|
||||||
|
);
|
||||||
|
// and its prompt is listed and can be saved like the others
|
||||||
|
let prompts = app.get("/v1/admin/prompts", Some(&admin)).await.body;
|
||||||
|
assert!(prompts["prompts"].as_array().unwrap().iter().any(|p| p["kind"] == "forecast"));
|
||||||
|
let r = app.call("PUT", "/v1/admin/prompts/forecast/hu", Some(&admin), Some(json!({"system": "Saját."}))).await;
|
||||||
|
assert_eq!((r.status, &r.body["custom"]), (StatusCode::OK, &json!(true)), "{}", r.body);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
@@ -1392,3 +1437,114 @@ async fn forecasts_are_free_their_analysis_uses_a_forecast_unit(pool: PgPool) {
|
|||||||
let (n,): (i64,) = sqlx::query_as("SELECT count(*) FROM forecasts").fetch_one(&pool).await.unwrap();
|
let (n,): (i64,) = sqlx::query_as("SELECT count(*) FROM forecasts").fetch_one(&pool).await.unwrap();
|
||||||
assert_eq!(n, 0);
|
assert_eq!(n, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
|
async fn recalculate_refreshes_calculations_and_queues_every_analysis_again(pool: PgPool) {
|
||||||
|
let app = TestApp::new(pool.clone()).await;
|
||||||
|
let anna = app.register("anna@example.com", "Anna").await;
|
||||||
|
let own = app.chart(&anna, "Saját", true, "1990-03-15").await;
|
||||||
|
let bela = app.chart(&anna, "Béla", false, "1985-08-02").await;
|
||||||
|
let syn = app.post("/v1/synastries", Some(&anna), json!({"chart1_id": own["id"], "chart2_id": bela["id"]})).await;
|
||||||
|
let own_id = own["id"].as_str().unwrap();
|
||||||
|
let forecast = app.post(&format!("/v1/charts/{own_id}/forecasts"), Some(&anna), json!({})).await;
|
||||||
|
assert_eq!(forecast.status, StatusCode::CREATED, "{}", forecast.body);
|
||||||
|
let before = app.get("/v1/me", Some(&anna)).await.body["analyses_left"].clone();
|
||||||
|
// stored with an older calculation
|
||||||
|
sqlx::query("UPDATE charts SET result = '{}', chart_hash = 'old'").execute(&pool).await.unwrap();
|
||||||
|
sqlx::query("UPDATE synastries SET result = '{}', synastry_hash = 'old'").execute(&pool).await.unwrap();
|
||||||
|
sqlx::query("UPDATE forecasts SET result = '{}', forecast_hash = 'old'").execute(&pool).await.unwrap();
|
||||||
|
|
||||||
|
routes::recalculate(&app.state).await.unwrap();
|
||||||
|
|
||||||
|
let (old,): (i64,) = sqlx::query_as(
|
||||||
|
"SELECT (SELECT count(*) FROM charts WHERE chart_hash = 'old' OR result = '{}') \
|
||||||
|
+ (SELECT count(*) FROM synastries WHERE synastry_hash = 'old' OR result = '{}') \
|
||||||
|
+ (SELECT count(*) FROM forecasts WHERE forecast_hash = 'old' OR result = '{}')",
|
||||||
|
)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(old, 0);
|
||||||
|
let rows: Vec<(String, String, i32)> =
|
||||||
|
sqlx::query_as("SELECT kind, status, credits_charged FROM analyses ORDER BY kind")
|
||||||
|
.fetch_all(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let kinds: Vec<&str> = rows.iter().map(|r| r.0.as_str()).collect();
|
||||||
|
assert_eq!(kinds, ["forecast", "natal", "natal", "summary", "summary", "synastry"]);
|
||||||
|
assert!(rows.iter().all(|r| r.1 == "pending" && r.2 == 0), "{rows:?}");
|
||||||
|
assert_eq!(app.get("/v1/me", Some(&anna)).await.body["analyses_left"], before);
|
||||||
|
assert_eq!(syn.status, StatusCode::CREATED);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
|
async fn admins_choose_the_model_of_each_function(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/models", Some(&anna)).await.status, StatusCode::FORBIDDEN);
|
||||||
|
|
||||||
|
let r = app.get("/v1/admin/models", Some(&admin)).await;
|
||||||
|
let models: Vec<(&str, &str, bool)> = r.body["functions"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.map(|f| (f["kind"].as_str().unwrap(), f["model"].as_str().unwrap(), f["custom"].as_bool().unwrap()))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
models,
|
||||||
|
[
|
||||||
|
("summary", "anthropic/claude-summary", false),
|
||||||
|
("natal", "anthropic/claude-test", false),
|
||||||
|
("synastry", "anthropic/claude-test", false),
|
||||||
|
("forecast", "anthropic/claude-test", false),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
// the list has only models that give structured answers, with prices per million tokens
|
||||||
|
let r = app.get("/v1/admin/models/catalog", Some(&admin)).await;
|
||||||
|
let ids: Vec<&str> = r.body["models"].as_array().unwrap().iter().map(|m| m["id"].as_str().unwrap()).collect();
|
||||||
|
assert_eq!(ids, ["anthropic/claude-test", "openai/gpt-x"]);
|
||||||
|
assert_eq!(r.body["models"][1]["input_per_million"].as_f64().map(|p| (p * 100.0).round()), Some(300.0));
|
||||||
|
|
||||||
|
let put = |kind: &str, model: Value| {
|
||||||
|
let uri = format!("/v1/admin/models/{kind}");
|
||||||
|
let (app, admin) = (&app, &admin);
|
||||||
|
async move { app.call("PUT", &uri, Some(admin), Some(json!({ "model": model }))).await }
|
||||||
|
};
|
||||||
|
assert_eq!(put("natal", json!("vendor/plain")).await.status, StatusCode::BAD_REQUEST);
|
||||||
|
assert_eq!(put("composite", json!("openai/gpt-x")).await.status, StatusCode::NOT_FOUND);
|
||||||
|
let r = put("natal", json!("openai/gpt-x")).await;
|
||||||
|
assert_eq!((r.status, &r.body["model"], &r.body["custom"]), (StatusCode::OK, &json!("openai/gpt-x"), &json!(true)));
|
||||||
|
|
||||||
|
// new analyses use it; regenerating writes it again in place with the current model
|
||||||
|
let chart = app.chart(&admin, "Saját", true, "1990-03-15").await;
|
||||||
|
let chart_id = chart["id"].as_str().unwrap();
|
||||||
|
let r = app.post(&format!("/v1/charts/{chart_id}/analyses"), Some(&admin), json!({})).await;
|
||||||
|
assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body);
|
||||||
|
let id = r.body["id"].as_str().unwrap().to_string();
|
||||||
|
let model =
|
||||||
|
|| sqlx::query_scalar::<_, String>("SELECT model FROM analyses WHERE id = $1::uuid").bind(&id).fetch_one(&pool);
|
||||||
|
assert_eq!(model().await.unwrap(), "openai/gpt-x");
|
||||||
|
let regenerate_uri = format!("/v1/admin/analyses/{id}/regenerate");
|
||||||
|
let regenerate = || app.post(®enerate_uri, Some(&admin), json!({}));
|
||||||
|
assert_eq!(regenerate().await.status, StatusCode::CONFLICT); // still being written
|
||||||
|
sqlx::query("UPDATE analyses SET status = 'done', content = '{\"title\": \"Régi\"}', completed_at = now()")
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(put("natal", Value::Null).await.body["model"], "anthropic/claude-test");
|
||||||
|
assert_eq!(
|
||||||
|
app.post(&format!("/v1/admin/analyses/{id}/regenerate"), Some(&anna), json!({})).await.status,
|
||||||
|
StatusCode::FORBIDDEN
|
||||||
|
);
|
||||||
|
let r = regenerate().await;
|
||||||
|
assert_eq!(
|
||||||
|
(r.status, r.body["status"].as_str(), &r.body["content"]),
|
||||||
|
(StatusCode::OK, Some("pending"), &Value::Null)
|
||||||
|
);
|
||||||
|
assert_eq!(r.body["id"].as_str(), Some(id.as_str()));
|
||||||
|
assert_eq!(model().await.unwrap(), "anthropic/claude-test");
|
||||||
|
let r = app.get(&format!("/v1/charts/{chart_id}/analyses"), Some(&admin)).await;
|
||||||
|
assert_eq!(r.body["analyses"].as_array().unwrap().iter().filter(|a| a["kind"] == "natal").count(), 1);
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,205 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useMemo, useState } from "react";
|
||||||
|
|
||||||
|
import { api, errorText } from "@/lib/api";
|
||||||
|
import { formatDate } from "@/lib/astro";
|
||||||
|
import type { CatalogModel, ModelFunction, PromptKind } from "@/lib/types";
|
||||||
|
|
||||||
|
const LABELS: Record<PromptKind, { title: string; about: string }> = {
|
||||||
|
summary: { title: "Tömör összefoglaló", about: "Ingyenes, minden új képlethez magától elkészül. Olcsó, gyors modell elég." },
|
||||||
|
natal: { title: "Részletes képletelemzés", about: "Fizetős, hat fejezet." },
|
||||||
|
synastry: { title: "Kapcsolati elemzés", about: "Fizetős, öt fejezet két képletről." },
|
||||||
|
forecast: { title: "Éves előrejelzés", about: "Fizetős, öt fejezet, a leghosszabb adatsorral." },
|
||||||
|
};
|
||||||
|
|
||||||
|
/** How many models the picker lists at once (narrow it with the search). */
|
||||||
|
const SHOWN = 60;
|
||||||
|
|
||||||
|
const usd = (x: number) => (x < 0.01 ? `$${x.toFixed(4)}` : `$${x.toFixed(3)}`);
|
||||||
|
const perMillion = (x: number) => `$${x < 1 ? x.toFixed(2) : x.toFixed(x % 1 === 0 ? 0 : 2)}`;
|
||||||
|
|
||||||
|
/** Estimated cost of one analysis of this kind with this model, from the average size of the latest ones. */
|
||||||
|
function estimate(f: ModelFunction, m: CatalogModel | undefined): number | null {
|
||||||
|
if (!m || f.avg_input_tokens === null || f.avg_output_tokens === null) return null;
|
||||||
|
return (f.avg_input_tokens * m.input_per_million + f.avg_output_tokens * m.output_per_million) / 1e6;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AdminModels() {
|
||||||
|
const [functions, setFunctions] = useState<ModelFunction[] | null>(null);
|
||||||
|
const [catalog, setCatalog] = useState<CatalogModel[] | null>(null);
|
||||||
|
const [catalogError, setCatalogError] = useState<string | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
api<{ functions: ModelFunction[] }>("/admin/models")
|
||||||
|
.then((d) => setFunctions(d.functions))
|
||||||
|
.catch((e) => setError(errorText(e)));
|
||||||
|
api<{ models: CatalogModel[] }>("/admin/models/catalog")
|
||||||
|
.then((d) => setCatalog(d.models))
|
||||||
|
.catch((e) => setCatalogError(errorText(e)));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return (
|
||||||
|
<p className="msg msg-error" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!functions) return <p className="muted">Betöltés…</p>;
|
||||||
|
const replace = (next: ModelFunction) => setFunctions((all) => all?.map((f) => (f.kind === next.kind ? next : f)) ?? null);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="model-list">
|
||||||
|
{catalogError && (
|
||||||
|
<p className="msg msg-error" role="alert">
|
||||||
|
{catalogError}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{functions.map((f) => (
|
||||||
|
<FunctionModel key={f.kind} fn={f} catalog={catalog} onSaved={replace} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function FunctionModel({
|
||||||
|
fn,
|
||||||
|
catalog,
|
||||||
|
onSaved,
|
||||||
|
}: {
|
||||||
|
fn: ModelFunction;
|
||||||
|
catalog: CatalogModel[] | null;
|
||||||
|
onSaved: (f: ModelFunction) => void;
|
||||||
|
}) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [query, setQuery] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const current = catalog?.find((m) => m.id === fn.model);
|
||||||
|
const cost = estimate(fn, current);
|
||||||
|
const label = LABELS[fn.kind];
|
||||||
|
const searchId = `model-search-${fn.kind}`;
|
||||||
|
|
||||||
|
const matches = useMemo(() => {
|
||||||
|
const words = query.toLowerCase().split(/\s+/).filter(Boolean);
|
||||||
|
return (catalog ?? []).filter((m) => {
|
||||||
|
const text = `${m.name} ${m.id}`.toLowerCase();
|
||||||
|
return words.every((w) => text.includes(w));
|
||||||
|
});
|
||||||
|
}, [catalog, query]);
|
||||||
|
|
||||||
|
async function save(model: string | null) {
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
onSaved(await api<ModelFunction>(`/admin/models/${fn.kind}`, { method: "PUT", body: { model } }));
|
||||||
|
setOpen(false);
|
||||||
|
setQuery("");
|
||||||
|
} catch (e) {
|
||||||
|
setError(errorText(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="card model-card" aria-labelledby={`model-${fn.kind}`}>
|
||||||
|
<div className="model-head">
|
||||||
|
<div>
|
||||||
|
<h2 id={`model-${fn.kind}`}>{label.title}</h2>
|
||||||
|
<p className="hint">{label.about}</p>
|
||||||
|
</div>
|
||||||
|
<div className="model-current">
|
||||||
|
<strong>{current?.name ?? fn.model}</strong>
|
||||||
|
<code>{fn.model}</code>
|
||||||
|
<span className="hint">
|
||||||
|
{current
|
||||||
|
? `${perMillion(current.input_per_million)} be / ${perMillion(current.output_per_million)} ki, millió tokenenként`
|
||||||
|
: catalog
|
||||||
|
? "nincs az OpenRouter listájában"
|
||||||
|
: ""}
|
||||||
|
</span>
|
||||||
|
<span className="hint">
|
||||||
|
{cost !== null
|
||||||
|
? `Becsült költség: kb. ${usd(cost)} elemzésenként (az utolsó ${fn.samples} alapján)`
|
||||||
|
: "Költségbecslés az első elkészült elemzések után."}
|
||||||
|
</span>
|
||||||
|
<span className="hint">
|
||||||
|
{fn.custom
|
||||||
|
? `Módosítva: ${fn.updated_at ? formatDate(fn.updated_at, true) : ""}${fn.updated_by ? `, ${fn.updated_by}` : ""}`
|
||||||
|
: "Alapértelmezett"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="form-actions">
|
||||||
|
<button type="button" className="btn btn-sm" onClick={() => setOpen((o) => !o)} aria-expanded={open}>
|
||||||
|
{open ? "Mégse" : "Másik modell"}
|
||||||
|
</button>
|
||||||
|
{fn.custom && (
|
||||||
|
<button type="button" className="btn btn-sm btn-ghost" onClick={() => save(null)} disabled={busy}>
|
||||||
|
Vissza az alapértelmezettre ({fn.default})
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{error && (
|
||||||
|
<p className="msg msg-error" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{open && (
|
||||||
|
<div className="model-picker">
|
||||||
|
<div className="field">
|
||||||
|
<label htmlFor={searchId}>Keresés név vagy azonosító szerint</label>
|
||||||
|
<input
|
||||||
|
id={searchId}
|
||||||
|
className="inp"
|
||||||
|
type="search"
|
||||||
|
value={query}
|
||||||
|
autoFocus
|
||||||
|
placeholder="pl. claude, gpt, gemini"
|
||||||
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{!catalog ? (
|
||||||
|
<p className="muted">A lista betöltése…</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<p className="hint">
|
||||||
|
{matches.length} modell (csak azok, amelyek kötött JSON-választ tudnak adni). Ár: dollár millió tokenenként,
|
||||||
|
bemenet / kimenet{fn.avg_input_tokens !== null ? "; jobb oldalt a becsült költség elemzésenként" : ""}.
|
||||||
|
</p>
|
||||||
|
<ul className="model-options">
|
||||||
|
{matches.slice(0, SHOWN).map((m) => {
|
||||||
|
const each = estimate(fn, m);
|
||||||
|
return (
|
||||||
|
<li key={m.id}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="model-option"
|
||||||
|
aria-current={m.id === fn.model ? "true" : undefined}
|
||||||
|
onClick={() => save(m.id)}
|
||||||
|
disabled={busy}
|
||||||
|
>
|
||||||
|
<span>
|
||||||
|
<strong>{m.name}</strong>
|
||||||
|
<code>{m.id}</code>
|
||||||
|
</span>
|
||||||
|
<span className="model-price">
|
||||||
|
{perMillion(m.input_per_million)} / {perMillion(m.output_per_million)}
|
||||||
|
{each !== null && <strong>{usd(each)}</strong>}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
{matches.length > SHOWN && <p className="hint">Szűkítsd a keresést a többi találathoz.</p>}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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 { AdminModels } from "./AdminModels";
|
||||||
|
|
||||||
|
export const metadata: Metadata = { title: "Modellek" };
|
||||||
|
|
||||||
|
export default async function AdminModelsPage() {
|
||||||
|
const me = await requireMe("/admin/modellek");
|
||||||
|
if (!me.user.roles.includes("admin")) notFound();
|
||||||
|
return (
|
||||||
|
<main className="page" style={{ maxWidth: 1180 }}>
|
||||||
|
<AdminNav current="/admin/modellek" />
|
||||||
|
<div className="page-head">
|
||||||
|
<h1>Modellek</h1>
|
||||||
|
<p className="muted">
|
||||||
|
Melyik modell írja az egyes elemzéseket. A változás az ezután kért és az újragenerált elemzésekre hat; a már
|
||||||
|
elkészültek változatlanok maradnak. A felhasználók a modell nevét sehol nem látják.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<AdminModels />
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -28,6 +28,13 @@ const KINDS: { kind: PromptKind; id: string; label: string; about: string }[] =
|
|||||||
label: "Kapcsolati elemzés",
|
label: "Kapcsolati elemzés",
|
||||||
about: "Fizetős összevetés-elemzés két képletről: öt fejezet, erősségek, kihívások és útravaló. Kérésre készül.",
|
about: "Fizetős összevetés-elemzés két képletről: öt fejezet, erősségek, kihívások és útravaló. Kérésre készül.",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
kind: "forecast",
|
||||||
|
id: "elorejelzes",
|
||||||
|
label: "Éves előrejelzés",
|
||||||
|
about:
|
||||||
|
"Fizetős elemzés egy születésnaptól a következőig: szolár, lassú tranzitok, progresszió, profekció, fogyatkozások. Öt fejezet, lehetőségek, kihívások és útravaló. Kérésre készül.",
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const LANGUAGES: Record<string, string> = { hu: "Magyar", en: "Angol" };
|
const LANGUAGES: Record<string, string> = { hu: "Magyar", en: "Angol" };
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { AnalysisView } from "@/components/AnalysisView";
|
|||||||
import { api, errorText } from "@/lib/api";
|
import { api, errorText } from "@/lib/api";
|
||||||
import { formatDate } from "@/lib/astro";
|
import { formatDate } from "@/lib/astro";
|
||||||
import { listName } from "@/lib/synastry";
|
import { listName } from "@/lib/synastry";
|
||||||
import type { ChartListItem, PromptKind, PromptPreview, SynastryListItem } from "@/lib/types";
|
import type { ChartListItem, ForecastList, ForecastSummary, PromptKind, PromptPreview, SynastryListItem } from "@/lib/types";
|
||||||
|
|
||||||
const POLL_MS = 4000;
|
const POLL_MS = 4000;
|
||||||
const MAX_POLLS = 150; // 10 minutes
|
const MAX_POLLS = 150; // 10 minutes
|
||||||
@@ -36,6 +36,7 @@ export function PromptTrial({
|
|||||||
onLoad: (system: string) => void;
|
onLoad: (system: string) => void;
|
||||||
}) {
|
}) {
|
||||||
const synastry = kind === "synastry";
|
const synastry = kind === "synastry";
|
||||||
|
const forecastKind = kind === "forecast";
|
||||||
const [chartId, setChartId] = useState(charts.find((c) => c.is_primary)?.id ?? charts[0]?.id ?? "");
|
const [chartId, setChartId] = useState(charts.find((c) => c.is_primary)?.id ?? charts[0]?.id ?? "");
|
||||||
const [synastries, setSynastries] = useState<SynastryListItem[]>([]);
|
const [synastries, setSynastries] = useState<SynastryListItem[]>([]);
|
||||||
const [synastryId, setSynastryId] = useState("");
|
const [synastryId, setSynastryId] = useState("");
|
||||||
@@ -50,7 +51,23 @@ export function PromptTrial({
|
|||||||
})
|
})
|
||||||
.catch(() => setSynastries([]));
|
.catch(() => setSynastries([]));
|
||||||
}, [synastry]);
|
}, [synastry]);
|
||||||
const targetId = synastry ? synastryId : chartId;
|
// A forecast is tried on one of the chosen chart's calculated years.
|
||||||
|
const [forecasts, setForecasts] = useState<ForecastSummary[] | null>(null);
|
||||||
|
const [forecastId, setForecastId] = useState("");
|
||||||
|
const [allForecasts, setAllForecasts] = useState<ForecastSummary[]>([]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!forecastKind || !chartId) return;
|
||||||
|
setForecasts(null);
|
||||||
|
api<ForecastList>(`/charts/${chartId}/forecasts`)
|
||||||
|
.then((d) => {
|
||||||
|
setForecasts(d.forecasts);
|
||||||
|
setForecastId(d.forecasts[0]?.id ?? "");
|
||||||
|
setAllForecasts((all) => [...all.filter((f) => f.chart_id !== chartId), ...d.forecasts]);
|
||||||
|
})
|
||||||
|
.catch(() => setForecasts([]));
|
||||||
|
}, [forecastKind, chartId]);
|
||||||
|
const targetId = synastry ? synastryId : forecastKind ? forecastId : chartId;
|
||||||
|
const forecastName = (f: ForecastSummary) => `${f.year}–${f.year + 1} · ${f.place ?? "születési hely"}`;
|
||||||
const comparisonName = (s: SynastryListItem) => `${listName(s.chart1, charts)} és ${listName(s.chart2, charts)}`;
|
const comparisonName = (s: SynastryListItem) => `${listName(s.chart1, charts)} és ${listName(s.chart2, charts)}`;
|
||||||
const [trials, setTrials] = useState<Trial[]>([]);
|
const [trials, setTrials] = useState<Trial[]>([]);
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
@@ -62,7 +79,11 @@ export function PromptTrial({
|
|||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const preview = await api<PromptPreview>(`/admin/prompts/${kind}/${language}/preview`, {
|
const preview = await api<PromptPreview>(`/admin/prompts/${kind}/${language}/preview`, {
|
||||||
body: synastry ? { system: draft, synastry_id: synastryId } : { system: draft, chart_id: chartId },
|
body: synastry
|
||||||
|
? { system: draft, synastry_id: synastryId }
|
||||||
|
: forecastKind
|
||||||
|
? { system: draft, forecast_id: forecastId }
|
||||||
|
: { system: draft, chart_id: chartId },
|
||||||
});
|
});
|
||||||
setTrials((all) => [{ preview, system: draft }, ...all]);
|
setTrials((all) => [{ preview, system: draft }, ...all]);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -84,7 +105,8 @@ export function PromptTrial({
|
|||||||
<h2 id={`${selectId}-title`}>Kipróbálás</h2>
|
<h2 id={`${selectId}-title`}>Kipróbálás</h2>
|
||||||
<p className="hint">
|
<p className="hint">
|
||||||
A szerkesztőben lévő szöveggel (mentés nélkül is) megírja az elemzést egy saját{" "}
|
A szerkesztőben lévő szöveggel (mentés nélkül is) megírja az elemzést egy saját{" "}
|
||||||
{synastry ? "összevetésedre" : "képletedre"}. Az eredmény nem kerül {synastry ? "az összevetéshez" : "a képlethez"},
|
{synastry ? "összevetésedre" : forecastKind ? "előrejelzésedre" : "képletedre"}. Az eredmény nem kerül{" "}
|
||||||
|
{synastry ? "az összevetéshez" : forecastKind ? "az előrejelzéshez" : "a képlethez"},
|
||||||
csak itt látod. Valódi modellhívás, ezért költsége van.
|
csak itt látod. Valódi modellhívás, ezért költsége van.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -110,6 +132,54 @@ export function PromptTrial({
|
|||||||
</div>
|
</div>
|
||||||
) : charts.length === 0 ? (
|
) : charts.length === 0 ? (
|
||||||
<p className="muted">Kipróbáláshoz előbb legyen legalább egy képleted.</p>
|
<p className="muted">Kipróbáláshoz előbb legyen legalább egy képleted.</p>
|
||||||
|
) : forecastKind ? (
|
||||||
|
<div className="prompt-trial-form">
|
||||||
|
<div className="field">
|
||||||
|
<label htmlFor={selectId}>Képlet</label>
|
||||||
|
<select id={selectId} className="inp" value={chartId} onChange={(e) => setChartId(e.target.value)}>
|
||||||
|
{charts.map((c) => (
|
||||||
|
<option key={c.id} value={c.id}>
|
||||||
|
{c.is_primary ? `Én (${c.label})` : c.label}
|
||||||
|
{c.birth.time ? "" : " – idő nélkül"}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
{forecasts === null ? (
|
||||||
|
<p className="hint">Betöltés…</p>
|
||||||
|
) : forecasts.length === 0 ? (
|
||||||
|
<p className="muted">
|
||||||
|
Ehhez a képlethez még nincs kiszámolt év. Előbb kérj egyet az{" "}
|
||||||
|
<a href={`/kepletek/${chartId}/elorejelzes`}>előrejelzés oldalán</a> (a számítás ingyenes).
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="field">
|
||||||
|
<label htmlFor={`${selectId}-year`}>Év</label>
|
||||||
|
<select
|
||||||
|
id={`${selectId}-year`}
|
||||||
|
className="inp"
|
||||||
|
value={forecastId}
|
||||||
|
onChange={(e) => setForecastId(e.target.value)}
|
||||||
|
>
|
||||||
|
{forecasts.map((f) => (
|
||||||
|
<option key={f.id} value={f.id}>
|
||||||
|
{forecastName(f)}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-primary"
|
||||||
|
onClick={start}
|
||||||
|
disabled={busy || !targetId || !draft.trim()}
|
||||||
|
>
|
||||||
|
{busy ? "Indítás…" : "Kipróbálás"}
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="prompt-trial-form">
|
<div className="prompt-trial-form">
|
||||||
<div className="field">
|
<div className="field">
|
||||||
@@ -138,7 +208,13 @@ export function PromptTrial({
|
|||||||
key={t.preview.id}
|
key={t.preview.id}
|
||||||
trial={t}
|
trial={t}
|
||||||
chartLabel={
|
chartLabel={
|
||||||
t.preview.synastry_id
|
t.preview.forecast_id
|
||||||
|
? (() => {
|
||||||
|
const f = allForecasts.find((x) => x.id === t.preview.forecast_id);
|
||||||
|
const c = f && charts.find((x) => x.id === f.chart_id);
|
||||||
|
return f ? `${c?.label ?? "Képlet"}, ${forecastName(f)}` : "Előrejelzés";
|
||||||
|
})()
|
||||||
|
: t.preview.synastry_id
|
||||||
? (() => {
|
? (() => {
|
||||||
const s = synastries.find((x) => x.id === t.preview.synastry_id);
|
const s = synastries.find((x) => x.id === t.preview.synastry_id);
|
||||||
return s ? comparisonName(s) : "Összevetés";
|
return s ? comparisonName(s) : "Összevetés";
|
||||||
@@ -218,7 +294,13 @@ function TrialResult({
|
|||||||
{waiting ? (
|
{waiting ? (
|
||||||
<AnalysisLoading
|
<AnalysisLoading
|
||||||
compact
|
compact
|
||||||
text={p.kind === "summary" ? "Készül az összefoglaló, kb. 10–30 másodperc." : "Készül az elemzés, kb. 1–3 perc."}
|
text={
|
||||||
|
p.kind === "summary"
|
||||||
|
? "Készül az összefoglaló, kb. 10–30 másodperc."
|
||||||
|
: p.kind === "forecast"
|
||||||
|
? "Készül az előrejelzés, kb. 2–4 perc."
|
||||||
|
: "Készül az elemzés, kb. 1–3 perc."
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
) : p.status === "failed" ? (
|
) : p.status === "failed" ? (
|
||||||
<p className="msg msg-error" role="alert">
|
<p className="msg msg-error" role="alert">
|
||||||
@@ -231,7 +313,7 @@ function TrialResult({
|
|||||||
<p className="summary-text">{p.content.summary}</p>
|
<p className="summary-text">{p.content.summary}</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<AnalysisView content={p.content} kind={p.kind === "synastry" ? "synastry" : "natal"} />
|
<AnalysisView content={p.content} kind={p.kind} />
|
||||||
)
|
)
|
||||||
) : null}
|
) : null}
|
||||||
{meta.length > 0 && !waiting && <p className="hint">{meta.join(" · ")}</p>}
|
{meta.length > 0 && !waiting && <p className="hint">{meta.join(" · ")}</p>}
|
||||||
|
|||||||
@@ -610,3 +610,26 @@ a.pair-row:hover strong { color: var(--gold); }
|
|||||||
.timeline-item { grid-template-columns: 52px 1fr; }
|
.timeline-item { grid-template-columns: 52px 1fr; }
|
||||||
.timeline-glyph { display: none; }
|
.timeline-glyph { display: none; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* admin: models */
|
||||||
|
.model-list { display: flex; flex-direction: column; gap: 16px; }
|
||||||
|
.model-card { gap: 12px; }
|
||||||
|
.model-head { display: flex; gap: 12px 24px; justify-content: space-between; flex-wrap: wrap; }
|
||||||
|
.model-head h2 { margin: 0 0 4px; font-size: 20px; }
|
||||||
|
.model-current { display: flex; flex-direction: column; gap: 2px; align-items: flex-end; text-align: right; min-width: 0; }
|
||||||
|
.model-current code, .model-option code { font-size: 13px; color: var(--muted); overflow-wrap: anywhere; }
|
||||||
|
.model-picker { display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
.model-options { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 4px; max-height: 420px; overflow-y: auto; }
|
||||||
|
.model-option {
|
||||||
|
width: 100%; display: flex; gap: 12px; justify-content: space-between; align-items: center; text-align: left;
|
||||||
|
padding: 8px 12px; border: 1px solid var(--line); border-radius: 8px; background: transparent; color: inherit; cursor: pointer; font: inherit;
|
||||||
|
}
|
||||||
|
.model-option > span:first-child { display: flex; flex-direction: column; min-width: 0; }
|
||||||
|
.model-option:hover { border-color: var(--gold); }
|
||||||
|
.model-option[aria-current="true"] { border-color: var(--gold); background: color-mix(in srgb, var(--gold) 10%, transparent); }
|
||||||
|
.model-price { display: flex; flex-direction: column; align-items: flex-end; font-size: 13px; color: var(--muted); white-space: nowrap; }
|
||||||
|
.model-price strong { color: var(--ink); font-size: 14px; }
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.model-current { align-items: flex-start; text-align: left; }
|
||||||
|
}
|
||||||
|
.regenerate { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; justify-content: flex-end; }
|
||||||
|
|||||||
@@ -72,7 +72,12 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
|
|||||||
<WheelLegend />
|
<WheelLegend />
|
||||||
</div>
|
</div>
|
||||||
<div className="field chart-side">
|
<div className="field chart-side">
|
||||||
<ChartSummary chartId={chart.id} initial={summary} detailedDone={detailed?.status === "done"} />
|
<ChartSummary
|
||||||
|
chartId={chart.id}
|
||||||
|
initial={summary}
|
||||||
|
detailedDone={detailed?.status === "done"}
|
||||||
|
isAdmin={me.user.roles.includes("admin")}
|
||||||
|
/>
|
||||||
<BigThree chart={chart} />
|
<BigThree chart={chart} />
|
||||||
{(elements || modalities || phase) && (
|
{(elements || modalities || phase) && (
|
||||||
<div className="card" style={{ gap: 12 }}>
|
<div className="card" style={{ gap: 12 }}>
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ const PAGES = [
|
|||||||
{ href: "/admin", label: "Felhasználók" },
|
{ href: "/admin", label: "Felhasználók" },
|
||||||
{ href: "/admin/meghivok", label: "Meghívók" },
|
{ href: "/admin/meghivok", label: "Meghívók" },
|
||||||
{ href: "/admin/promptok", label: "Promptok" },
|
{ href: "/admin/promptok", label: "Promptok" },
|
||||||
|
{ href: "/admin/modellek", label: "Modellek" },
|
||||||
];
|
];
|
||||||
|
|
||||||
/** Switches between the admin pages. */
|
/** Switches between the admin pages. */
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { api } from "@/lib/api";
|
|||||||
import type { Analysis } from "@/lib/types";
|
import type { Analysis } from "@/lib/types";
|
||||||
|
|
||||||
import { AnalysisLoading } from "./AnalysisLoading";
|
import { AnalysisLoading } from "./AnalysisLoading";
|
||||||
|
import { RegenerateButton } from "./RegenerateButton";
|
||||||
import { Rich } from "./Rich";
|
import { Rich } from "./Rich";
|
||||||
import { openTab } from "./Tabs";
|
import { openTab } from "./Tabs";
|
||||||
|
|
||||||
@@ -21,11 +22,14 @@ export function ChartSummary({
|
|||||||
chartId,
|
chartId,
|
||||||
initial,
|
initial,
|
||||||
detailedDone = false,
|
detailedDone = false,
|
||||||
|
isAdmin = false,
|
||||||
}: {
|
}: {
|
||||||
chartId: string;
|
chartId: string;
|
||||||
initial: Analysis | null;
|
initial: Analysis | null;
|
||||||
/** The detailed analysis is ready: the link says so instead of offering it. */
|
/** The detailed analysis is ready: the link says so instead of offering it. */
|
||||||
detailedDone?: boolean;
|
detailedDone?: boolean;
|
||||||
|
/** Admins can write the summary again. */
|
||||||
|
isAdmin?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const [summary, setSummary] = useState<Analysis | null>(initial);
|
const [summary, setSummary] = useState<Analysis | null>(initial);
|
||||||
const [gaveUp, setGaveUp] = useState(false);
|
const [gaveUp, setGaveUp] = useState(false);
|
||||||
@@ -61,6 +65,15 @@ export function ChartSummary({
|
|||||||
<span className="eyebrow">Röviden</span>
|
<span className="eyebrow">Röviden</span>
|
||||||
{content ? (
|
{content ? (
|
||||||
<>
|
<>
|
||||||
|
{isAdmin && summary && (
|
||||||
|
<RegenerateButton
|
||||||
|
analysisId={summary.id}
|
||||||
|
onStarted={(a) => {
|
||||||
|
setGaveUp(false);
|
||||||
|
setSummary(a);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
<h2 id="summary-title" className="summary-title">
|
<h2 id="summary-title" className="summary-title">
|
||||||
{content.title}
|
{content.title}
|
||||||
</h2>
|
</h2>
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import type { Analysis } from "@/lib/types";
|
|||||||
import { AI_SHORT } from "./AiNote";
|
import { AI_SHORT } from "./AiNote";
|
||||||
import { AnalysisLoading } from "./AnalysisLoading";
|
import { AnalysisLoading } from "./AnalysisLoading";
|
||||||
import { PackageChooser } from "./PackageCards";
|
import { PackageChooser } from "./PackageCards";
|
||||||
|
import { RegenerateButton } from "./RegenerateButton";
|
||||||
import { AnalysisView } from "./AnalysisView";
|
import { AnalysisView } from "./AnalysisView";
|
||||||
|
|
||||||
const POLL_MS = 5000;
|
const POLL_MS = 5000;
|
||||||
@@ -145,6 +146,7 @@ export function DetailedAnalysis({
|
|||||||
return (
|
return (
|
||||||
<section className="analysis-card" aria-label={t.eyebrow}>
|
<section className="analysis-card" aria-label={t.eyebrow}>
|
||||||
<span className="eyebrow">{t.eyebrow}</span>
|
<span className="eyebrow">{t.eyebrow}</span>
|
||||||
|
{isAdmin && <RegenerateButton analysisId={analysis.id} onStarted={setAnalysis} />}
|
||||||
{note && <p className="hint">{note}</p>}
|
{note && <p className="hint">{note}</p>}
|
||||||
<AnalysisView content={analysis.content} kind={target.kind} />
|
<AnalysisView content={analysis.content} kind={target.kind} />
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
import { api, errorText } from "@/lib/api";
|
||||||
|
import type { Analysis } from "@/lib/types";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Admin only: writes the analysis again in place with the current prompt and
|
||||||
|
* model (nobody is charged). Asks once before it starts.
|
||||||
|
*/
|
||||||
|
export function RegenerateButton({ analysisId, onStarted }: { analysisId: string; onStarted: (a: Analysis) => void }) {
|
||||||
|
const [asking, setAsking] = useState(false);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
async function regenerate() {
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
onStarted(await api<Analysis>(`/admin/analyses/${analysisId}/regenerate`, { method: "POST" }));
|
||||||
|
setAsking(false);
|
||||||
|
} catch (e) {
|
||||||
|
setError(errorText(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="regenerate">
|
||||||
|
{asking ? (
|
||||||
|
<>
|
||||||
|
<span className="hint">A mostani szöveg helyett újat ír a jelenlegi prompttal és modellel.</span>
|
||||||
|
<button type="button" className="btn btn-sm" onClick={regenerate} disabled={busy}>
|
||||||
|
{busy ? "Indítás…" : "Igen, újragenerálás"}
|
||||||
|
</button>
|
||||||
|
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setAsking(false)} disabled={busy}>
|
||||||
|
Mégse
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<button type="button" className="btn btn-sm btn-ghost" onClick={() => setAsking(true)} title="Admin: újragenerálás">
|
||||||
|
↻ Újragenerálás
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{error && (
|
||||||
|
<span className="msg msg-error" role="alert">
|
||||||
|
{error}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -229,7 +229,31 @@ export interface AdminUser {
|
|||||||
analyses_left: UnitBalance;
|
analyses_left: UnitBalance;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type PromptKind = "summary" | "natal" | "synastry";
|
export type PromptKind = "summary" | "natal" | "synastry" | "forecast";
|
||||||
|
|
||||||
|
/** Admin: the model writing one kind of analysis. */
|
||||||
|
export interface ModelFunction {
|
||||||
|
kind: PromptKind;
|
||||||
|
model: string;
|
||||||
|
/** The configured default (environment). */
|
||||||
|
default: string;
|
||||||
|
custom: boolean;
|
||||||
|
updated_at: string | null;
|
||||||
|
updated_by: string | null;
|
||||||
|
/** Average size of the latest analyses of this kind, for the cost estimate. */
|
||||||
|
avg_input_tokens: number | null;
|
||||||
|
avg_output_tokens: number | null;
|
||||||
|
samples: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A model OpenRouter offers; prices in USD per million tokens. */
|
||||||
|
export interface CatalogModel {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
input_per_million: number;
|
||||||
|
output_per_million: number;
|
||||||
|
context_length: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
export interface PromptRevision {
|
export interface PromptRevision {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -261,6 +285,7 @@ export interface PromptPreview {
|
|||||||
kind: PromptKind;
|
kind: PromptKind;
|
||||||
chart_id: string | null;
|
chart_id: string | null;
|
||||||
synastry_id: string | null;
|
synastry_id: string | null;
|
||||||
|
forecast_id: string | null;
|
||||||
language: string;
|
language: string;
|
||||||
model: string;
|
model: string;
|
||||||
status: "pending" | "running" | "done" | "failed";
|
status: "pending" | "running" | "done" | "failed";
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ async fn info(State(state): State<Arc<AppState>>) -> Json<Value> {
|
|||||||
],
|
],
|
||||||
"node_type": [NodeType::True, NodeType::Mean],
|
"node_type": [NodeType::True, NodeType::Mean],
|
||||||
"lilith_type": [LilithType::Mean, LilithType::True],
|
"lilith_type": [LilithType::Mean, LilithType::True],
|
||||||
"aspect_set": [AspectSet::Major, AspectSet::Extended],
|
"aspect_set": [AspectSet::Major, AspectSet::Standard, AspectSet::Extended],
|
||||||
"ambiguous_time": ["reject", "earlier", "later"],
|
"ambiguous_time": ["reject", "earlier", "later"],
|
||||||
"calendar": ["gregorian", "julian"],
|
"calendar": ["gregorian", "julian"],
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -22,7 +22,8 @@ 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 (`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):
|
- **5 fokos szabály:** ha egy pont legfeljebb 5°-kal (`CUSP_ORB`) a következő ház csúcsa előtt áll, a szöveg már abban a házban adja meg, és odaírja, hogy formálisan az előzőben van („house 11 (on the cusp: 2°00' before it, formally house 10)”). Így olvassák az asztrológusok. A számított ház, a képlet rajza és a táblázatok nem változnak. Ugyanez érvényes az összevetés házátfedéseire, a szolár Aszcendensre, az év urára és a fogyatkozásokra.
|
||||||
|
- 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 = v3`; ha a sor `prompt_version`-je `v3-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`;
|
||||||
|
|||||||
@@ -75,12 +75,49 @@ fn names(list: &Value) -> String {
|
|||||||
list.as_array().into_iter().flatten().filter_map(Value::as_str).map(point_name).collect::<Vec<_>>().join(", ")
|
list.as_array().into_iter().flatten().filter_map(Value::as_str).map(point_name).collect::<Vec<_>>().join(", ")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A point at most this far before the next house cusp is read in that house,
|
||||||
|
/// as astrologers do (the "5° rule"). The calculation keeps the exact house.
|
||||||
|
const CUSP_ORB: f64 = 5.0;
|
||||||
|
|
||||||
|
/// "2°05'"
|
||||||
|
fn degrees(x: f64) -> String {
|
||||||
|
let minutes = (x * 60.0).round() as i64;
|
||||||
|
format!("{}°{:02}'", minutes / 60, minutes % 60)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn point_longitude(chart: &Value, id: &str) -> Option<f64> {
|
||||||
|
points(chart).find(|p| p["id"] == id)?["longitude"].as_f64()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The house a point is read in: its own, or the next one when that cusp is
|
||||||
|
/// at most [`CUSP_ORB`] ahead, with how far ahead it is.
|
||||||
|
fn read_house(longitude: Option<f64>, house: i64, cusps: &Value) -> (i64, Option<f64>) {
|
||||||
|
let next = house % 12 + 1;
|
||||||
|
let cusp = cusps.as_array().into_iter().flatten().find(|c| c["house"].as_i64() == Some(next));
|
||||||
|
match (longitude, cusp.and_then(|c| c["longitude"].as_f64())) {
|
||||||
|
(Some(lon), Some(cusp)) if (cusp - lon).rem_euclid(360.0) <= CUSP_ORB => {
|
||||||
|
(next, Some((cusp - lon).rem_euclid(360.0)))
|
||||||
|
}
|
||||||
|
_ => (house, None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "house 11 (on the cusp: 2°05' before it, formally house 10)" or "house 10".
|
||||||
|
fn house_text(longitude: Option<f64>, house: i64, cusps: &Value) -> String {
|
||||||
|
match read_house(longitude, house, cusps) {
|
||||||
|
(read, Some(before)) => {
|
||||||
|
format!("house {read} (on the cusp: {} before it, formally house {house})", degrees(before))
|
||||||
|
}
|
||||||
|
(read, None) => format!("house {read}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// One line per point: "Sun: Cancer 0°24', house 3, retrograde, domicile".
|
/// One line per point: "Sun: Cancer 0°24', house 3, retrograde, domicile".
|
||||||
fn point_lines(out: &mut String, chart: &Value, prefix: &str, houses: bool) {
|
fn point_lines(out: &mut String, chart: &Value, prefix: &str, houses: bool) {
|
||||||
for p in points(chart).filter(|p| MAIN_POINTS.contains(&p["id"].as_str().unwrap_or(""))) {
|
for p in points(chart).filter(|p| MAIN_POINTS.contains(&p["id"].as_str().unwrap_or(""))) {
|
||||||
let mut line = format!("{prefix}- {}: {}", point_name(p["id"].as_str().unwrap_or("?")), position(p));
|
let mut line = format!("{prefix}- {}: {}", point_name(p["id"].as_str().unwrap_or("?")), position(p));
|
||||||
if houses && let Some(h) = p["house"].as_i64() {
|
if houses && let Some(h) = p["house"].as_i64() {
|
||||||
let _ = write!(line, ", house {h}");
|
let _ = write!(line, ", {}", house_text(p["longitude"].as_f64(), h, &chart["houses"]["cusps"]));
|
||||||
}
|
}
|
||||||
if p["retrograde"].as_bool() == Some(true) {
|
if p["retrograde"].as_bool() == Some(true) {
|
||||||
line.push_str(", retrograde");
|
line.push_str(", retrograde");
|
||||||
@@ -97,7 +134,10 @@ fn point_lines(out: &mut String, chart: &Value, prefix: &str, houses: bool) {
|
|||||||
.filter(|p| ASTEROIDS.contains(&p["id"].as_str().unwrap_or("")))
|
.filter(|p| ASTEROIDS.contains(&p["id"].as_str().unwrap_or("")))
|
||||||
.map(|p| {
|
.map(|p| {
|
||||||
let house = if houses {
|
let house = if houses {
|
||||||
p["house"].as_i64().map(|h| format!(" (house {h})")).unwrap_or_default()
|
p["house"]
|
||||||
|
.as_i64()
|
||||||
|
.map(|h| format!(" ({})", house_text(p["longitude"].as_f64(), h, &chart["houses"]["cusps"])))
|
||||||
|
.unwrap_or_default()
|
||||||
} else {
|
} else {
|
||||||
String::new()
|
String::new()
|
||||||
};
|
};
|
||||||
@@ -155,12 +195,15 @@ pub fn natal(chart: &Value) -> String {
|
|||||||
if kind == "modern" && ruler["traditional"]["planet"] == r["planet"] {
|
if kind == "modern" && ruler["traditional"]["planet"] == r["planet"] {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
let house = r["house"].as_i64().map_or_else(
|
||||||
|
|| "house ?".to_string(),
|
||||||
|
|h| house_text(point_longitude(chart, planet), h, &chart["houses"]["cusps"]),
|
||||||
|
);
|
||||||
let _ = writeln!(
|
let _ = writeln!(
|
||||||
out,
|
out,
|
||||||
"- Chart ruler ({kind}): {} in {}, house {}",
|
"- Chart ruler ({kind}): {} in {}, {house}",
|
||||||
point_name(planet),
|
point_name(planet),
|
||||||
capitalize(r["sign"].as_str().unwrap_or("?")),
|
capitalize(r["sign"].as_str().unwrap_or("?")),
|
||||||
r["house"]
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -199,7 +242,10 @@ pub fn natal(chart: &Value) -> String {
|
|||||||
}
|
}
|
||||||
if known && let Some(fortune) = chart["lots"]["fortune"].as_object() {
|
if known && let Some(fortune) = chart["lots"]["fortune"].as_object() {
|
||||||
let fortune = Value::Object(fortune.clone());
|
let fortune = Value::Object(fortune.clone());
|
||||||
let _ = writeln!(out, "- Part of Fortune: {}, house {}", position(&fortune), fortune["house"]);
|
if let Some(h) = fortune["house"].as_i64() {
|
||||||
|
let house = house_text(fortune["longitude"].as_f64(), h, &chart["houses"]["cusps"]);
|
||||||
|
let _ = writeln!(out, "- Part of Fortune: {}, {house}", position(&fortune));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
@@ -251,16 +297,23 @@ pub fn synastry(chart1: &Value, chart2: &Value, result: &Value) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let overlays = &result["house_overlays"];
|
let overlays = &result["house_overlays"];
|
||||||
for (key, label) in [
|
for (key, label, own, other) in [
|
||||||
("person1_in_person2", "Person 1's planets in Person 2's houses"),
|
("person1_in_person2", "Person 1's planets in Person 2's houses", chart1, chart2),
|
||||||
("person2_in_person1", "Person 2's planets in Person 1's houses"),
|
("person2_in_person1", "Person 2's planets in Person 1's houses", chart2, chart1),
|
||||||
] {
|
] {
|
||||||
let list: Vec<String> = overlays[key]
|
let list: Vec<String> = overlays[key]
|
||||||
.as_array()
|
.as_array()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.flatten()
|
.flatten()
|
||||||
.filter(|o| MAIN_POINTS.contains(&o["point"].as_str().unwrap_or("")))
|
.filter(|o| MAIN_POINTS.contains(&o["point"].as_str().unwrap_or("")))
|
||||||
.filter_map(|o| Some(format!("{} {}", point_name(o["point"].as_str()?), o["house"].as_i64()?)))
|
.filter_map(|o| {
|
||||||
|
let point = o["point"].as_str()?;
|
||||||
|
let house = o["house"].as_i64()?;
|
||||||
|
Some(match read_house(point_longitude(own, point), house, &other["houses"]["cusps"]) {
|
||||||
|
(read, Some(_)) => format!("{} {read} (on the cusp, formally {house})", point_name(point)),
|
||||||
|
(read, None) => format!("{} {read}", point_name(point)),
|
||||||
|
})
|
||||||
|
})
|
||||||
.collect();
|
.collect();
|
||||||
if !list.is_empty() {
|
if !list.is_empty() {
|
||||||
let _ = writeln!(out, "\n{label}: {}", list.join(", "));
|
let _ = writeln!(out, "\n{label}: {}", list.join(", "));
|
||||||
@@ -357,7 +410,12 @@ pub fn forecast(chart: &Value, result: &Value) -> String {
|
|||||||
out.push_str("\nSOLAR RETURN CHART (cast for the moment of the solar return at the place of the birthday):\n");
|
out.push_str("\nSOLAR RETURN CHART (cast for the moment of the solar return at the place of the birthday):\n");
|
||||||
angle_lines(&mut out, sr, "");
|
angle_lines(&mut out, sr, "");
|
||||||
if let Some(h) = sr["natal_house_of_ascendant"].as_i64() {
|
if let Some(h) = sr["natal_house_of_ascendant"].as_i64() {
|
||||||
let _ = writeln!(out, "- The solar return Ascendant falls in natal house {h}.");
|
let asc = sr["angles"]["ascendant"]["longitude"].as_f64();
|
||||||
|
let _ = writeln!(
|
||||||
|
out,
|
||||||
|
"- The solar return Ascendant falls in natal {}.",
|
||||||
|
house_text(asc, h, &chart["houses"]["cusps"])
|
||||||
|
);
|
||||||
}
|
}
|
||||||
point_lines(&mut out, sr, "", true);
|
point_lines(&mut out, sr, "", true);
|
||||||
aspect_lines(&mut out, &sr["aspects"], "Solar return aspects (tightest first):", 15);
|
aspect_lines(&mut out, &sr["aspects"], "Solar return aspects (tightest first):", 15);
|
||||||
@@ -370,13 +428,16 @@ pub fn forecast(chart: &Value, result: &Value) -> String {
|
|||||||
let planets = names(&p["planets_in_sign"]);
|
let planets = names(&p["planets_in_sign"]);
|
||||||
let _ = writeln!(
|
let _ = writeln!(
|
||||||
out,
|
out,
|
||||||
"\nANNUAL PROFECTION: the year activates natal house {} ({}); lord of the year: {} (natal {} in {}, house {}).{}",
|
"\nANNUAL PROFECTION: the year activates natal house {} ({}); lord of the year: {} (natal {} in {}, {}).{}",
|
||||||
p["house"],
|
p["house"],
|
||||||
capitalize(p["sign"].as_str().unwrap_or("?")),
|
capitalize(p["sign"].as_str().unwrap_or("?")),
|
||||||
point_name(p["lord"].as_str().unwrap_or("?")),
|
point_name(p["lord"].as_str().unwrap_or("?")),
|
||||||
point_name(p["lord"].as_str().unwrap_or("?")),
|
point_name(p["lord"].as_str().unwrap_or("?")),
|
||||||
capitalize(p["lord_sign"].as_str().unwrap_or("?")),
|
capitalize(p["lord_sign"].as_str().unwrap_or("?")),
|
||||||
p["lord_house"],
|
p["lord_house"].as_i64().map_or_else(
|
||||||
|
|| "house ?".to_string(),
|
||||||
|
|h| house_text(point_longitude(chart, p["lord"].as_str().unwrap_or("")), h, &chart["houses"]["cusps"])
|
||||||
|
),
|
||||||
if planets.is_empty() { String::new() } else { format!(" Natal planets in that sign: {planets}.") }
|
if planets.is_empty() { String::new() } else { format!(" Natal planets in that sign: {planets}.") }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -466,7 +527,7 @@ pub fn forecast(chart: &Value, result: &Value) -> String {
|
|||||||
position(e)
|
position(e)
|
||||||
);
|
);
|
||||||
if let Some(h) = e["house"].as_i64() {
|
if let Some(h) = e["house"].as_i64() {
|
||||||
let _ = write!(line, ", natal house {h}");
|
let _ = write!(line, ", natal {}", house_text(e["longitude"].as_f64(), h, &chart["houses"]["cusps"]));
|
||||||
}
|
}
|
||||||
let hits: Vec<String> = e["contacts"]
|
let hits: Vec<String> = e["contacts"]
|
||||||
.as_array()
|
.as_array()
|
||||||
@@ -525,6 +586,7 @@ fn aspect_lines(out: &mut String, aspects: &Value, heading: &str, limit: usize)
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
fn fixture(name: &str) -> Value {
|
fn fixture(name: &str) -> Value {
|
||||||
let path = format!("{}/testdata/{name}", env!("CARGO_MANIFEST_DIR"));
|
let path = format!("{}/testdata/{name}", env!("CARGO_MANIFEST_DIR"));
|
||||||
@@ -539,6 +601,19 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn points_just_before_a_cusp_are_read_in_the_next_house() {
|
||||||
|
let cusps = json!([{"house": 10, "longitude": 300.0}, {"house": 11, "longitude": 319.0}]);
|
||||||
|
// Moon at 17° with the 11th cusp at 19°: an astrologer reads it in the 11th.
|
||||||
|
assert_eq!(read_house(Some(317.0), 10, &cusps), (11, Some(2.0)));
|
||||||
|
assert_eq!(house_text(Some(317.0), 10, &cusps), "house 11 (on the cusp: 2°00' before it, formally house 10)");
|
||||||
|
assert_eq!(read_house(Some(313.0), 10, &cusps), (10, None));
|
||||||
|
assert_eq!(read_house(None, 10, &cusps), (10, None));
|
||||||
|
// across 0° Aries, and from the 12th to the 1st
|
||||||
|
let cusps = json!([{"house": 1, "longitude": 2.0}]);
|
||||||
|
assert_eq!(read_house(Some(358.5), 12, &cusps), (1, Some(3.5)));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn natal_with_birth_time() {
|
fn natal_with_birth_time() {
|
||||||
let text = natal(&fixture("natal-1990-03-15.json"));
|
let text = natal(&fixture("natal-1990-03-15.json"));
|
||||||
@@ -553,7 +628,8 @@ mod tests {
|
|||||||
"House cusps: 1 Leo 19°23' | 2 Virgo 9°35'",
|
"House cusps: 1 Leo 19°23' | 2 Virgo 9°35'",
|
||||||
"- Moon trine Chiron (orb 0.1°, applying)",
|
"- Moon trine Chiron (orb 0.1°, applying)",
|
||||||
"- Elements: air 2 (Venus, Mars); earth 3 (Saturn, Uranus, Neptune); fire 0;",
|
"- Elements: air 2 (Venus, Mars); earth 3 (Saturn, Uranus, Neptune); fire 0;",
|
||||||
"- Part of Fortune: Aries 5°10', house 8",
|
// 4' before the 9th cusp: read in the 9th
|
||||||
|
"- Part of Fortune: Aries 5°10', house 9 (on the cusp: 0°04' before it, formally house 8)",
|
||||||
] {
|
] {
|
||||||
assert!(text.contains(expected), "missing '{expected}' in:\n{text}");
|
assert!(text.contains(expected), "missing '{expected}' in:\n{text}");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ pub struct PreviewJob {
|
|||||||
pub kind: String,
|
pub kind: String,
|
||||||
pub chart_id: Option<Uuid>,
|
pub chart_id: Option<Uuid>,
|
||||||
pub synastry_id: Option<Uuid>,
|
pub synastry_id: Option<Uuid>,
|
||||||
|
pub forecast_id: Option<Uuid>,
|
||||||
pub language: String,
|
pub language: String,
|
||||||
pub model: String,
|
pub model: String,
|
||||||
pub system: String,
|
pub system: String,
|
||||||
@@ -159,7 +160,7 @@ impl Analyzer {
|
|||||||
"UPDATE prompt_previews SET status = 'running', started_at = now() \
|
"UPDATE prompt_previews SET status = 'running', started_at = now() \
|
||||||
WHERE id = (SELECT id FROM prompt_previews WHERE status = 'pending' \
|
WHERE id = (SELECT id FROM prompt_previews WHERE status = 'pending' \
|
||||||
ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED) \
|
ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED) \
|
||||||
RETURNING id, kind, chart_id, synastry_id, language, model, system",
|
RETURNING id, kind, chart_id, synastry_id, forecast_id, language, model, system",
|
||||||
)
|
)
|
||||||
.fetch_optional(&self.db)
|
.fetch_optional(&self.db)
|
||||||
.await?;
|
.await?;
|
||||||
@@ -177,7 +178,8 @@ impl Analyzer {
|
|||||||
Kind::parse(&job.kind).ok_or_else(|| LlmError::Permanent(format!("unknown kind '{}'", job.kind)))?;
|
Kind::parse(&job.kind).ok_or_else(|| LlmError::Permanent(format!("unknown kind '{}'", job.kind)))?;
|
||||||
let text = match kind {
|
let text = match kind {
|
||||||
Kind::Synastry => self.synastry_text(job.synastry_id).await?,
|
Kind::Synastry => self.synastry_text(job.synastry_id).await?,
|
||||||
_ => self.natal_text(job.chart_id).await?,
|
Kind::Forecast => self.forecast_text(job.forecast_id).await?,
|
||||||
|
Kind::Natal | Kind::Summary => self.natal_text(job.chart_id).await?,
|
||||||
};
|
};
|
||||||
let built = prompt::build(kind, &job.language, &text, Some(&job.system));
|
let built = prompt::build(kind, &job.language, &text, Some(&job.system));
|
||||||
let mut c = self.llm.complete(&job.model, &built).await?;
|
let mut c = self.llm.complete(&job.model, &built).await?;
|
||||||
@@ -293,7 +295,11 @@ impl Analyzer {
|
|||||||
if let Some((Some(user), units, kind)) = row
|
if let Some((Some(user), units, kind)) = row
|
||||||
&& units > 0
|
&& units > 0
|
||||||
{
|
{
|
||||||
let unit = if kind == "synastry" { "synastry" } else { "natal" };
|
let unit = match kind.as_str() {
|
||||||
|
"synastry" => "synastry",
|
||||||
|
"forecast" => "forecast",
|
||||||
|
_ => "natal",
|
||||||
|
};
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason, analysis_id, note) \
|
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason, analysis_id, note) \
|
||||||
VALUES ($1, $2, $3, $4, 'refund', $5, 'analysis failed') ON CONFLICT DO NOTHING",
|
VALUES ($1, $2, $3, $4, 'refund', $5, 'analysis failed') ON CONFLICT DO NOTHING",
|
||||||
|
|||||||
@@ -400,8 +400,10 @@ mod analyses {
|
|||||||
assert_eq!(body["provider"]["require_parameters"], true);
|
assert_eq!(body["provider"]["require_parameters"], true);
|
||||||
let system = body["messages"][0]["content"].as_str().unwrap();
|
let system = body["messages"][0]["content"].as_str().unwrap();
|
||||||
let user = body["messages"][1]["content"].as_str().unwrap();
|
let user = body["messages"][1]["content"].as_str().unwrap();
|
||||||
assert!(system.contains("Write in Hungarian.") && system.contains("Szaturnusz"));
|
assert!(system.contains("Magyarul írj") && system.contains("Szaturnusz"));
|
||||||
assert!(user.contains("- Sun: Pisces 24°42', house 8") && user.contains("- personality: "));
|
assert!(
|
||||||
|
user.contains("- Sun: Pisces 24°42', house 8") && user.contains("- personality: Az alapvető identitás")
|
||||||
|
);
|
||||||
// No birth data in the prompt.
|
// No birth data in the prompt.
|
||||||
for secret in ["1990", "14:30", "Szeged", "Hungary"] {
|
for secret in ["1990", "14:30", "Szeged", "Hungary"] {
|
||||||
assert!(!user.contains(secret) && !system.contains(secret), "{secret} leaked");
|
assert!(!user.contains(secret) && !system.contains(secret), "{secret} leaked");
|
||||||
|
|||||||
Reference in New Issue
Block a user