Paid detailed analyses with per-kind units; example analysis page
- Credits become analysis units (migration 0006): a natal analysis uses one 'natal' unit, a synastry analysis one 'synastry' unit. No monthly free credits, no model tiers: ANALYSIS_MODEL (default Opus 5.5) writes every paid analysis. Admins grant units per kind; the worker refunds the right unit on failure. - Chart page: the detailed analysis card (offer with units left and a confirmation, progress while writing, the finished six sections). - Public /pelda page: a full Opus analysis of a made-up chart, with the free summary and a login call to action. - The worker sends the JSON schema with properties in 'required' order. serde_json sorted them, so the title came after ~9000 tokens of text and Opus sometimes left it empty (3 failed attempts in a live test); with the order fixed the same analysis succeeded at the first try. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
//! Text analyses (LLM) of charts and synastries.
|
||||
//!
|
||||
//! A request creates a `pending` analysis and spends credits; the worker
|
||||
//! A request creates a `pending` analysis and spends one unit of its kind
|
||||
//! (`natal` or `synastry`, see [`credits`]); 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.
|
||||
@@ -25,7 +26,7 @@ use super::synastries::{load_synastry, visible_synastry};
|
||||
use super::{IdPath, St};
|
||||
use crate::AppState;
|
||||
use crate::auth::AuthUser;
|
||||
use crate::credits;
|
||||
use crate::credits::{self, Unit};
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{rfc3339, rfc3339_opt, sha256_hex};
|
||||
|
||||
@@ -93,8 +94,6 @@ pub async fn can_see(db: &PgPool, analysis: &AnalysisRow, user: Uuid) -> Result<
|
||||
pub struct AnalysisRequest {
|
||||
/// Defaults to the user's locale.
|
||||
language: Option<String>,
|
||||
/// One of the configured models; defaults to the first.
|
||||
model: Option<String>,
|
||||
}
|
||||
|
||||
/// The request body is optional: empty means all defaults.
|
||||
@@ -118,34 +117,25 @@ async fn request(
|
||||
req: AnalysisRequest,
|
||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||
let language = validate_locale(state, Some(req.language.as_deref().unwrap_or(&auth.user.locale)))?;
|
||||
let models = &state.config.llm_models;
|
||||
let chosen = match &req.model {
|
||||
None => &models[0],
|
||||
Some(id) => models.iter().find(|m| &m.id == id).ok_or_else(|| {
|
||||
let available: Vec<&str> = models.iter().map(|m| m.id.as_str()).collect();
|
||||
ApiError::BadRequest(format!("unknown model '{id}'; available: {}", available.join(", ")))
|
||||
})?,
|
||||
let unit = match target {
|
||||
Target::Synastry { .. } => Unit::Synastry,
|
||||
_ => Unit::Natal,
|
||||
};
|
||||
if let Some(role) = chosen.role
|
||||
&& !auth.user.has_access(role)
|
||||
{
|
||||
return Err(ApiError::Forbidden(format!("the model '{}' needs the '{}' role", chosen.id, role.as_str())));
|
||||
}
|
||||
let cost = chosen.credits;
|
||||
let (status, row) = queue(state, auth.id(), &target, &language, &chosen.id, cost).await?;
|
||||
let model = state.config.analysis_model.clone();
|
||||
let (status, row) = queue(state, auth.id(), &target, &language, &model, Some(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 `cost` credits). 200, 201 and 202 respectively.
|
||||
/// 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,
|
||||
cost: i32,
|
||||
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),
|
||||
@@ -206,7 +196,7 @@ async fn queue(
|
||||
return Ok((StatusCode::CREATED, row));
|
||||
}
|
||||
|
||||
// New analysis: spend credits and queue it for the worker.
|
||||
// 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)
|
||||
@@ -222,12 +212,12 @@ async fn queue(
|
||||
.bind(None::<Value>)
|
||||
.bind(None::<i32>)
|
||||
.bind(None::<i32>)
|
||||
.bind(cost)
|
||||
.bind(i32::from(unit.is_some()))
|
||||
.bind(None::<OffsetDateTime>)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if cost > 0 {
|
||||
credits::spend(&mut tx, user, cost, state.config.monthly_free_credits, "analysis", Some(id)).await?;
|
||||
if let Some(unit) = unit {
|
||||
credits::spend(&mut tx, user, unit, id).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok((StatusCode::ACCEPTED, row))
|
||||
@@ -238,7 +228,7 @@ async fn queue(
|
||||
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, 0).await?.1)
|
||||
Ok(queue(state, owner.id(), &target, &owner.user.locale, &model, None).await?.1)
|
||||
}
|
||||
|
||||
pub async fn summary_for_chart(
|
||||
|
||||
Reference in New Issue
Block a user