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_chat.rs445 lines, 17.9 KiBHistoryRawDownload
1//! Payload contract for the `rag.chat` capability.
2//!
3//! Same transport as every other capability: this is JSON riding inside a
4//! [`Request::payload`](crate::ai::protocol::Request::payload) and coming back
5//! inside [`Response::Ok`](crate::ai::protocol::Response::Ok)`::payload`. One
6//! request, one answer — retrieval-then-answer is unary here even though it is
7//! two steps inside the service.
8//!
9//! The service answers *about* a school's course-note corpus, so the request
10//! carries both who is asking (so the service can read that person's own data
11//! back through the bridge's api reads, as `on_behalf_of`) and the
12//! `(class, course)` scope the corpus is routed by. The reply returns the answer
13//! text plus the citations behind it, so the backend can resolve each cited
14//! passage to the course-note file it came from.
15
16use serde::{Deserialize, Serialize};
17
18use crate::ai::chat::ChatRole;
19use crate::constant::{
20 AI_RAG_CHAT_CAPABILITY, AI_RAG_CHAT_TIMEOUT_SECS, MAX_RAG_CITATIONS, MAX_RAG_CITATION_PAGES,
21};
22
23/// One `(class, course)` pair the question is scoped to.
24///
25/// The corpus is routed by the **pair**: a grade and a subject list sent
26/// separately would cross-product into combinations the asker never named, so
27/// each pair is one scope the service may retrieve from. The class is optional —
28/// a question about a subject across every grade names the course alone — and
29/// the course is required, since a subject-less scope retrieves nothing.
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31pub struct RagScopePair {
32 /// The class/grade the subject is taught in (`"9"`, `"10"`), or omitted to
33 /// scope the subject across grades.
34 #[serde(default)]
35 pub sinif: Option<String>,
36 /// The subject/course name the pair is scoped to (Mathematics, Physics). The
37 /// one field a pair cannot go without.
38 pub ders: String,
39}
40
41/// One previous message in the RAG conversation.
42///
43/// The same `{role, content}` shape the chatbot's history uses — a model's
44/// `messages` array takes it with no remapping — so the two histories are
45/// interchangeable.
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47pub struct RagTurn {
48 pub role: ChatRole,
49 pub content: String,
50}
51
52/// What the backend asks a RAG service to answer.
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct RagChatRequestPayload {
55 /// The user's new question. `history` does *not* contain it.
56 pub message: String,
57 /// The id of the user who asked. The service reads that person's own data
58 /// back through the bridge's api reads (`on_behalf_of`), so a question
59 /// about "my marks" is answered from *their* marks and never from another
60 /// student's. Read live from the authenticated session, never taken from a
61 /// request body.
62 pub asker: String,
63 /// The asker's **school role** — `"parent"`, `"student"`, `"teacher"`,
64 /// `"manager"` or `"admin"`, the same lowercase strings the rest of the
65 /// API uses. Read live from the session on every request, like the chatbot
66 /// request's copy, so a service may answer on it: a student must not be
67 /// handed an answer scoped for a manager.
68 pub asker_role: String,
69 /// The `(class, course)` pairs the question is scoped to — one entry per pair,
70 /// because the RAG routes corpora by the pair. At most
71 /// [`MAX_RAG_SCOPE_PAIRS`](crate::constant::MAX_RAG_SCOPE_PAIRS); a request
72 /// carrying more is refused rather than narrowed.
73 pub scope: Vec<RagScopePair>,
74 /// The last N turns of the conversation, **oldest first** — index 0 the
75 /// furthest back, the final element the turn immediately before `message`.
76 /// Absent or `[]` means a fresh conversation.
77 #[serde(default)]
78 pub history: Vec<RagTurn>,
79}
80
81/// One passage the answer drew on, inside the reply's `citations`.
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
83pub struct RagCitation {
84 /// The marker the answer text uses to point at this passage: `[N]` in
85 /// `text` resolves to the citation whose `n` is `N`.
86 pub n: u32,
87 /// The corpus document id the passage came from. The backend maps it to
88 /// the course-note file that owns that PDF (the `rag.index` reply echoes
89 /// this id back per file), so a citation resolves to something a reader can
90 /// open.
91 pub doc_id: String,
92 /// The page numbers within the document the passage spans, when the source
93 /// is paginated.
94 #[serde(default)]
95 pub pages: Vec<i64>,
96 /// Opaque retrieval span ids within the document, for a client that wants
97 /// to highlight the exact passage rather than the whole page.
98 #[serde(default)]
99 pub span_ids: Vec<String>,
100 /// The subject the passage belongs to, when the corpus records one.
101 #[serde(default)]
102 pub ders: Option<String>,
103}
104
105/// The service's answer, inside `Response::Ok { payload }`.
106///
107/// Handled failures do *not* come back here — they use the existing
108/// [`Response::Err`](crate::ai::protocol::Response::Err) `{ code, message }`,
109/// so there is exactly one failure shape on the bridge for every capability.
110/// A refusal that is part of the answer (the service chose not to answer, or
111/// could not) rides here instead, because it is still an answer: the turn
112/// completes, no error surfaces.
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
114pub struct RagChatReplyPayload {
115 /// The complete answer text, with `[N]` markers resolving to `citations`.
116 pub text: String,
117 /// Whether the service declined to answer rather than answering. A true
118 /// value is a complete, successful turn — not a failure — and `reason`
119 /// says why.
120 #[serde(default)]
121 pub abstained: bool,
122 /// Why the service abstained, as a short machine code (`""` when it did
123 /// not): `guard_*`, `insufficient_data`, `model_abstained`,
124 /// `scope_mismatch`, `role_required`, or a service-specific code. Empty on
125 /// an ordinary answer.
126 #[serde(default)]
127 pub reason: String,
128 /// The passages the answer drew on, oldest first.
129 #[serde(default)]
130 pub citations: Vec<RagCitation>,
131}
132
133/// Ask a RAG service one question and resolve what came back.
134///
135/// The request is built from what the session already proves — `asker` and
136/// `asker_role` are read from the live session by the caller, never taken from
137/// a body, and `scope` from [`crate::service::rag_scope`] — and the reply is
138/// mapped into what a message row can hold: the answer text, the abstention,
139/// and the citations whose corpus `doc_id` resolves to a course-note file the
140/// asker may view.
141///
142/// `Err` is a short, stable code for the turn's `error_code` — a transport
143/// failure, the service's own `Response::Err` verdict, or `bad_reply` when the
144/// reply was unreadable or exceeded a storage cap. Two codes are special:
145/// `role_required` and `scope_mismatch` mean the **backend** built a request
146/// the service may not answer. The turn still fails — an answer is not safe to
147/// invent — but this side of the bridge is the bug, so it is logged as one.
148#[allow(clippy::too_many_arguments)] // the whole turn context, spelled once
149pub async fn answer(
150 db: &crate::database::Database,
151 bridge: &crate::ai::AiBridge,
152 school: &crate::tenant::SchoolId,
153 thread: &crate::domain::rag_thread::RagThreadId,
154 fresh: &[crate::domain::rag_message::RagMessageId; 2],
155 prompt: String,
156 asker: &crate::domain::user::UserId,
157 asker_role: crate::domain::role::Role,
158 scope: Vec<RagScopePair>,
159 history: Vec<RagTurn>,
160) -> Result<(String, crate::domain::rag_message::RagReply), String> {
161 let scope_pairs = scope.len();
162 let payload = serde_json::to_value(RagChatRequestPayload {
163 message: prompt,
164 asker: asker.key(),
165 asker_role: asker_role.as_str().to_string(),
166 scope,
167 history,
168 })
169 .map_err(|err| {
170 tracing::error!("could not encode a rag.chat request: {err}");
171 "internal".to_string()
172 })?;
173 tracing::debug!(
174 "dispatching rag.chat for thread {} (answer {}): {scope_pairs} scope pairs",
175 thread.key(),
176 fresh[1].key()
177 );
178
179 let raw = bridge
180 .dispatch_with_timeout(
181 school,
182 AI_RAG_CHAT_CAPABILITY,
183 payload,
184 std::time::Duration::from_secs(AI_RAG_CHAT_TIMEOUT_SECS),
185 )
186 .await
187 .map_err(failure_code)?;
188 let reply: RagChatReplyPayload = serde_json::from_value(raw).map_err(|err| {
189 tracing::warn!("AI service answered with an unreadable rag.chat payload: {err}");
190 "bad_reply".to_string()
191 })?;
192
193 // The service is a trust boundary: a reply past a storage cap is refused
194 // whole rather than clipped. A half-cited answer reads as a complete one,
195 // and an unbounded answer is bytes a service chose to write into a
196 // school's database.
197 if reply.citations.len() > MAX_RAG_CITATIONS {
198 tracing::error!(
199 "rag.chat returned {} citations, over the {MAX_RAG_CITATIONS} cap",
200 reply.citations.len()
201 );
202 return Err("bad_reply".to_string());
203 }
204 if let Some(over) = reply
205 .citations
206 .iter()
207 .find(|citation| citation.pages.len() > MAX_RAG_CITATION_PAGES)
208 {
209 tracing::error!(
210 "rag.chat citation {} names {} pages, over the {MAX_RAG_CITATION_PAGES} cap",
211 over.n,
212 over.pages.len()
213 );
214 return Err("bad_reply".to_string());
215 }
216
217 // The two verdicts that mean the *backend* built a bad request: the scope
218 // or the asker's role it sent is not something the service may answer. The
219 // turn still fails, but this is a bug on this side of the bridge, so it is
220 // logged as one rather than as an ordinary service refusal.
221 if matches!(reply.reason.as_str(), "role_required" | "scope_mismatch") {
222 tracing::error!(
223 "rag.chat refused a request the backend built: {} (asker {})",
224 reply.reason,
225 asker.key()
226 );
227 return Err(reply.reason);
228 }
229
230 if reply.text.trim().is_empty() && !reply.abstained {
231 // Nothing to show, and the domain would refuse to store it anyway. A
232 // blank bubble is indistinguishable from a bug, so it is reported as
233 // one.
234 tracing::warn!("rag.chat answered with a blank, non-abstained reply");
235 return Err("empty_reply".to_string());
236 }
237
238 let citations = resolve_citations(db, asker, &reply.citations).await;
239 Ok((
240 reply.text,
241 crate::domain::rag_message::RagReply {
242 abstained: reply.abstained,
243 reason: reply.reason,
244 citations,
245 },
246 ))
247}
248
249/// Resolve each citation's corpus `doc_id` to the course-note file that owns
250/// it, keeping only a file whose course the asker may view.
251///
252/// One read per *distinct* `doc_id`: identical PDF bytes resolve to the same
253/// document, so one document may be claimed by several files — across courses,
254/// which is exactly why the visibility check is per candidate and not per
255/// document. The first visible candidate wins, in the store's own order, so two
256/// identical turns resolve a citation the same way. A citation whose document
257/// no visible file claims keeps every other field and stores `file: null` —
258/// the passage stays citable, only not openable.
259async fn resolve_citations(
260 db: &crate::database::Database,
261 asker: &crate::domain::user::UserId,
262 citations: &[RagCitation],
263) -> Vec<crate::domain::rag_message::RagCitedFile> {
264 let user = match crate::service::user::read(db, asker).await {
265 Ok(Some(user)) => Some(user),
266 // The asker vanished mid-turn (only reachable through a deleted
267 // account): nothing can be visible to them, so nothing resolves.
268 Ok(None) => {
269 tracing::warn!("the asker is gone; citations stay unresolved");
270 None
271 }
272 Err(err) => {
273 tracing::warn!("could not read the asker for citation resolution: {err}");
274 None
275 }
276 };
277
278 let mut candidates: std::collections::HashMap<&str, Vec<crate::domain::course_note_file::CourseNoteFile>> =
279 std::collections::HashMap::new();
280 for citation in citations {
281 if !candidates.contains_key(citation.doc_id.as_str()) {
282 let files =
283 match crate::db::course_note_file::find_by_rag_doc_id(db, &citation.doc_id).await {
284 Ok(files) => files,
285 Err(err) => {
286 tracing::warn!("could not resolve doc {}: {err}", citation.doc_id);
287 Vec::new()
288 }
289 };
290 candidates.insert(citation.doc_id.as_str(), files);
291 }
292 }
293
294 let mut resolved = Vec::with_capacity(citations.len());
295 for citation in citations {
296 let file = match &user {
297 Some(user) => {
298 let files = candidates
299 .get(citation.doc_id.as_str())
300 .map(Vec::as_slice)
301 .unwrap_or(&[]);
302 first_visible_file(db, user, files).await
303 }
304 None => None,
305 };
306 resolved.push(crate::domain::rag_message::RagCitedFile {
307 n: citation.n,
308 file,
309 pages: citation.pages.clone(),
310 span_ids: citation.span_ids.clone(),
311 ders: citation.ders.clone(),
312 });
313 }
314 resolved
315}
316
317/// The first candidate file whose owning course `user` may view, in the
318/// store's order; `None` when the document is claimed by no file they can
319/// open. A read that fails mid-walk is treated like a file they cannot see —
320/// the citation still lands, only unresolved.
321async fn first_visible_file(
322 db: &crate::database::Database,
323 user: &crate::domain::user::User,
324 candidates: &[crate::domain::course_note_file::CourseNoteFile],
325) -> Option<String> {
326 for candidate in candidates {
327 let Some(note) = crate::db::course_note::read(db, candidate.get_course_note())
328 .await
329 .ok()
330 .flatten()
331 else {
332 continue;
333 };
334 let Some(course) = crate::db::course::read(db, note.get_course()).await.ok().flatten()
335 else {
336 continue;
337 };
338 match crate::service::course::can_view_course(&course, user, db).await {
339 Ok(true) => return Some(candidate.get_id().key().to_string()),
340 Ok(false) => {}
341 Err(err) => {
342 tracing::warn!("could not check course visibility for a citation: {err}");
343 }
344 }
345 }
346 None
347}
348
349/// A dispatch failure as a short, stable code the frontend can branch on. The
350/// same mapping the chatbot nest applies to its own round trip.
351fn failure_code(err: crate::ai::AiError) -> String {
352 use crate::ai::AiError;
353 match err {
354 AiError::NoWorker(_) | AiError::Setup(_) => "unavailable".to_string(),
355 AiError::Busy(_) => "busy".to_string(),
356 AiError::Timeout(_) => "timed_out".to_string(),
357 AiError::Transport(_) => "transport".to_string(),
358 AiError::Protocol(_) | AiError::IdMismatch { .. } => "protocol".to_string(),
359 // The service's own verdict. Kept verbatim (the domain trims it) so a
360 // service can define codes the backend has never heard of.
361 AiError::Remote { code, message } => {
362 tracing::warn!("AI RAG service refused the request: {code}: {message}");
363 if code.trim().is_empty() {
364 "service_error".to_string()
365 } else {
366 code
367 }
368 }
369 }
370}
371
372#[cfg(test)]
373mod tests {
374 use super::*;
375 use serde_json::json;
376
377 #[test]
378 fn rag_chat_payload_keys_are_the_documented_wire_names() {
379 // Services in other languages match on these literals — a rename here
380 // silently breaks every one of them, so pin the encoding, key names
381 // included (the exact wire key sets are the contract).
382 let request = serde_json::to_value(RagChatRequestPayload {
383 message: "ikinci yasa nedir?".into(),
384 asker: "01ASKER".into(),
385 asker_role: "student".into(),
386 scope: vec![RagScopePair {
387 sinif: Some("11".into()),
388 ders: "Fizik".into(),
389 }],
390 history: vec![RagTurn {
391 role: ChatRole::User,
392 content: "merhaba".into(),
393 }],
394 })
395 .unwrap();
396 assert_eq!(
397 request,
398 json!({
399 "message": "ikinci yasa nedir?",
400 "asker": "01ASKER",
401 "asker_role": "student",
402 "scope": [{ "sinif": "11", "ders": "Fizik" }],
403 "history": [{ "role": "user", "content": "merhaba" }],
404 })
405 );
406
407 let reply = serde_json::to_value(RagChatReplyPayload {
408 text: "F = m·a [1]".into(),
409 abstained: false,
410 reason: String::new(),
411 citations: vec![RagCitation {
412 n: 1,
413 doc_id: "01DOC".into(),
414 pages: vec![3],
415 span_ids: vec!["s-7".into()],
416 ders: Some("Fizik".into()),
417 }],
418 })
419 .unwrap();
420 assert_eq!(
421 reply,
422 json!({
423 "text": "F = m·a [1]",
424 "abstained": false,
425 "reason": "",
426 "citations": [{
427 "n": 1,
428 "doc_id": "01DOC",
429 "pages": [3],
430 "span_ids": ["s-7"],
431 "ders": "Fizik",
432 }],
433 })
434 );
435
436 // The three optional fields default to empty on a minimal service
437 // reply, and a scope pair may omit the class.
438 let bare: RagChatReplyPayload =
439 serde_json::from_value(json!({ "text": "bilmiyorum", "abstained": true })).unwrap();
440 assert_eq!(bare.reason, "");
441 assert!(bare.citations.is_empty());
442 let pair: RagScopePair = serde_json::from_value(json!({ "ders": "Matematik" })).unwrap();
443 assert_eq!(pair.sinif, None);
444 }
445}