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

271 lines
9.2 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; 2] = [Kind::Summary, Kind::Natal];
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).
chart_id: Uuid,
}
type PreviewRow = (
Uuid,
String,
Uuid,
String,
String,
String,
Option<Value>,
Option<String>,
Option<String>,
Option<i32>,
Option<i32>,
Option<f64>,
OffsetDateTime,
Option<OffsetDateTime>,
Option<OffsetDateTime>,
);
const PREVIEW_COLUMNS: &str = "id, kind, chart_id, language, model, status, content, error, model_used, \
input_tokens, output_tokens, cost_usd, created_at, started_at, completed_at";
fn preview_view(row: PreviewRow) -> Value {
let (
id,
kind,
chart_id,
language,
model,
status,
content,
error,
model_used,
input,
output,
cost,
created,
started,
completed,
) = row;
let seconds = started.zip(completed).map(|(s, c)| (c - s).whole_seconds());
json!({
"id": id, "kind": kind, "chart_id": chart_id, "language": language, "model": model, "status": status,
"content": content, "error": error, "model_used": model_used, "input_tokens": input, "output_tokens": output,
"cost_usd": cost, "created_at": rfc3339(created), "completed_at": rfc3339_opt(completed), "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)?;
let own: Option<(Uuid,)> = sqlx::query_as("SELECT id FROM charts WHERE id = $1 AND owner_id = $2")
.bind(req.chart_id)
.bind(admin.id())
.fetch_optional(&state.db)
.await?;
own.ok_or(ApiError::NotFound("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, language, model, system, created_by) \
VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING {PREVIEW_COLUMNS}"
))
.bind(Uuid::now_v7())
.bind(kind.as_str())
.bind(req.chart_id)
.bind(&language)
.bind(model)
.bind(&system)
.bind(admin.id())
.fetch_one(&state.db)
.await?;
Ok((StatusCode::ACCEPTED, Json(preview_view(row))))
}
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(preview_view(row.ok_or(ApiError::NotFound("preview"))?)))
}