The system prompts of the free summary and the paid detailed analysis can be edited per language under /admin/promptok. Every save is a new row in prompt_revisions (NULL = built-in text); new analyses record the revision in prompt_version (v2-r<id>) and the worker uses exactly that text. Existing analyses stay; the cross-user cache only copies results of the same revision. The prompt code moves to the shared analysis-prompt crate so the backend can show the built-in text. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
312 lines
11 KiB
Rust
312 lines
11 KiB
Rust
//! Text analyses (LLM) of charts and synastries.
|
|
//!
|
|
//! A request creates a `pending` analysis and spends one unit of its kind
|
|
//! (`natal` or `synastry`, see [`credits`]; admins pay nothing); the worker
|
|
//! writes the text later. A finished analysis with the same cache key (same
|
|
//! chart or synastry hash, prompt version, model and language) is copied
|
|
//! instead, free of charge, so the same chart is never paid for twice.
|
|
//!
|
|
//! Every saved chart also gets a free short summary (`summary` kind, written
|
|
//! by `SUMMARY_MODEL`); the detailed analyses are paid.
|
|
|
|
use axum::Json;
|
|
use axum::body::Bytes;
|
|
use axum::extract::{Path, State};
|
|
use axum::http::StatusCode;
|
|
use axum_extra::extract::WithRejection;
|
|
use serde::Deserialize;
|
|
use serde_json::{Value, json};
|
|
use sqlx::PgPool;
|
|
use time::OffsetDateTime;
|
|
use uuid::Uuid;
|
|
|
|
use super::auth::validate_locale;
|
|
use super::charts::{ChartRow, find_chart, owned_chart};
|
|
use super::synastries::{load_synastry, visible_synastry};
|
|
use super::{IdPath, St};
|
|
use crate::AppState;
|
|
use crate::auth::AuthUser;
|
|
use crate::credits::{self, Unit};
|
|
use crate::error::{ApiError, ApiResult};
|
|
use crate::views::{rfc3339, rfc3339_opt, sha256_hex};
|
|
use db::Role;
|
|
|
|
#[derive(Debug, Clone, sqlx::FromRow)]
|
|
pub struct AnalysisRow {
|
|
pub id: Uuid,
|
|
pub kind: String,
|
|
pub chart_id: Option<Uuid>,
|
|
pub synastry_id: Option<Uuid>,
|
|
pub language: String,
|
|
pub model: String,
|
|
pub prompt_version: String,
|
|
pub status: String,
|
|
pub content: Option<Value>,
|
|
pub error: Option<String>,
|
|
pub credits_charged: i32,
|
|
pub created_at: OffsetDateTime,
|
|
pub completed_at: Option<OffsetDateTime>,
|
|
}
|
|
|
|
const ANALYSIS_COLUMNS: &str = "id, kind, chart_id, synastry_id, language, model, prompt_version, status, content, \
|
|
error, credits_charged, created_at, completed_at";
|
|
|
|
impl AnalysisRow {
|
|
pub fn view(&self) -> Value {
|
|
json!({
|
|
"id": self.id,
|
|
"kind": self.kind,
|
|
"chart_id": self.chart_id,
|
|
"synastry_id": self.synastry_id,
|
|
"language": self.language,
|
|
"model": self.model,
|
|
"prompt_version": self.prompt_version,
|
|
"status": self.status,
|
|
"content": self.content,
|
|
"error": self.error,
|
|
"credits_charged": self.credits_charged,
|
|
"created_at": rfc3339(self.created_at),
|
|
"completed_at": rfc3339_opt(self.completed_at),
|
|
})
|
|
}
|
|
}
|
|
|
|
pub async fn find_analysis(db: &PgPool, id: Uuid) -> Result<Option<AnalysisRow>, ApiError> {
|
|
Ok(sqlx::query_as(&format!("SELECT {ANALYSIS_COLUMNS} FROM analyses WHERE id = $1"))
|
|
.bind(id)
|
|
.fetch_optional(db)
|
|
.await?)
|
|
}
|
|
|
|
/// Whether `user` may read the analysis: the chart's owner, or a member of
|
|
/// the synastry.
|
|
pub async fn can_see(db: &PgPool, analysis: &AnalysisRow, user: Uuid) -> Result<bool, ApiError> {
|
|
if let Some(chart_id) = analysis.chart_id {
|
|
return Ok(find_chart(db, chart_id).await?.is_some_and(|c| c.owner_id == user));
|
|
}
|
|
if let Some(synastry_id) = analysis.synastry_id {
|
|
return Ok(load_synastry(db, synastry_id).await?.is_some_and(|s| s.is_member(user)));
|
|
}
|
|
Ok(false)
|
|
}
|
|
|
|
#[derive(Deserialize, Default)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct AnalysisRequest {
|
|
/// Defaults to the user's locale.
|
|
language: Option<String>,
|
|
}
|
|
|
|
/// The request body is optional: empty means all defaults.
|
|
fn optional_body(body: &[u8]) -> Result<AnalysisRequest, ApiError> {
|
|
if body.iter().all(u8::is_ascii_whitespace) {
|
|
return Ok(AnalysisRequest::default());
|
|
}
|
|
serde_json::from_slice(body).map_err(|e| ApiError::BadRequest(format!("invalid request body: {e}")))
|
|
}
|
|
|
|
enum Target {
|
|
Natal { chart_id: Uuid, hash: String },
|
|
Summary { chart_id: Uuid, hash: String },
|
|
Synastry { synastry_id: Uuid, hash: String },
|
|
}
|
|
|
|
async fn request(
|
|
state: &AppState,
|
|
auth: &AuthUser,
|
|
target: Target,
|
|
req: AnalysisRequest,
|
|
) -> ApiResult<(StatusCode, Json<Value>)> {
|
|
let language = validate_locale(state, Some(req.language.as_deref().unwrap_or(&auth.user.locale)))?;
|
|
// Admins get detailed analyses free of charge.
|
|
let unit = match target {
|
|
_ if auth.user.has_role(Role::Admin) => None,
|
|
Target::Synastry { .. } => Some(Unit::Synastry),
|
|
_ => Some(Unit::Natal),
|
|
};
|
|
let model = state.config.analysis_model.clone();
|
|
let (status, row) = queue(state, auth.id(), &target, &language, &model, 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.
|
|
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) = match target {
|
|
Target::Natal { chart_id, hash } => ("natal", hash, Some(*chart_id), None),
|
|
Target::Summary { chart_id, hash } => ("summary", hash, Some(*chart_id), None),
|
|
Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_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(),
|
|
};
|
|
|
|
// Already requested for this chart/synastry: return it.
|
|
let existing: Option<AnalysisRow> = sqlx::query_as(&format!(
|
|
"SELECT {ANALYSIS_COLUMNS} FROM analyses \
|
|
WHERE (chart_id = $1 OR synastry_id = $2) AND cache_key = $3 AND status <> 'failed' \
|
|
ORDER BY created_at DESC LIMIT 1"
|
|
))
|
|
.bind(chart_id)
|
|
.bind(synastry_id)
|
|
.bind(&cache_key)
|
|
.fetch_optional(&state.db)
|
|
.await?;
|
|
if let Some(row) = existing {
|
|
return Ok((StatusCode::OK, row));
|
|
}
|
|
|
|
let insert = format!(
|
|
"INSERT INTO analyses (id, kind, chart_id, synastry_id, requested_by, language, model, prompt_version, \
|
|
cache_key, status, content, input_tokens, output_tokens, credits_charged, completed_at) \
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15) RETURNING {ANALYSIS_COLUMNS}"
|
|
);
|
|
let id = Uuid::now_v7();
|
|
|
|
// The same chart elsewhere (another user, same birth data) was already analysed: copy it.
|
|
let cached: Option<(Value, Option<i32>, Option<i32>)> = sqlx::query_as(
|
|
"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(prompt_version)
|
|
.fetch_optional(&state.db)
|
|
.await?;
|
|
if let Some((content, input_tokens, output_tokens)) = cached {
|
|
let row: AnalysisRow = sqlx::query_as(&insert)
|
|
.bind(id)
|
|
.bind(kind)
|
|
.bind(chart_id)
|
|
.bind(synastry_id)
|
|
.bind(user)
|
|
.bind(language)
|
|
.bind(model)
|
|
.bind(prompt_version)
|
|
.bind(&cache_key)
|
|
.bind("done")
|
|
.bind(content)
|
|
.bind(input_tokens)
|
|
.bind(output_tokens)
|
|
.bind(0)
|
|
.bind(OffsetDateTime::now_utc())
|
|
.fetch_one(&state.db)
|
|
.await?;
|
|
return Ok((StatusCode::CREATED, row));
|
|
}
|
|
|
|
// New analysis: spend a unit and queue it for the worker.
|
|
let mut tx = state.db.begin().await?;
|
|
let row: AnalysisRow = sqlx::query_as(&insert)
|
|
.bind(id)
|
|
.bind(kind)
|
|
.bind(chart_id)
|
|
.bind(synastry_id)
|
|
.bind(user)
|
|
.bind(language)
|
|
.bind(model)
|
|
.bind(prompt_version)
|
|
.bind(&cache_key)
|
|
.bind("pending")
|
|
.bind(None::<Value>)
|
|
.bind(None::<i32>)
|
|
.bind(None::<i32>)
|
|
.bind(i32::from(unit.is_some()))
|
|
.bind(None::<OffsetDateTime>)
|
|
.fetch_one(&mut *tx)
|
|
.await?;
|
|
if let Some(unit) = unit {
|
|
credits::spend(&mut tx, user, unit, id).await?;
|
|
}
|
|
tx.commit().await?;
|
|
Ok((StatusCode::ACCEPTED, row))
|
|
}
|
|
|
|
/// The free short summary of a chart (in the owner's language): queued if
|
|
/// 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)
|
|
}
|
|
|
|
pub async fn summary_for_chart(
|
|
State(state): St,
|
|
auth: AuthUser,
|
|
WithRejection(Path(id), _): IdPath,
|
|
) -> ApiResult<Json<Value>> {
|
|
let chart = owned_chart(&state.db, id, auth.id()).await?;
|
|
Ok(Json(ensure_summary(&state, &auth, &chart).await?.view()))
|
|
}
|
|
|
|
async fn list_where(db: &PgPool, column: &str, id: Uuid) -> Result<Json<Value>, ApiError> {
|
|
let rows: Vec<AnalysisRow> = sqlx::query_as(&format!(
|
|
"SELECT {ANALYSIS_COLUMNS} FROM analyses WHERE {column} = $1 ORDER BY created_at DESC"
|
|
))
|
|
.bind(id)
|
|
.fetch_all(db)
|
|
.await?;
|
|
Ok(Json(json!({ "analyses": rows.iter().map(AnalysisRow::view).collect::<Vec<_>>() })))
|
|
}
|
|
|
|
pub async fn list_for_chart(
|
|
State(state): St,
|
|
auth: AuthUser,
|
|
WithRejection(Path(id), _): IdPath,
|
|
) -> ApiResult<Json<Value>> {
|
|
owned_chart(&state.db, id, auth.id()).await?;
|
|
list_where(&state.db, "chart_id", id).await
|
|
}
|
|
|
|
pub async fn request_for_chart(
|
|
State(state): St,
|
|
auth: AuthUser,
|
|
WithRejection(Path(id), _): IdPath,
|
|
body: Bytes,
|
|
) -> ApiResult<(StatusCode, Json<Value>)> {
|
|
let chart = owned_chart(&state.db, id, auth.id()).await?;
|
|
let req = optional_body(&body)?;
|
|
request(&state, &auth, Target::Natal { chart_id: chart.id, hash: chart.chart_hash }, req).await
|
|
}
|
|
|
|
pub async fn list_for_synastry(
|
|
State(state): St,
|
|
auth: AuthUser,
|
|
WithRejection(Path(id), _): IdPath,
|
|
) -> ApiResult<Json<Value>> {
|
|
visible_synastry(&state.db, id, auth.id()).await?;
|
|
list_where(&state.db, "synastry_id", id).await
|
|
}
|
|
|
|
pub async fn request_for_synastry(
|
|
State(state): St,
|
|
auth: AuthUser,
|
|
WithRejection(Path(id), _): IdPath,
|
|
body: Bytes,
|
|
) -> ApiResult<(StatusCode, Json<Value>)> {
|
|
let s = visible_synastry(&state.db, id, auth.id()).await?;
|
|
let req = optional_body(&body)?;
|
|
let target = Target::Synastry { synastry_id: s.synastry.id, hash: s.synastry.synastry_hash };
|
|
request(&state, &auth, target, req).await
|
|
}
|
|
|
|
pub async fn get_one(State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
|
|
let analysis = find_analysis(&state.db, id).await?.ok_or(ApiError::NotFound("analysis"))?;
|
|
if !can_see(&state.db, &analysis, auth.id()).await? {
|
|
return Err(ApiError::NotFound("analysis"));
|
|
}
|
|
Ok(Json(analysis.view()))
|
|
}
|