forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

rag_study.rs410 lines, 17.1 KiBHistoryRawDownload
1//! Payload contract for the `rag.summarize` and `rag.questions` capabilities.
2//!
3//! Same transport as every other capability: JSON inside a
4//! [`Request::payload`](crate::ai::protocol::Request::payload) and coming back
5//! inside [`Response::Ok`](crate::ai::protocol::Response::Ok)`::payload`. What
6//! differs from [`super::rag_chat`] is the shape of a turn: those are
7//! thread-bound and asynchronous (a `202`, a stored row, a poll), while these
8//! two are **one-shot** — the caller names exactly one corpus and a range
9//! inside it and waits for the artifact itself (a summary, or a set of
10//! practice questions). Nothing is stored on either side of the bridge, so the
11//! reply *is* the answer.
12//!
13//! The scope is one `(sinif, ders)` pair plus the page/span range inside it.
14//! Which pairs the asker may name is the backend's own derivation
15//! ([`crate::service::rag_scope`]) and the caller's body only picks a target
16//! within them, so the pair that travels here is already the authorized one.
17//! The asker rides along for the same reason it does on `rag.chat`: the service
18//! may read that person's own data back through the bridge's api reads
19//! (`on_behalf_of`).
20
21use std::time::Duration;
22
23use serde::{Deserialize, Serialize};
24
25use crate::ai::AiBridge;
26use crate::constant::{
27 AI_RAG_QUESTIONS_CAPABILITY, AI_RAG_QUESTIONS_TIMEOUT_SECS, AI_RAG_SUMMARIZE_CAPABILITY,
28 AI_RAG_SUMMARIZE_TIMEOUT_SECS,
29};
30use crate::tenant::SchoolId;
31
32/// The one corpus a study request is addressed to, and where inside it.
33///
34/// One scope, never a list: a summary or a question set is *about* the
35/// material the caller selected, and a range spanning several corpora has no
36/// single thing to be about.
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38pub struct RagScope {
39 /// The class/grade the corpus belongs to (`"10"`), or `null` for a
40 /// school-wide corpus (club/etüt), which belongs to no section and so
41 /// names no grade.
42 pub sinif: Option<String>,
43 /// The subject/course name the corpus is routed by — the one field a scope
44 /// cannot go without, since a subject-less scope retrieves nothing.
45 pub ders: String,
46 /// The pages of the corpus to work over, when its source is paginated.
47 /// Empty is legal: a scope with neither pages nor spans is answered with an
48 /// `abstained` reply (`empty_scope`), not refused here.
49 #[serde(default)]
50 pub pages: Vec<i64>,
51 /// Opaque retrieval span ids to work over, for a range the caller already
52 /// holds from an earlier retrieval. Normally exactly one of
53 /// `pages`/`span_ids` is set.
54 #[serde(default)]
55 pub span_ids: Vec<String>,
56 /// A human label for the range (the heading the caller selected), used by
57 /// the service in its own prose. May be empty.
58 #[serde(default)]
59 pub scope_label: String,
60}
61
62/// What the backend asks a RAG service to summarize (`rag.summarize`).
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
64pub struct RagSummarizePayload {
65 /// The corpus and range to summarize.
66 pub scope: RagScope,
67 /// Backend-computed caller grant, in the same `(sinif, ders)` pair shape as `rag.chat`.
68 #[serde(default)]
69 pub scope_pairs: Vec<(Option<String>, String)>,
70 /// The id of the person who asked. The service reads that person's own
71 /// data back through the bridge's api reads (`on_behalf_of`). Read live
72 /// from the authenticated session, never taken from a request body.
73 pub asker: String,
74 /// The asker's **school role** — the same lowercase strings the rest of the
75 /// API uses, read live from the session, so a service may refuse a scope a
76 /// student's role may not have.
77 pub asker_role: String,
78}
79/// What the backend asks a RAG service for (`rag.questions`).
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81pub struct RagQuestionsPayload {
82 /// The corpus and range the questions are generated from — also the bound
83 /// on their answers: a question whose answer is not in this range must not
84 /// be generated.
85 pub scope: RagScope,
86 /// Backend-computed caller grant, in the same `(sinif, ders)` pair shape as `rag.chat`.
87 #[serde(default)]
88 pub scope_pairs: Vec<(Option<String>, String)>,
89 /// The id of the person who asked, exactly as [`RagSummarizePayload`]'s.
90 pub asker: String,
91 /// The asker's live school role.
92 pub asker_role: String,
93 /// How many questions to generate. The door holds it to a small bounded
94 /// set (1..=20) before dispatching.
95 pub n: u32,
96 /// The difficulty the caller asked for (`kolay`/`orta`/`zor` and whatever
97 /// else the service knows). The backend only forwards it — the vocabulary
98 /// is the service's.
99 pub difficulty: String,
100 /// A question to base the set on, when the caller wants variations of one
101 /// specific exercise. `null` means "any question within the scope".
102 #[serde(default)]
103 pub seed_question: Option<String>,
104}
105
106/// One passage a summary drew on, inside the reply's `citations`.
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
108pub struct RagSummaryCitation {
109 /// The marker the summary text uses to point at this passage: `[N]` in
110 /// `text` resolves to the citation whose `n` is `N`.
111 pub n: u32,
112 /// The page numbers within the document the passage spans.
113 #[serde(default)]
114 pub pages: Vec<i64>,
115 /// Opaque retrieval span ids within the document.
116 #[serde(default)]
117 pub span_ids: Vec<String>,
118}
119
120/// The service's summary, inside `Response::Ok { payload }`.
121///
122/// Handled failures do *not* come back here — they use the existing
123/// [`Response::Err`](crate::ai::protocol::Response::Err) `{ code, message }`,
124/// so there is exactly one failure shape on the bridge for every capability.
125/// A refusal that is part of the answer (nothing in the named range to
126/// summarize, a guard) rides here with `abstained: true` and a `reason`: the
127/// request completes, and nothing is reported as an error.
128///
129/// Unlike `rag.chat`'s citations, these carry **no corpus `doc_id`** — a
130/// summary is addressed to a range the caller selected, not scoped to one
131/// document — so nothing here resolves to a course-note file.
132#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
133pub struct RagSummarizeReply {
134 /// The summary text. Required: a reply without it is unreadable, not an
135 /// empty summary.
136 pub text: String,
137 /// Whether the service declined to summarize rather than summarizing.
138 #[serde(default)]
139 pub abstained: bool,
140 /// Why it abstained, as a short machine code (`empty_scope`,
141 /// `insufficient_data`, `guard_*`, `model_abstained`, …); empty on an
142 /// ordinary answer.
143 #[serde(default)]
144 pub reason: String,
145 /// The passages the summary drew on, oldest first.
146 #[serde(default)]
147 pub citations: Vec<RagSummaryCitation>,
148 /// The pages the summary actually covered, when the service resolved the
149 /// requested range against the corpus.
150 #[serde(default)]
151 pub scope_pages: Vec<i64>,
152 /// Whether the service summarized the range hierarchically (per section,
153 /// then rolled up) rather than flat.
154 #[serde(default)]
155 pub hierarchical: bool,
156}
157
158/// One generated practice question, inside the reply's `items`.
159///
160/// The keys are the **service's** own (`soru`/`cevap`/`zorluk`) — the wire
161/// mirrors the service's vocabulary exactly as `rag.chat` mirrors its own, and
162/// the HTTP door is where they become this API's English field names.
163#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
164pub struct RagQuestion {
165 /// The question itself.
166 pub soru: String,
167 /// The answer, generated from the named range and never from outside it —
168 /// the range is the bound that keeps a practice question answerable from
169 /// the material the student holds.
170 pub cevap: String,
171 /// The question's difficulty, in the service's own vocabulary.
172 pub zorluk: String,
173}
174
175/// The service's generated question set, inside `Response::Ok { payload }`.
176#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
177pub struct RagQuestionsReply {
178 /// The generated questions, in the order they should be shown. Required: a
179 /// reply without `items` is unreadable; a set that could not be generated
180 /// is `abstained: true` with a `reason` instead.
181 pub items: Vec<RagQuestion>,
182 /// Whether the service declined to generate rather than generating.
183 #[serde(default)]
184 pub abstained: bool,
185 /// Why it abstained, as a short machine code; empty on an ordinary answer.
186 #[serde(default)]
187 pub reason: String,
188 /// The retrieval spans the whole set is bounded to.
189 #[serde(default)]
190 pub span_ids: Vec<String>,
191 /// The pages those spans sit on.
192 #[serde(default)]
193 pub pages: Vec<i64>,
194}
195
196/// Ask a RAG service to summarize one range of one corpus.
197///
198/// `Err` is a short, stable code for the door's refusal table — a transport
199/// failure, the service's own `Response::Err` verdict, or `bad_reply` when the
200/// reply was unreadable. Two codes are special: `role_required` and
201/// `scope_mismatch` mean the **backend** composed a request the service may not
202/// answer (the pair or the role it sent), so they are logged as bugs here and
203/// reach the caller as a `502` — the same posture `rag.chat` takes.
204pub async fn summarize(
205 bridge: &AiBridge,
206 school: &SchoolId,
207 payload: RagSummarizePayload,
208) -> Result<RagSummarizeReply, String> {
209 let asker = payload.asker.clone();
210 let encoded = encode(&payload, AI_RAG_SUMMARIZE_CAPABILITY)?;
211 let raw = bridge
212 .dispatch_with_timeout(
213 school,
214 AI_RAG_SUMMARIZE_CAPABILITY,
215 encoded,
216 Duration::from_secs(AI_RAG_SUMMARIZE_TIMEOUT_SECS),
217 )
218 .await
219 .map_err(failure_code)?;
220 let reply: RagSummarizeReply = decode(raw, AI_RAG_SUMMARIZE_CAPABILITY)?;
221 reject_backend_bug(&reply.reason, &asker, AI_RAG_SUMMARIZE_CAPABILITY)?;
222 Ok(reply)
223}
224
225/// Ask a RAG service to generate practice questions over one range of one
226/// corpus. The refusal vocabulary is [`summarize`]'s, code for code.
227pub async fn questions(
228 bridge: &AiBridge,
229 school: &SchoolId,
230 payload: RagQuestionsPayload,
231) -> Result<RagQuestionsReply, String> {
232 let asker = payload.asker.clone();
233 let encoded = encode(&payload, AI_RAG_QUESTIONS_CAPABILITY)?;
234 let raw = bridge
235 .dispatch_with_timeout(
236 school,
237 AI_RAG_QUESTIONS_CAPABILITY,
238 encoded,
239 Duration::from_secs(AI_RAG_QUESTIONS_TIMEOUT_SECS),
240 )
241 .await
242 .map_err(failure_code)?;
243 let reply: RagQuestionsReply = decode(raw, AI_RAG_QUESTIONS_CAPABILITY)?;
244 reject_backend_bug(&reply.reason, &asker, AI_RAG_QUESTIONS_CAPABILITY)?;
245 Ok(reply)
246}
247
248/// Encode one payload; a payload that cannot be encoded is this side's bug, so
249/// it is logged and reported as `internal` rather than as a service verdict.
250fn encode<P: Serialize>(payload: &P, capability: &str) -> Result<serde_json::Value, String> {
251 serde_json::to_value(payload).map_err(|err| {
252 tracing::error!("could not encode a {capability} request: {err}");
253 "internal".to_string()
254 })
255}
256
257/// Decode one service reply, wrapped in the capability's name. An unreadable
258/// payload is `bad_reply`: the answer is not safe to guess at, and a service
259/// that changed its shape must be seen failing rather than half-read.
260fn decode<R: serde::de::DeserializeOwned>(
261 raw: serde_json::Value,
262 capability: &str,
263) -> Result<R, String> {
264 serde_json::from_value(raw).map_err(|err| {
265 tracing::warn!("AI service answered with an unreadable {capability} payload: {err}");
266 "bad_reply".to_string()
267 })
268}
269
270/// The two verdicts that mean the **backend** built a bad request: the scope or
271/// the role it sent is not something the service may answer. The request still
272/// fails — an artifact is not safe to invent — but this side of the bridge is
273/// the bug, so it is logged as one rather than as an ordinary service refusal.
274fn reject_backend_bug(reason: &str, asker: &str, capability: &str) -> Result<(), String> {
275 if matches!(reason, "role_required" | "scope_mismatch") {
276 tracing::error!(
277 "{capability} refused a request the backend built: {reason} (asker {asker})"
278 );
279 return Err(reason.to_string());
280 }
281 Ok(())
282}
283
284/// A dispatch failure as a short, stable code the frontend can branch on. The
285/// same mapping the chatbot nest applies to its own round trip.
286fn failure_code(err: crate::ai::AiError) -> String {
287 use crate::ai::AiError;
288 match err {
289 AiError::NoWorker(_) | AiError::Setup(_) => "unavailable".to_string(),
290 AiError::Busy(_) => "busy".to_string(),
291 AiError::Timeout(_) => "timed_out".to_string(),
292 AiError::Transport(_) => "transport".to_string(),
293 AiError::Protocol(_) | AiError::IdMismatch { .. } => "protocol".to_string(),
294 // The service's own verdict. Kept verbatim so a service can define
295 // codes the backend has never heard of.
296 AiError::Remote { code, message } => {
297 tracing::warn!("AI RAG service refused the request: {code}: {message}");
298 if code.trim().is_empty() {
299 "service_error".to_string()
300 } else {
301 code
302 }
303 }
304 }
305}
306
307#[cfg(test)]
308mod tests {
309 use super::*;
310 use serde_json::json;
311
312 #[test]
313 fn study_payload_keys_are_the_documented_wire_names() {
314 // Services in other languages match on these literals — a rename here
315 // silently breaks every one of them, so pin the encoding, key names
316 // included (the exact wire key sets are the contract).
317 let summarize = serde_json::to_value(RagSummarizePayload {
318 scope: RagScope {
319 sinif: Some("10".into()),
320 ders: "biyoloji".into(),
321 pages: vec![16, 17],
322 span_ids: vec![],
323 scope_label: "DNA".into(),
324 },
325 scope_pairs: vec![(Some("10".into()), "Biyoloji".into())],
326 asker: "01ASKER".into(),
327 asker_role: "teacher".into(),
328 })
329 .unwrap();
330 assert_eq!(
331 summarize,
332 json!({
333 "scope": {
334 "sinif": "10",
335 "ders": "biyoloji",
336 "pages": [16, 17],
337 "span_ids": [],
338 "scope_label": "DNA",
339 },
340 "scope_pairs": [["10", "Biyoloji"]],
341 "asker": "01ASKER",
342 "asker_role": "teacher",
343 })
344 );
345
346 // A grade-less (school-wide) corpus sends `sinif: null`, exactly as
347 // `rag.chat`'s pairs do, and a span-addressed range sends no pages.
348 let questions = serde_json::to_value(RagQuestionsPayload {
349 scope: RagScope {
350 sinif: None,
351 ders: "Satranç Kulübü".into(),
352 pages: vec![],
353 span_ids: vec!["s-7".into()],
354 scope_label: String::new(),
355 },
356 scope_pairs: vec![(None, "Satranç Kulübü".into())],
357 asker: "01ASKER".into(),
358 asker_role: "student".into(),
359 n: 5,
360 difficulty: "orta".into(),
361 seed_question: None,
362 })
363 .unwrap();
364 assert_eq!(
365 questions,
366 json!({
367 "scope": {
368 "sinif": null,
369 "ders": "Satranç Kulübü",
370 "pages": [],
371 "span_ids": ["s-7"],
372 "scope_label": "",
373 },
374 "scope_pairs": [[null, "Satranç Kulübü"]],
375 "asker": "01ASKER",
376 "asker_role": "student",
377 "n": 5,
378 "difficulty": "orta",
379 "seed_question": null,
380 })
381 );
382
383 // Every optional reply field defaults on a minimal service answer, and
384 // the one required field of each stays required: a reply without text
385 // (or without items) is unreadable, never an empty artifact.
386 let bare: RagSummarizeReply =
387 serde_json::from_value(json!({ "text": "özet" })).unwrap();
388 assert!(!bare.abstained);
389 assert_eq!(bare.reason, "");
390 assert!(bare.citations.is_empty());
391 assert!(bare.scope_pages.is_empty());
392 assert!(!bare.hierarchical);
393 assert!(serde_json::from_value::<RagSummarizeReply>(json!({ "abstained": true })).is_err());
394
395 let bare: RagQuestionsReply = serde_json::from_value(json!({ "items": [] })).unwrap();
396 assert!(!bare.abstained);
397 assert_eq!(bare.reason, "");
398 assert!(bare.span_ids.is_empty());
399 assert!(bare.pages.is_empty());
400 assert!(serde_json::from_value::<RagQuestionsReply>(json!({ "abstained": true })).is_err());
401
402 // The question row keeps the service's own keys.
403 let row: RagQuestion =
404 serde_json::from_value(json!({ "soru": "DNA nedir?", "cevap": "…", "zorluk": "orta" }))
405 .unwrap();
406 assert_eq!(row.soru, "DNA nedir?");
407 assert_eq!(row.cevap, "…");
408 assert_eq!(row.zorluk, "orta");
409 }
410}