Hungarian prompts in Hungarian, model choice per analysis kind, admin regenerate
- 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:
@@ -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()))
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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?))
|
||||
}
|
||||
@@ -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}"
|
||||
|
||||
@@ -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");
|
||||
|
||||
Reference in New Issue
Block a user