Questions about an analysis or forecast, answered by the model that wrote it
- 3 questions in every package, +5 questions add-on (1 000 Ft); question units, refund on failure - The answer sees the chart data, the analysis and earlier questions; at most 250 words - Editable question prompt (Promptok → Kérdés-válasz); admins regenerate answers - Package texts and FAQ updated Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -158,6 +158,7 @@ pub async fn export(State(state): St, auth: AuthUser) -> ApiResult<impl IntoResp
|
||||
"invites": rows("SELECT json_build_object('id', id, 'chart_id', inviter_chart_id, 'message', message, 'created_at', created_at, 'expires_at', expires_at, 'accepted_at', accepted_at) FROM synastry_invites WHERE inviter_id = $1").await?,
|
||||
"forecasts": rows("SELECT json_build_object('id', f.id, 'chart_id', f.chart_id, 'year', f.year, 'location', f.location, 'result', f.result, 'created_at', f.created_at) FROM forecasts f JOIN charts c ON c.id = f.chart_id WHERE c.owner_id = $1").await?,
|
||||
"analyses": rows("SELECT json_build_object('id', a.id, 'kind', a.kind, 'chart_id', a.chart_id, 'synastry_id', a.synastry_id, 'forecast_id', a.forecast_id, 'language', a.language, 'status', a.status, 'content', a.content, 'created_at', a.created_at) FROM analyses a WHERE a.requested_by = $1 OR a.chart_id IN (SELECT id FROM charts WHERE owner_id = $1)").await?,
|
||||
"questions": rows("SELECT json_build_object('id', q.id, 'analysis_id', q.analysis_id, 'question', q.question, 'status', q.status, 'answer', q.answer, 'created_at', q.created_at) FROM questions q WHERE q.asked_by = $1").await?,
|
||||
"credit_ledger": rows("SELECT json_build_object('unit', unit, 'delta', delta, 'reason', reason, 'note', note, 'created_at', created_at) FROM credit_ledger WHERE user_id = $1 ORDER BY created_at").await?,
|
||||
"shares": rows("SELECT json_build_object('slug', slug, 'kind', kind, 'title', title, 'show_birth_data', show_birth_data, 'view_count', view_count, 'created_at', created_at, 'revoked_at', revoked_at) FROM shares WHERE owner_id = $1").await?,
|
||||
});
|
||||
|
||||
@@ -33,14 +33,27 @@ pub async fn list_users(
|
||||
let limit = query.limit.unwrap_or(50).clamp(1, 200);
|
||||
let offset = query.offset.unwrap_or(0).max(0);
|
||||
let pattern = query.q.as_deref().map(|q| format!("%{}%", q.trim().replace(['%', '_'], "")));
|
||||
type Row =
|
||||
(Uuid, String, Option<String>, Vec<String>, bool, OffsetDateTime, Option<OffsetDateTime>, i64, i64, i64, i64);
|
||||
type Row = (
|
||||
Uuid,
|
||||
String,
|
||||
Option<String>,
|
||||
Vec<String>,
|
||||
bool,
|
||||
OffsetDateTime,
|
||||
Option<OffsetDateTime>,
|
||||
i64,
|
||||
i64,
|
||||
i64,
|
||||
i64,
|
||||
i64,
|
||||
);
|
||||
let rows: Vec<Row> = sqlx::query_as(
|
||||
"SELECT u.id, u.email, u.display_name, u.roles, u.email_verified_at IS NOT NULL, u.created_at, u.last_login_at, \
|
||||
(SELECT count(*) FROM charts c WHERE c.owner_id = u.id), \
|
||||
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id AND l.unit = 'natal'), \
|
||||
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id AND l.unit = 'synastry'), \
|
||||
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id AND l.unit = 'forecast') \
|
||||
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id AND l.unit = 'forecast'), \
|
||||
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger l WHERE l.user_id = u.id AND l.unit = 'question') \
|
||||
FROM users u \
|
||||
WHERE $1::text IS NULL OR u.email ILIKE $1 OR u.display_name ILIKE $1 \
|
||||
ORDER BY u.created_at DESC LIMIT $2 OFFSET $3",
|
||||
@@ -52,11 +65,12 @@ pub async fn list_users(
|
||||
.await?;
|
||||
let users: Vec<Value> = rows
|
||||
.into_iter()
|
||||
.map(|(id, email, name, roles, verified, created, last_login, charts, natal, synastry, forecast)| {
|
||||
.map(|(id, email, name, roles, verified, created, last_login, charts, natal, synastry, forecast, question)| {
|
||||
json!({
|
||||
"id": id, "email": email, "display_name": name, "roles": roles, "email_verified": verified,
|
||||
"created_at": rfc3339(created), "last_login_at": rfc3339_opt(last_login),
|
||||
"charts": charts, "analyses_left": {"natal": natal, "synastry": synastry, "forecast": forecast},
|
||||
"charts": charts,
|
||||
"analyses_left": {"natal": natal, "synastry": synastry, "forecast": forecast, "question": question},
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
@@ -370,6 +370,7 @@ pub async fn regenerate(
|
||||
}
|
||||
let kind = Kind::parse(&row.kind).ok_or_else(|| ApiError::Internal(format!("unknown kind {}", row.kind)))?;
|
||||
let hash: Option<String> = match kind {
|
||||
Kind::Question => None,
|
||||
Kind::Natal | Kind::Summary => {
|
||||
sqlx::query_scalar("SELECT chart_hash FROM charts WHERE id = $1")
|
||||
.bind(row.chart_id)
|
||||
|
||||
@@ -15,6 +15,7 @@ mod invitations;
|
||||
mod models;
|
||||
mod payments;
|
||||
mod prompts;
|
||||
mod questions;
|
||||
mod recalculate;
|
||||
mod shares;
|
||||
mod synastries;
|
||||
@@ -90,6 +91,8 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.route("/v1/invites/accept", post(synastries::accept_invite))
|
||||
// analyses
|
||||
.route("/v1/analyses/{id}", get(analyses::get_one))
|
||||
.route("/v1/analyses/{id}/questions", get(questions::list).post(questions::ask))
|
||||
.route("/v1/questions/{id}", get(questions::get_one))
|
||||
// sharing
|
||||
.route("/v1/shares", get(shares::list).post(shares::create))
|
||||
.route("/v1/shares/{id}", delete(shares::revoke))
|
||||
@@ -117,6 +120,7 @@ pub fn router(state: Arc<AppState>) -> Router {
|
||||
.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))
|
||||
.route("/v1/admin/questions/{id}/regenerate", post(questions::regenerate))
|
||||
.layer(cors(&state.config.cors_allowed_origins))
|
||||
.layer(
|
||||
TraceLayer::new_for_http()
|
||||
|
||||
@@ -57,7 +57,7 @@ async fn entry(state: &AppState, kind: Kind) -> Result<Value, sqlx::Error> {
|
||||
|
||||
pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult<Json<Value>> {
|
||||
let mut functions = Vec::new();
|
||||
for kind in Kind::ALL {
|
||||
for kind in Kind::ANALYSES {
|
||||
functions.push(entry(&state, kind).await?);
|
||||
}
|
||||
Ok(Json(json!({ "functions": functions })))
|
||||
|
||||
@@ -55,6 +55,7 @@ pub async fn mock(
|
||||
(None, Some(Unit::Synastry)) => "addon_synastry",
|
||||
(None, Some(Unit::Forecast)) => "addon_forecast",
|
||||
(None, Some(Unit::Person)) => "addon_persons",
|
||||
(None, Some(Unit::Question)) => "addon_questions",
|
||||
_ => return Err(ApiError::BadRequest("give either package or unit".into())),
|
||||
};
|
||||
let package = packages::find(id).ok_or(ApiError::NotFound("package"))?;
|
||||
|
||||
@@ -27,7 +27,7 @@ use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{rfc3339, rfc3339_opt};
|
||||
|
||||
/// The kinds whose prompt the admin page edits.
|
||||
const EDITABLE: [Kind; 4] = [Kind::Summary, Kind::Natal, Kind::Synastry, Kind::Forecast];
|
||||
const EDITABLE: [Kind; 5] = [Kind::Summary, Kind::Natal, Kind::Synastry, Kind::Forecast, Kind::Question];
|
||||
const MAX_CHARS: usize = 50_000;
|
||||
const HISTORY: i64 = 20;
|
||||
/// Test runs of one admin waiting or being written at the same time.
|
||||
@@ -228,6 +228,11 @@ pub async fn start_preview(
|
||||
),
|
||||
(Kind::Synastry, ..) => return Err(ApiError::BadRequest("a synastry analysis needs synastry_id".into())),
|
||||
(Kind::Forecast, ..) => return Err(ApiError::BadRequest("a forecast analysis needs forecast_id".into())),
|
||||
(Kind::Question, ..) => {
|
||||
return Err(ApiError::BadRequest(
|
||||
"the question prompt cannot be tried here; ask a question on one of your analyses".into(),
|
||||
));
|
||||
}
|
||||
_ => return Err(ApiError::BadRequest("this analysis needs chart_id".into())),
|
||||
};
|
||||
let found: Option<(Uuid,)> = sqlx::query_as(query).bind(id).bind(admin.id()).fetch_optional(&state.db).await?;
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
//! Questions about a finished detailed analysis: a natal chart analysis or a
|
||||
//! yearly forecast. Each question uses a `question` unit (admins ask for
|
||||
//! free). The worker answers with the model that wrote the analysis, seeing
|
||||
//! the chart data, the analysis and the earlier questions about it.
|
||||
|
||||
use analysis_prompt::{Kind, QUESTION_MAX_CHARS};
|
||||
use axum::Json;
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum_extra::extract::WithRejection;
|
||||
use db::Role;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use sqlx::PgPool;
|
||||
use time::OffsetDateTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
use super::analyses::{can_see, find_analysis};
|
||||
use super::{Body, IdPath, St};
|
||||
use crate::auth::{AdminUser, AuthUser};
|
||||
use crate::credits;
|
||||
use crate::error::{ApiError, ApiResult};
|
||||
use crate::views::{rfc3339, rfc3339_opt};
|
||||
|
||||
/// The analyses that can be asked about.
|
||||
const ASKABLE: [&str; 2] = ["natal", "forecast"];
|
||||
/// A safety cap per analysis.
|
||||
const MAX_PER_ANALYSIS: i64 = 100;
|
||||
|
||||
/// A question as users see it (the model is left out on purpose).
|
||||
#[derive(Debug, sqlx::FromRow)]
|
||||
pub struct QuestionRow {
|
||||
pub id: Uuid,
|
||||
pub analysis_id: Uuid,
|
||||
pub question: String,
|
||||
pub status: String,
|
||||
pub answer: Option<String>,
|
||||
pub error: Option<String>,
|
||||
pub credits_charged: i32,
|
||||
pub created_at: OffsetDateTime,
|
||||
pub completed_at: Option<OffsetDateTime>,
|
||||
}
|
||||
|
||||
const QUESTION_COLUMNS: &str =
|
||||
"id, analysis_id, question, status, answer, error, credits_charged, created_at, completed_at";
|
||||
|
||||
impl QuestionRow {
|
||||
pub fn view(&self) -> Value {
|
||||
json!({
|
||||
"id": self.id,
|
||||
"analysis_id": self.analysis_id,
|
||||
"question": self.question,
|
||||
"status": self.status,
|
||||
"answer": self.answer,
|
||||
"error": self.error,
|
||||
"credits_charged": self.credits_charged,
|
||||
"created_at": rfc3339(self.created_at),
|
||||
"completed_at": rfc3339_opt(self.completed_at),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn find_question(db: &PgPool, id: Uuid) -> Result<Option<QuestionRow>, sqlx::Error> {
|
||||
sqlx::query_as(&format!("SELECT {QUESTION_COLUMNS} FROM questions WHERE id = $1")).bind(id).fetch_optional(db).await
|
||||
}
|
||||
|
||||
/// The model of the analysis (questions are answered by the same model) and
|
||||
/// the prompt version of the question prompt in force.
|
||||
async fn model_and_version(
|
||||
state: &crate::AppState,
|
||||
analysis_id: Uuid,
|
||||
language: &str,
|
||||
) -> Result<(String, String), sqlx::Error> {
|
||||
let model: String =
|
||||
sqlx::query_scalar("SELECT model FROM analyses WHERE id = $1").bind(analysis_id).fetch_one(&state.db).await?;
|
||||
let base = &state.config.prompt_version;
|
||||
let version = match super::prompts::current_revision(&state.db, Kind::Question.as_str(), language).await? {
|
||||
Some(id) => format!("{base}-r{id}"),
|
||||
None => base.clone(),
|
||||
};
|
||||
Ok((model, version))
|
||||
}
|
||||
|
||||
pub async fn list(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"));
|
||||
}
|
||||
let rows: Vec<QuestionRow> =
|
||||
sqlx::query_as(&format!("SELECT {QUESTION_COLUMNS} FROM questions WHERE analysis_id = $1 ORDER BY created_at"))
|
||||
.bind(id)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
Ok(Json(json!({ "questions": rows.iter().map(QuestionRow::view).collect::<Vec<_>>() })))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct AskQuestion {
|
||||
question: String,
|
||||
}
|
||||
|
||||
pub async fn ask(
|
||||
State(state): St,
|
||||
auth: AuthUser,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
WithRejection(Json(req), _): Body<AskQuestion>,
|
||||
) -> ApiResult<(StatusCode, 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"));
|
||||
}
|
||||
if !ASKABLE.contains(&analysis.kind.as_str()) {
|
||||
return Err(ApiError::BadRequest("questions can be asked about a natal analysis or a forecast".into()));
|
||||
}
|
||||
if analysis.status != "done" {
|
||||
return Err(ApiError::conflict("analysis_not_ready", "Az elemzés még nem készült el."));
|
||||
}
|
||||
let question = req.question.trim().replace("\r\n", "\n");
|
||||
let length = question.chars().count();
|
||||
if !(3..=QUESTION_MAX_CHARS).contains(&length) {
|
||||
return Err(ApiError::BadRequest(format!("the question must be 3 to {QUESTION_MAX_CHARS} characters long")));
|
||||
}
|
||||
let (open, total): (i64, i64) = sqlx::query_as(
|
||||
"SELECT count(*) FILTER (WHERE status IN ('pending', 'running')), count(*) FROM questions WHERE analysis_id = $1",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
if open > 0 {
|
||||
return Err(ApiError::conflict(
|
||||
"question_in_progress",
|
||||
"Az előző kérdésedre még készül a válasz. Várd meg, és utána kérdezz újra.",
|
||||
));
|
||||
}
|
||||
if total >= MAX_PER_ANALYSIS {
|
||||
return Err(ApiError::conflict(
|
||||
"question_limit_reached",
|
||||
"Ehhez az elemzéshez már nem lehet több kérdést feltenni.",
|
||||
));
|
||||
}
|
||||
|
||||
let admin = auth.user.has_role(Role::Admin);
|
||||
let (model, prompt_version) = model_and_version(&state, id, &analysis.language).await?;
|
||||
let question_id = Uuid::now_v7();
|
||||
let mut tx = state.db.begin().await?;
|
||||
let row: QuestionRow = sqlx::query_as(&format!(
|
||||
"INSERT INTO questions (id, analysis_id, asked_by, question, language, model, prompt_version, credits_charged) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING {QUESTION_COLUMNS}"
|
||||
))
|
||||
.bind(question_id)
|
||||
.bind(id)
|
||||
.bind(auth.id())
|
||||
.bind(&question)
|
||||
.bind(&analysis.language)
|
||||
.bind(&model)
|
||||
.bind(&prompt_version)
|
||||
.bind(i32::from(!admin))
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
if !admin {
|
||||
credits::spend_question(&mut tx, auth.id(), question_id).await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok((StatusCode::ACCEPTED, Json(row.view())))
|
||||
}
|
||||
|
||||
pub async fn get_one(State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
|
||||
let row = find_question(&state.db, id).await?.ok_or(ApiError::NotFound("question"))?;
|
||||
let analysis = find_analysis(&state.db, row.analysis_id).await?.ok_or(ApiError::NotFound("question"))?;
|
||||
if !can_see(&state.db, &analysis, auth.id()).await? {
|
||||
return Err(ApiError::NotFound("question"));
|
||||
}
|
||||
Ok(Json(row.view()))
|
||||
}
|
||||
|
||||
/// Admin: answers a question again in place, with the current question prompt
|
||||
/// and the analysis's model. Nobody is charged.
|
||||
pub async fn regenerate(
|
||||
State(state): St,
|
||||
_admin: AdminUser,
|
||||
WithRejection(Path(id), _): IdPath,
|
||||
) -> ApiResult<Json<Value>> {
|
||||
let row = find_question(&state.db, id).await?.ok_or(ApiError::NotFound("question"))?;
|
||||
let language: String =
|
||||
sqlx::query_scalar("SELECT language FROM questions WHERE id = $1").bind(id).fetch_one(&state.db).await?;
|
||||
let (model, prompt_version) = model_and_version(&state, row.analysis_id, &language).await?;
|
||||
let mut tx = state.db.begin().await?;
|
||||
let row: QuestionRow = sqlx::query_as(&format!(
|
||||
"UPDATE questions SET status = 'pending', answer = 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 \
|
||||
WHERE id = $1 AND status IN ('done', 'failed') RETURNING {QUESTION_COLUMNS}"
|
||||
))
|
||||
.bind(id)
|
||||
.bind(&model)
|
||||
.bind(&prompt_version)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.ok_or_else(|| ApiError::conflict("question_in_progress", "Erre a kérdésre éppen készül a válasz."))?;
|
||||
sqlx::query("SELECT pg_notify('analyses', '')").execute(&mut *tx).await?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(row.view()))
|
||||
}
|
||||
Reference in New Issue
Block a user