Files
sorsfonalak/services/backend/src/routes/prompts.rs
T

281 lines
10 KiB
Rust
Raw Normal View History

2026-11-17 14:25:08 +00:00
//! Editable system prompts of the analyses (admin only).
//!
//! Every save adds a row to `prompt_revisions`; the newest row of a
//! (kind, language) is in force, `system` NULL meaning the built-in text.
//! New analyses record the revision in `prompt_version`, so analyses that
//! are already written or queued keep the text they were started with.
//!
//! A draft can be tried on one of the admin's own charts first: a row in
//! `prompt_previews` that the worker writes like an analysis, but it is never
//! shown to users, cached or charged.
2026-11-17 14:25:08 +00:00
use analysis_prompt::{Kind, default_system, user_template};
use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
2026-11-17 14:25:08 +00:00
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use sqlx::PgPool;
use time::OffsetDateTime;
use uuid::Uuid;
2026-11-17 14:25:08 +00:00
use super::{Body, IdPath, St};
2026-11-17 14:25:08 +00:00
use crate::AppState;
use crate::auth::AdminUser;
use crate::error::{ApiError, ApiResult};
use crate::views::{rfc3339, rfc3339_opt};
2026-11-17 14:25:08 +00:00
/// The kinds whose prompt the admin page edits.
const EDITABLE: [Kind; 3] = [Kind::Summary, Kind::Natal, Kind::Synastry];
2026-11-17 14:25:08 +00:00
const MAX_CHARS: usize = 50_000;
const HISTORY: i64 = 20;
/// Test runs of one admin waiting or being written at the same time.
const MAX_OPEN_PREVIEWS: i64 = 3;
2026-11-17 14:25:08 +00:00
/// The revision id of an admin-edited prompt in force, `None` for the built-in one.
pub async fn current_revision(db: &PgPool, kind: &str, language: &str) -> Result<Option<i64>, sqlx::Error> {
let row: Option<(i64, bool)> = sqlx::query_as(
"SELECT id, system IS NOT NULL FROM prompt_revisions WHERE kind = $1 AND language = $2 ORDER BY id DESC LIMIT 1",
)
.bind(kind)
.bind(language)
.fetch_optional(db)
.await?;
Ok(row.filter(|(_, custom)| *custom).map(|(id, _)| id))
}
type RevisionRow = (i64, Option<String>, OffsetDateTime, Option<String>);
async fn entry(db: &PgPool, kind: Kind, language: &str) -> Result<Value, sqlx::Error> {
let rows: Vec<RevisionRow> = sqlx::query_as(
"SELECT r.id, r.system, r.created_at, u.email FROM prompt_revisions r \
LEFT JOIN users u ON u.id = r.created_by \
WHERE r.kind = $1 AND r.language = $2 ORDER BY r.id DESC LIMIT $3",
)
.bind(kind.as_str())
.bind(language)
.bind(HISTORY)
.fetch_all(db)
.await?;
let default = default_system(kind, language);
let current = rows.first();
let history: Vec<Value> = rows
.iter()
.map(|(id, system, at, by)| {
json!({"id": id, "custom": system.is_some(), "system": system, "created_at": rfc3339(*at), "created_by": by})
})
.collect();
Ok(json!({
"kind": kind.as_str(),
"language": language,
"system": current.and_then(|r| r.1.clone()).unwrap_or_else(|| default.clone()),
"custom": current.is_some_and(|r| r.1.is_some()),
"updated_at": current.map(|r| rfc3339(r.2)),
"updated_by": current.and_then(|r| r.3.clone()),
"default": default,
"user_template": user_template(kind),
"history": history,
}))
}
pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult<Json<Value>> {
let mut prompts = Vec::new();
for kind in EDITABLE {
for language in &state.config.supported_locales {
prompts.push(entry(&state.db, kind, language).await?);
}
}
Ok(Json(json!({ "prompts": prompts })))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SavePrompt {
/// The new system prompt; `null` restores the built-in one.
system: Option<String>,
}
fn parse_target(state: &AppState, kind: &str, language: &str) -> Result<Kind, ApiError> {
let kind = Kind::parse(kind).filter(|k| EDITABLE.contains(k)).ok_or(ApiError::NotFound("prompt"))?;
if !state.config.supported_locales.iter().any(|l| l == language) {
return Err(ApiError::NotFound("prompt"));
}
Ok(kind)
}
/// Trims a submitted prompt and checks its length.
fn clean_system(text: &str) -> Result<String, ApiError> {
let text = text.trim().replace("\r\n", "\n");
if text.is_empty() {
return Err(ApiError::BadRequest("the prompt must not be empty".into()));
}
if text.chars().count() > MAX_CHARS {
return Err(ApiError::BadRequest(format!("the prompt is longer than {MAX_CHARS} characters")));
}
Ok(text)
}
2026-11-17 14:25:08 +00:00
pub async fn save(
State(state): St,
AdminUser(admin): AdminUser,
WithRejection(Path((kind, language)), _): WithRejection<Path<(String, String)>, ApiError>,
WithRejection(Json(req), _): Body<SavePrompt>,
) -> ApiResult<Json<Value>> {
let kind = parse_target(&state, &kind, &language)?;
let default = default_system(kind, &language);
// The built-in text is stored as NULL, so later code changes reach it.
let system = match req.system.as_deref().map(clean_system).transpose()? {
2026-11-17 14:25:08 +00:00
Some(s) if s == default.trim() => None,
other => other,
};
let current: Option<(Option<String>,)> = sqlx::query_as(
"SELECT system FROM prompt_revisions WHERE kind = $1 AND language = $2 ORDER BY id DESC LIMIT 1",
)
.bind(kind.as_str())
.bind(&language)
.fetch_optional(&state.db)
.await?;
let unchanged = match &current {
Some((text,)) => *text == system,
None => system.is_none(),
};
if !unchanged {
sqlx::query("INSERT INTO prompt_revisions (kind, language, system, created_by) VALUES ($1, $2, $3, $4)")
.bind(kind.as_str())
.bind(&language)
.bind(&system)
.bind(admin.id())
.execute(&state.db)
.await?;
tracing::info!(admin = %admin.id(), kind = kind.as_str(), %language, custom = system.is_some(), "prompt changed");
}
Ok(Json(entry(&state.db, kind, &language).await?))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StartPreview {
/// The draft to try (it need not be saved).
system: String,
/// One of the admin's own charts (own or a person), for a summary or natal analysis.
chart_id: Option<Uuid>,
/// One of the admin's own comparisons, for a synastry analysis.
synastry_id: Option<Uuid>,
}
#[derive(sqlx::FromRow)]
struct PreviewRow {
id: Uuid,
kind: String,
chart_id: Option<Uuid>,
synastry_id: Option<Uuid>,
language: String,
model: String,
status: String,
content: Option<Value>,
error: Option<String>,
model_used: Option<String>,
input_tokens: Option<i32>,
output_tokens: Option<i32>,
cost_usd: Option<f64>,
created_at: OffsetDateTime,
started_at: Option<OffsetDateTime>,
completed_at: Option<OffsetDateTime>,
}
const PREVIEW_COLUMNS: &str = "id, kind, chart_id, synastry_id, language, model, status, content, error, model_used, \
input_tokens, output_tokens, cost_usd, created_at, started_at, completed_at";
impl PreviewRow {
fn view(self) -> Value {
let seconds = self.started_at.zip(self.completed_at).map(|(s, c)| (c - s).whole_seconds());
json!({
"id": self.id, "kind": self.kind, "chart_id": self.chart_id, "synastry_id": self.synastry_id,
"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,
"output_tokens": self.output_tokens, "cost_usd": self.cost_usd, "created_at": rfc3339(self.created_at),
"completed_at": rfc3339_opt(self.completed_at), "seconds": seconds,
})
}
}
pub async fn start_preview(
State(state): St,
AdminUser(admin): AdminUser,
WithRejection(Path((kind, language)), _): WithRejection<Path<(String, String)>, ApiError>,
WithRejection(Json(req), _): Body<StartPreview>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let kind = parse_target(&state, &kind, &language)?;
let system = clean_system(&req.system)?;
// The target must be the admin's own: a chart, or for a synastry analysis a comparison.
let (chart_id, synastry_id, found) = match (kind, req.chart_id, req.synastry_id) {
(Kind::Synastry, None, Some(id)) => {
let row: Option<(Uuid,)> = sqlx::query_as("SELECT id FROM synastries WHERE id = $1 AND owner_id = $2")
.bind(id)
.bind(admin.id())
.fetch_optional(&state.db)
.await?;
(None, Some(id), row.map(|_| "synastry"))
}
(Kind::Summary | Kind::Natal, Some(id), None) => {
let row: Option<(Uuid,)> = sqlx::query_as("SELECT id FROM charts WHERE id = $1 AND owner_id = $2")
.bind(id)
.bind(admin.id())
.fetch_optional(&state.db)
.await?;
(Some(id), None, row.map(|_| "chart"))
}
(Kind::Synastry, ..) => return Err(ApiError::BadRequest("a synastry analysis needs synastry_id".into())),
_ => return Err(ApiError::BadRequest("this analysis needs chart_id".into())),
};
if found.is_none() {
return Err(ApiError::NotFound(if synastry_id.is_some() { "synastry" } else { "chart" }));
}
let (open,): (i64,) = sqlx::query_as(
"SELECT count(*) FROM prompt_previews WHERE created_by = $1 AND status IN ('pending', 'running')",
)
.bind(admin.id())
.fetch_one(&state.db)
.await?;
if open >= MAX_OPEN_PREVIEWS {
return Err(ApiError::conflict(
"too_many_previews",
"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 row: PreviewRow = sqlx::query_as(&format!(
"INSERT INTO prompt_previews (id, kind, chart_id, synastry_id, language, model, system, created_by) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING {PREVIEW_COLUMNS}"
))
.bind(Uuid::now_v7())
.bind(kind.as_str())
.bind(chart_id)
.bind(synastry_id)
.bind(&language)
.bind(model)
.bind(&system)
.bind(admin.id())
.fetch_one(&state.db)
.await?;
Ok((StatusCode::ACCEPTED, Json(row.view())))
}
pub async fn get_preview(
State(state): St,
AdminUser(admin): AdminUser,
WithRejection(Path(id), _): IdPath,
) -> ApiResult<Json<Value>> {
let row: Option<PreviewRow> =
sqlx::query_as(&format!("SELECT {PREVIEW_COLUMNS} FROM prompt_previews WHERE id = $1 AND created_by = $2"))
.bind(id)
.bind(admin.id())
.fetch_optional(&state.db)
.await?;
Ok(Json(row.ok_or(ApiError::NotFound("preview"))?.view()))
}