Three layers for the text users write into a prompt (questions about an analysis, tarot questions): - analysis_prompt::guard cleans it (controls, zero-width characters, spaces, empty lines) and refuses links, tags, code fences, chat role labels, more than 6 lines and phrases that try to change the model's instructions (Hungarian and English, accent-insensitive). The check runs before any unit is spent; refusals are logged without the text. - The prompt puts the question (and earlier ones) between <kerdes> tags, with anything that could close the tag neutralized. - The system prompts say the tagged text is data, not instructions, and not to quote or summarize the rules (the tarot prompts now say it too). The question limit drops from 600 to 300 characters (as for tarot), with a counter always shown under the box. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
213 lines
8.4 KiB
Rust
213 lines
8.4 KiB
Rust
//! Questions about a finished detailed analysis: a natal chart analysis, a
|
|
//! relationship (synastry) analysis or a yearly forecast. On a comparison both
|
|
//! people see the questions and answers. Each question uses a `question` unit (admins ask for
|
|
//! free). The worker answers with the question model of the admin page,
|
|
//! seeing the chart data, the analysis and the earlier questions about it.
|
|
|
|
use analysis_prompt::{Kind, QUESTION_MAX_CHARS, guard};
|
|
use axum::Json;
|
|
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::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; 3] = ["natal", "synastry", "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>,
|
|
pub attempts: i32,
|
|
pub next_attempt_at: OffsetDateTime,
|
|
pub requested_at: OffsetDateTime,
|
|
}
|
|
|
|
const QUESTION_COLUMNS: &str = "id, analysis_id, question, status, answer, error, credits_charged, created_at, \
|
|
completed_at, attempts, next_attempt_at, requested_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),
|
|
"attempts": self.attempts,
|
|
"next_attempt_at": rfc3339(self.next_attempt_at),
|
|
"requested_at": rfc3339(self.requested_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 question model (and its fallback) and the version of the question
|
|
/// prompt in force.
|
|
pub(super) async fn model_and_version(
|
|
state: &crate::AppState,
|
|
language: &str,
|
|
) -> Result<(String, Option<String>, String), sqlx::Error> {
|
|
let (model, fallback) = crate::models::models_for(state, Kind::Question).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, fallback, 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("Kérdést részletes elemzésről vagy előrejelzésről lehet feltenni.".into()));
|
|
}
|
|
if analysis.status != "done" {
|
|
return Err(ApiError::conflict("analysis_not_ready", "Az elemzés még nem készült el."));
|
|
}
|
|
// Cleaned, and refused when it looks like instructions to the model (before any unit is spent).
|
|
let question = guard::check_question(&req.question, 3, QUESTION_MAX_CHARS).map_err(|refusal| {
|
|
tracing::warn!(user = %auth.id(), analysis = %id, reason = refusal.as_str(), "question refused");
|
|
ApiError::BadRequest(refusal.message())
|
|
})?;
|
|
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 (model, fallback, prompt_version) = model_and_version(&state, &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, \
|
|
fallback_model) \
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING {QUESTION_COLUMNS}"
|
|
))
|
|
.bind(question_id)
|
|
.bind(id)
|
|
.bind(auth.id())
|
|
.bind(&question)
|
|
.bind(&analysis.language)
|
|
.bind(&model)
|
|
.bind(&prompt_version)
|
|
.bind(1i32)
|
|
.bind(&fallback)
|
|
.fetch_one(&mut *tx)
|
|
.await?;
|
|
// Admins use questions too (they can add more on the admin page).
|
|
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 model. Nobody is charged.
|
|
pub async fn regenerate(
|
|
State(state): St,
|
|
_admin: AdminUser,
|
|
WithRejection(Path(id), _): IdPath,
|
|
) -> ApiResult<Json<Value>> {
|
|
let language: String = sqlx::query_scalar("SELECT language FROM questions WHERE id = $1")
|
|
.bind(id)
|
|
.fetch_optional(&state.db)
|
|
.await?
|
|
.ok_or(ApiError::NotFound("question"))?;
|
|
let (model, fallback, prompt_version) = model_and_version(&state, &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, fallback_model = $4, on_fallback = false, \
|
|
requested_at = now() \
|
|
WHERE id = $1 AND status IN ('done', 'failed') RETURNING {QUESTION_COLUMNS}"
|
|
))
|
|
.bind(id)
|
|
.bind(&model)
|
|
.bind(&prompt_version)
|
|
.bind(&fallback)
|
|
.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()))
|
|
}
|