Hungarian prompts in Hungarian, model choice per analysis kind, admin regenerate
CI / test (push) Successful in 57s
CI / build (push) Successful in 4m48s
CI / deploy (push) Skipped

- The built-in Hungarian system prompts and the user message frame are written in Hungarian
- Admin page Modellek: the model of each analysis kind, chosen from the OpenRouter list
  (structured-output models only) with prices and a cost estimate per analysis
- Admin: regenerate any analysis in place with the current prompt and model (no charge)
- Fix: a failed forecast analysis refunds a forecast unit, not a natal one

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-18 13:15:57 +00:00
co-authored by Claude Opus 5.5
parent 23975a8369
commit 27de820091
24 changed files with 981 additions and 71 deletions
+6 -3
View File
@@ -20,8 +20,9 @@ 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 |
| `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 |
| `ANALYSIS_MODEL` | `anthropic/claude-opus-5.5` | ez írja a fizetős részletes elemzéseket |
| `SUMMARY_MODEL` | `anthropic/claude-sonnet-5.5` | ez írja minden mentett képlet ingyenes rövid összefoglalóját (kb. 1 cent darabonként) |
| `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` | alapból ez írja minden mentett képlet ingyenes rövid összefoglalóját (kb. 1 cent darabonként) |
| `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 |
| `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.
- **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.
- **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).
+7 -1
View File
@@ -61,6 +61,9 @@ pub struct Config {
/// `SUMMARY_MODEL`: writes the free short summary of every saved chart
/// (default `anthropic/claude-sonnet-5.5`, about 1 US cent each).
pub summary_model: String,
/// `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,
/// `MAX_CHARTS_PER_USER` (default 1000): a safety cap.
@@ -121,6 +124,8 @@ impl Config {
supported_locales,
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()),
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)?,
free_person_slots: parsed("FREE_PERSON_SLOTS", 0)?,
@@ -141,7 +146,7 @@ impl Config {
pub fn for_tests(database_url: String, horoscope_api_url: String, google_jwks_url: String) -> Self {
Self {
database_url,
horoscope_api_url,
horoscope_api_url: horoscope_api_url.clone(),
public_base_url: "https://sorsfonalak.test".into(),
cors_allowed_origins: vec!["https://sorsfonalak.test".into()],
cookie_secure: true,
@@ -155,6 +160,7 @@ impl Config {
supported_locales: vec!["hu".into(), "en".into()],
analysis_model: "anthropic/claude-test".into(),
summary_model: "anthropic/claude-summary".into(),
openrouter_models_url: format!("{horoscope_api_url}/openrouter/models"),
prompt_version: "v1".into(),
max_charts_per_user: 50,
free_person_slots: 5,
+3
View File
@@ -13,6 +13,7 @@ mod config;
mod credits;
mod error;
mod google;
mod models;
mod packages;
mod persons;
mod routes;
@@ -39,6 +40,7 @@ pub struct AppState {
pub horoscope: HoroscopeClient,
pub google: GoogleVerifier,
pub login_limiter: LoginLimiter,
pub models: models::Catalog,
}
impl AppState {
@@ -47,6 +49,7 @@ impl AppState {
horoscope: HoroscopeClient::new(&config.horoscope_api_url),
google: GoogleVerifier::new(config.google_client_ids.clone(), config.google_jwks_url.clone()),
login_limiter: LoginLimiter::new(10, Duration::from_secs(15 * 60)),
models: models::Catalog::new(&config.openrouter_models_url),
db,
config,
}
+117
View File
@@ -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)
}
}
+84 -17
View File
@@ -9,6 +9,7 @@
//! Every saved chart also gets a free short summary (`summary` kind, written
//! by `SUMMARY_MODEL`); the detailed analyses are paid.
use analysis_prompt::Kind;
use axum::Json;
use axum::body::Bytes;
use axum::extract::{Path, State};
@@ -135,20 +136,37 @@ async fn request(
Target::Forecast { .. } => Some(Unit::Forecast),
_ => Some(Unit::Natal),
};
let model = state.config.analysis_model.clone();
let (status, row) = queue(state, auth.id(), &target, &language, &model, unit).await?;
let (status, row) = queue(state, auth.id(), &target, &language, unit).await?;
Ok((status, Json(row.view())))
}
/// 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
/// new one (spending one `unit`, if given). 200, 201 and 202 respectively.
/// 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,
user: Uuid,
target: &Target,
language: &str,
model: &str,
unit: Option<Unit>,
) -> Result<(StatusCode, AnalysisRow), ApiError> {
let (kind, hash, chart_id, synastry_id, forecast_id) = match target {
@@ -157,14 +175,8 @@ pub(super) async fn queue(
Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id), None),
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
// its analysis when the prompt changes; copying from another chart needs the same revision.
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(),
};
let model = &crate::models::model_for(state, Kind::parse(kind).expect("known kind")).await?;
let (cache_key, prompt_version) = &versions(state, kind, hash, model, language).await?;
// Already requested for this chart/synastry: return it.
let existing: Option<AnalysisRow> = sqlx::query_as(&format!(
@@ -174,7 +186,7 @@ pub(super) async fn queue(
))
.bind(chart_id)
.bind(synastry_id)
.bind(&cache_key)
.bind(cache_key)
.bind(forecast_id)
.fetch_optional(&state.db)
.await?;
@@ -195,7 +207,7 @@ pub(super) async fn queue(
"SELECT content, input_tokens, output_tokens FROM analyses \
WHERE cache_key = $1 AND prompt_version = $2 AND status = 'done' LIMIT 1",
)
.bind(&cache_key)
.bind(cache_key)
.bind(prompt_version)
.fetch_optional(&state.db)
.await?;
@@ -209,7 +221,7 @@ pub(super) async fn queue(
.bind(language)
.bind(model)
.bind(prompt_version)
.bind(&cache_key)
.bind(cache_key)
.bind("done")
.bind(content)
.bind(input_tokens)
@@ -233,7 +245,7 @@ pub(super) async fn queue(
.bind(language)
.bind(model)
.bind(prompt_version)
.bind(&cache_key)
.bind(cache_key)
.bind("pending")
.bind(None::<Value>)
.bind(None::<i32>)
@@ -254,8 +266,7 @@ pub(super) async fn queue(
/// it does not exist yet or the last attempt failed.
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 model = state.config.summary_model.clone();
Ok(queue(state, owner.id(), &target, &owner.user.locale, &model, None).await?.1)
Ok(queue(state, owner.id(), &target, &owner.user.locale, None).await?.1)
}
pub async fn summary_for_chart(
@@ -345,3 +356,59 @@ pub async fn request_for_forecast(
let req = optional_body(&body)?;
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()))
}
+5
View File
@@ -12,6 +12,7 @@ mod auth;
mod charts;
mod forecasts;
mod invitations;
mod models;
mod payments;
mod prompts;
mod recalculate;
@@ -112,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}/preview", post(prompts::start_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(
TraceLayer::new_for_http()
+110
View File
@@ -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?))
}
+1 -4
View File
@@ -246,10 +246,7 @@ pub async fn start_preview(
"Egyszerre legfeljebb három próba futhat. Várd meg, amíg valamelyik elkészül.",
));
}
let model = match kind {
Kind::Summary => &state.config.summary_model,
_ => &state.config.analysis_model,
};
let model = &crate::models::model_for(&state, kind).await?;
let row: PreviewRow = sqlx::query_as(&format!(
"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, $9) RETURNING {PREVIEW_COLUMNS}"
+4 -6
View File
@@ -91,25 +91,23 @@ pub async fn run(state: &AppState) -> anyhow::Result<()> {
tracing::info!(count = forecast_hashes.len(), "forecasts recalculated");
let deleted = sqlx::query("DELETE FROM analyses").execute(db).await?.rows_affected();
let summary_model = &state.config.summary_model;
let analysis_model = &state.config.analysis_model;
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, summary_model, None).await?;
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, analysis_model, None).await?;
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?, analysis_model, None).await?;
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?, analysis_model, None).await?;
queue(state, owner, &target, &locale(db, owner).await?, None).await?;
queued += 1;
}
tracing::info!(deleted, queued, "analyses queued again");
+88
View File
@@ -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 {
let app = Router::new()
.route("/openrouter/models", get(fake_openrouter_models))
.route("/v1/natal", post(fake_natal))
.route("/v1/synastry", post(fake_synastry))
.route("/v1/forecast", post(fake_forecast))
@@ -1460,3 +1476,75 @@ async fn recalculate_refreshes_calculations_and_queues_every_analysis_again(pool
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(&regenerate_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);
}