| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | use std::time::Duration; |
| 22 | |
| 23 | use crate::web::tenant_state::{ResolvedTenant, SchoolSlug, State, TenantExt}; |
| 24 | use axum::Json; |
| 25 | use axum::extract::{Path, Query}; |
| 26 | use axum::http::StatusCode; |
| 27 | use axum::response::sse::{Event, KeepAlive, Sse}; |
| 28 | use axum::response::{IntoResponse, Response}; |
| 29 | use serde::{Deserialize, Serialize}; |
| 30 | use serde_json::json; |
| 31 | use tokio::sync::mpsc; |
| 32 | use tokio_stream::Stream; |
| 33 | use tokio_stream::wrappers::ReceiverStream; |
| 34 | use utoipa::ToSchema; |
| 35 | use utoipa_axum::router::OpenApiRouter; |
| 36 | use utoipa_axum::routes; |
| 37 | |
| 38 | use crate::ai::chat::{ChatReplyPayload, ChatRequestPayload, ChatRole, ChatTurn}; |
| 39 | use crate::ai::{AiBridge, AiError}; |
| 40 | use crate::constant::{ |
| 41 | AI_CHAT_CAPABILITY, CHAT_STREAM_POLL_MS, MAX_CHATBOT_MESSAGE_LEN, MIN_CHUNK_CHARS, REPLY_CHUNKS, |
| 42 | }; |
| 43 | use crate::database::Database; |
| 44 | use crate::domain::chatbot_message::{ |
| 45 | ChatContent, ChatbotMessage, ChatbotMessageId, MessageRole, MessageStatus, |
| 46 | }; |
| 47 | use crate::domain::chatbot_thread::{ChatbotThread, ChatbotThreadId, ChatbotThreadTitle}; |
| 48 | use crate::domain::role::Role; |
| 49 | use crate::domain::settings::Settings; |
| 50 | use crate::domain::user::UserId; |
| 51 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 52 | use crate::service; |
| 53 | use crate::state::{AppState, scoped_key}; |
| 54 | |
| 55 | use super::{CurrentUser, Page, PageParams}; |
| 56 | |
| 57 | pub fn routes() -> OpenApiRouter<AppState> { |
| 58 | OpenApiRouter::new() |
| 59 | .routes(routes!(create_thread, list_threads)) |
| 60 | .routes(routes!(rename_thread, delete_thread)) |
| 61 | .routes(routes!(list_messages, send_message)) |
| 62 | .routes(routes!(read_message)) |
| 63 | .routes(routes!(stream_message)) |
| 64 | } |
| 65 | |
| 66 | |
| 67 | |
| 68 | #[derive(Deserialize, ToSchema)] |
| 69 | struct CreateChatbotThread { |
| 70 | |
| 71 | |
| 72 | #[schema(max_length = 200, example = "Fizik ödevi")] |
| 73 | title: Option<String>, |
| 74 | } |
| 75 | |
| 76 | |
| 77 | |
| 78 | #[derive(Serialize, ToSchema)] |
| 79 | struct ChatbotThreadResponse { |
| 80 | #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] |
| 81 | id: String, |
| 82 | #[schema(example = "Fizik ödevi")] |
| 83 | title: Option<String>, |
| 84 | |
| 85 | created_at: i64, |
| 86 | |
| 87 | updated_at: i64, |
| 88 | } |
| 89 | |
| 90 | impl ChatbotThreadResponse { |
| 91 | fn new(thread: &ChatbotThread) -> Self { |
| 92 | Self { |
| 93 | id: thread.get_id().key().to_string(), |
| 94 | title: thread.get_title().map(|title| title.as_str().to_string()), |
| 95 | created_at: thread.get_created_at().as_millis(), |
| 96 | updated_at: thread.get_updated_at().as_millis(), |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 104 | |
| 105 | |
| 106 | #[utoipa::path( |
| 107 | post, |
| 108 | path = "/threads", |
| 109 | tag = "chatbot", |
| 110 | security(("session_cookie" = [])), |
| 111 | request_body = CreateChatbotThread, |
| 112 | responses( |
| 113 | (status = 201, description = "The new thread", body = ChatbotThreadResponse), |
| 114 | (status = 400, description = "Invalid title", body = ErrorResponse), |
| 115 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 116 | (status = 409, description = "At the school's thread cap", body = ErrorResponse), |
| 117 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 118 | ), |
| 119 | )] |
| 120 | async fn create_thread( |
| 121 | State(st): State<AppState>, |
| 122 | CurrentUser(user): CurrentUser, |
| 123 | Json(req): Json<CreateChatbotThread>, |
| 124 | ) -> Result<(StatusCode, Json<ChatbotThreadResponse>), AppError> { |
| 125 | |
| 126 | let title = match req.title.as_deref().map(str::trim).unwrap_or_default() { |
| 127 | "" => None, |
| 128 | value => Some(ChatbotThreadTitle::try_new(value)?), |
| 129 | }; |
| 130 | |
| 131 | |
| 132 | |
| 133 | |
| 134 | let thread = service::chatbot_thread::create_capped(&st.db, user.get_id(), title).await?; |
| 135 | Ok(( |
| 136 | StatusCode::CREATED, |
| 137 | Json(ChatbotThreadResponse::new(&thread)), |
| 138 | )) |
| 139 | } |
| 140 | |
| 141 | |
| 142 | |
| 143 | #[utoipa::path( |
| 144 | get, |
| 145 | path = "/threads", |
| 146 | tag = "chatbot", |
| 147 | security(("session_cookie" = [])), |
| 148 | params(PageParams), |
| 149 | responses( |
| 150 | (status = 200, description = "A page of the caller's threads", body = Page<ChatbotThreadResponse>), |
| 151 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 152 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 153 | ), |
| 154 | )] |
| 155 | async fn list_threads( |
| 156 | State(st): State<AppState>, |
| 157 | CurrentUser(user): CurrentUser, |
| 158 | Query(page): Query<PageParams>, |
| 159 | ) -> Result<Json<Page<ChatbotThreadResponse>>, AppError> { |
| 160 | let (limit, offset) = page.resolve()?; |
| 161 | let (threads, total) = |
| 162 | service::chatbot_thread::list_for_user(&st.db, user.get_id(), limit, offset).await?; |
| 163 | let items = threads.iter().map(ChatbotThreadResponse::new).collect(); |
| 164 | Ok(Json(Page::new(items, total, limit, offset))) |
| 165 | } |
| 166 | |
| 167 | #[derive(Deserialize, ToSchema)] |
| 168 | struct RenameChatbotThread { |
| 169 | |
| 170 | |
| 171 | #[schema(max_length = 200, example = "Fizik ödevi")] |
| 172 | title: Option<String>, |
| 173 | } |
| 174 | |
| 175 | |
| 176 | |
| 177 | |
| 178 | |
| 179 | |
| 180 | |
| 181 | |
| 182 | #[utoipa::path( |
| 183 | patch, |
| 184 | path = "/threads/{id}", |
| 185 | tag = "chatbot", |
| 186 | security(("session_cookie" = [])), |
| 187 | params(("id" = String, Path, description = "ChatbotThread id")), |
| 188 | request_body = RenameChatbotThread, |
| 189 | responses( |
| 190 | (status = 200, description = "The renamed thread", body = ChatbotThreadResponse), |
| 191 | (status = 400, description = "Invalid title", body = ErrorResponse), |
| 192 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 193 | (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse), |
| 194 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 195 | ), |
| 196 | )] |
| 197 | async fn rename_thread( |
| 198 | State(st): State<AppState>, |
| 199 | CurrentUser(user): CurrentUser, |
| 200 | Path(id): Path<String>, |
| 201 | Json(req): Json<RenameChatbotThread>, |
| 202 | ) -> Result<Json<ChatbotThreadResponse>, AppError> { |
| 203 | let title = match req.title.as_deref().map(str::trim).unwrap_or_default() { |
| 204 | "" => None, |
| 205 | value => Some(ChatbotThreadTitle::try_new(value)?), |
| 206 | }; |
| 207 | let thread = own_thread(&id, user.get_id(), &st.db).await?; |
| 208 | let renamed = service::chatbot_thread::rename(&st.db, &thread, title).await?; |
| 209 | Ok(Json(ChatbotThreadResponse::new(&renamed))) |
| 210 | } |
| 211 | |
| 212 | |
| 213 | |
| 214 | #[utoipa::path( |
| 215 | delete, |
| 216 | path = "/threads/{id}", |
| 217 | tag = "chatbot", |
| 218 | security(("session_cookie" = [])), |
| 219 | params(("id" = String, Path, description = "ChatbotThread id")), |
| 220 | responses( |
| 221 | (status = 204, description = "Deleted, with its messages"), |
| 222 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 223 | (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse), |
| 224 | ), |
| 225 | )] |
| 226 | async fn delete_thread( |
| 227 | State(st): State<AppState>, |
| 228 | CurrentUser(user): CurrentUser, |
| 229 | Path(id): Path<String>, |
| 230 | ) -> Result<StatusCode, AppError> { |
| 231 | let thread = own_thread(&id, user.get_id(), &st.db).await?; |
| 232 | service::chatbot_thread::delete(&st.db, thread).await?; |
| 233 | Ok(StatusCode::NO_CONTENT) |
| 234 | } |
| 235 | |
| 236 | |
| 237 | |
| 238 | async fn own_thread(id: &str, user: &UserId, db: &Database) -> Result<ChatbotThread, AppError> { |
| 239 | service::chatbot_thread::read_for(db, &ChatbotThreadId::from_key(id), user) |
| 240 | .await? |
| 241 | .ok_or(AppError::NotFound) |
| 242 | } |
| 243 | |
| 244 | |
| 245 | |
| 246 | #[derive(Deserialize, ToSchema)] |
| 247 | struct SendChatbotMessage { |
| 248 | |
| 249 | |
| 250 | |
| 251 | #[schema( |
| 252 | example = "Newton'un ikinci yasasını açıklar mısın?", |
| 253 | max_length = 8_000 |
| 254 | )] |
| 255 | content: String, |
| 256 | } |
| 257 | |
| 258 | |
| 259 | |
| 260 | |
| 261 | #[derive(Serialize, ToSchema)] |
| 262 | struct AcceptedResponse { |
| 263 | |
| 264 | #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] |
| 265 | message_id: String, |
| 266 | |
| 267 | #[schema(example = "pending")] |
| 268 | status: String, |
| 269 | } |
| 270 | |
| 271 | |
| 272 | |
| 273 | #[derive(Serialize, ToSchema)] |
| 274 | struct ChatbotMessageResponse { |
| 275 | #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] |
| 276 | id: String, |
| 277 | #[schema(example = "01J8XZ0K3Q8G7X2M4N5P6R7S8T")] |
| 278 | thread_id: String, |
| 279 | |
| 280 | #[schema(example = "assistant")] |
| 281 | role: String, |
| 282 | |
| 283 | #[schema(example = "complete")] |
| 284 | status: String, |
| 285 | content: String, |
| 286 | |
| 287 | |
| 288 | |
| 289 | |
| 290 | |
| 291 | #[schema(example = false)] |
| 292 | truncated: bool, |
| 293 | |
| 294 | |
| 295 | |
| 296 | |
| 297 | #[schema(example = "timed_out")] |
| 298 | error_code: Option<String>, |
| 299 | |
| 300 | created_at: i64, |
| 301 | |
| 302 | completed_at: Option<i64>, |
| 303 | } |
| 304 | |
| 305 | impl ChatbotMessageResponse { |
| 306 | fn new(message: &ChatbotMessage) -> Self { |
| 307 | Self { |
| 308 | id: message.get_id().key().to_string(), |
| 309 | thread_id: message.get_thread_id().key().to_string(), |
| 310 | role: message.get_role().as_str().to_string(), |
| 311 | status: message.get_status().as_str().to_string(), |
| 312 | content: message.get_content().as_str().to_string(), |
| 313 | truncated: message.is_truncated(), |
| 314 | error_code: message.get_error_code().map(str::to_string), |
| 315 | created_at: message.get_created_at().as_millis(), |
| 316 | completed_at: message.get_completed_at().map(|at| at.as_millis()), |
| 317 | } |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | |
| 322 | #[utoipa::path( |
| 323 | get, |
| 324 | path = "/threads/{id}/messages", |
| 325 | tag = "chatbot", |
| 326 | security(("session_cookie" = [])), |
| 327 | params(("id" = String, Path, description = "ChatbotThread id"), PageParams), |
| 328 | responses( |
| 329 | (status = 200, description = "A page of the thread's turns", body = Page<ChatbotMessageResponse>), |
| 330 | (status = 400, description = "Invalid limit or offset", body = ErrorResponse), |
| 331 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 332 | (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse), |
| 333 | ), |
| 334 | )] |
| 335 | async fn list_messages( |
| 336 | State(st): State<AppState>, |
| 337 | CurrentUser(user): CurrentUser, |
| 338 | Path(id): Path<String>, |
| 339 | Query(page): Query<PageParams>, |
| 340 | ) -> Result<Json<Page<ChatbotMessageResponse>>, AppError> { |
| 341 | let (limit, offset) = page.resolve()?; |
| 342 | let thread = own_thread(&id, user.get_id(), &st.db).await?; |
| 343 | let (messages, total) = |
| 344 | service::chatbot_message::list_for_thread(&st.db, thread.get_id(), limit, offset).await?; |
| 345 | let items = messages.iter().map(ChatbotMessageResponse::new).collect(); |
| 346 | Ok(Json(Page::new(items, total, limit, offset))) |
| 347 | } |
| 348 | |
| 349 | |
| 350 | |
| 351 | |
| 352 | |
| 353 | |
| 354 | |
| 355 | |
| 356 | |
| 357 | |
| 358 | |
| 359 | |
| 360 | |
| 361 | |
| 362 | #[utoipa::path( |
| 363 | post, |
| 364 | path = "/threads/{id}/messages", |
| 365 | tag = "chatbot", |
| 366 | security(("session_cookie" = [])), |
| 367 | params(("id" = String, Path, description = "ChatbotThread id")), |
| 368 | request_body = SendChatbotMessage, |
| 369 | responses( |
| 370 | (status = 202, description = "Accepted; the answer is on its way", body = AcceptedResponse), |
| 371 | (status = 400, description = "Empty message, or longer than the school's `max_chatbot_message_len`", body = ErrorResponse), |
| 372 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 373 | (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse), |
| 374 | (status = 429, description = "Over the per-user message rate limit; see `Retry-After`", body = ErrorResponse), |
| 375 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 376 | (status = 503, description = "No AI service is available — nothing was written, retry later", body = ErrorResponse), |
| 377 | ), |
| 378 | )] |
| 379 | async fn send_message( |
| 380 | State(st): State<AppState>, |
| 381 | SchoolSlug(slug): SchoolSlug, |
| 382 | tenant: ResolvedTenant, |
| 383 | CurrentUser(user): CurrentUser, |
| 384 | Path(id): Path<String>, |
| 385 | Json(req): Json<SendChatbotMessage>, |
| 386 | ) -> Result<Response, AppError> { |
| 387 | |
| 388 | st.chatbot_limit |
| 389 | .enforce_user(&scoped_key(&slug, user.get_id().key().as_str()))?; |
| 390 | |
| 391 | let thread = own_thread(&id, user.get_id(), &st.db).await?; |
| 392 | let settings = service::settings::load(&st.db).await?; |
| 393 | let reply_cap = content_cap(&settings); |
| 394 | let length = req.content.chars().count(); |
| 395 | if length > reply_cap { |
| 396 | return Err(AppError::Validation(ValidationError::TooLong { |
| 397 | field: "content", |
| 398 | max: reply_cap, |
| 399 | got: length, |
| 400 | })); |
| 401 | } |
| 402 | let content = ChatContent::try_new(&req.content)?; |
| 403 | |
| 404 | |
| 405 | |
| 406 | |
| 407 | let Some(bridge) = st.ai.clone() else { |
| 408 | return Ok(unavailable( |
| 409 | "the AI service is not enabled on this deployment", |
| 410 | )); |
| 411 | }; |
| 412 | if !bridge.has_capability(AI_CHAT_CAPABILITY) { |
| 413 | return Ok(unavailable("no AI service is connected right now")); |
| 414 | } |
| 415 | |
| 416 | |
| 417 | |
| 418 | |
| 419 | |
| 420 | |
| 421 | |
| 422 | |
| 423 | |
| 424 | let prompt = |
| 425 | service::chatbot_message::append_user(&st.db, thread.get_id(), user.get_id(), content) |
| 426 | .await?; |
| 427 | let answer = |
| 428 | service::chatbot_message::append_pending_assistant(&st.db, thread.get_id(), user.get_id()) |
| 429 | .await?; |
| 430 | |
| 431 | let message_id = answer.get_id().key().to_string(); |
| 432 | |
| 433 | |
| 434 | |
| 435 | |
| 436 | |
| 437 | |
| 438 | |
| 439 | |
| 440 | |
| 441 | |
| 442 | |
| 443 | |
| 444 | tokio::spawn(answer_turn( |
| 445 | |
| 446 | |
| 447 | |
| 448 | TenantExt { |
| 449 | slug, |
| 450 | db: st.db.clone(), |
| 451 | modules: tenant.modules, |
| 452 | }, |
| 453 | bridge, |
| 454 | prompt.get_id().clone(), |
| 455 | answer, |
| 456 | user.get_role(), |
| 457 | settings.get_chatbot_history_turns().max(0) as usize, |
| 458 | reply_cap, |
| 459 | )); |
| 460 | |
| 461 | Ok(( |
| 462 | StatusCode::ACCEPTED, |
| 463 | Json(AcceptedResponse { |
| 464 | message_id, |
| 465 | status: MessageStatus::Pending.as_str().to_string(), |
| 466 | }), |
| 467 | ) |
| 468 | .into_response()) |
| 469 | } |
| 470 | |
| 471 | |
| 472 | |
| 473 | fn content_cap(settings: &Settings) -> usize { |
| 474 | (settings.get_max_chatbot_message_len().max(0) as usize).min(MAX_CHATBOT_MESSAGE_LEN) |
| 475 | } |
| 476 | |
| 477 | |
| 478 | |
| 479 | |
| 480 | |
| 481 | fn unavailable(message: &str) -> Response { |
| 482 | ( |
| 483 | StatusCode::SERVICE_UNAVAILABLE, |
| 484 | Json(json!({ "error": message })), |
| 485 | ) |
| 486 | .into_response() |
| 487 | } |
| 488 | |
| 489 | |
| 490 | |
| 491 | |
| 492 | async fn answer_turn( |
| 493 | tenant: TenantExt, |
| 494 | bridge: AiBridge, |
| 495 | prompt_id: ChatbotMessageId, |
| 496 | answer: ChatbotMessage, |
| 497 | asker_role: Role, |
| 498 | history_turns: usize, |
| 499 | reply_cap: usize, |
| 500 | ) { |
| 501 | let db = tenant.db.clone(); |
| 502 | let answer_id = answer.get_id().clone(); |
| 503 | let thread = answer.get_thread_id().clone(); |
| 504 | |
| 505 | |
| 506 | |
| 507 | let prompt = match service::chatbot_message::prompt_of(&db, &prompt_id).await { |
| 508 | Ok(Some(prompt)) => prompt, |
| 509 | Ok(None) => { |
| 510 | |
| 511 | |
| 512 | tracing::warn!("chat answer {} has no prompt to send", answer_id.key()); |
| 513 | let _ = service::chatbot_message::fail(&db, &answer_id, "internal").await; |
| 514 | return; |
| 515 | } |
| 516 | Err(err) => { |
| 517 | |
| 518 | |
| 519 | |
| 520 | tracing::warn!("could not read the prompt for {}: {err}", answer_id.key()); |
| 521 | let _ = service::chatbot_message::fail(&db, &answer_id, "internal").await; |
| 522 | return; |
| 523 | } |
| 524 | }; |
| 525 | let fresh = [prompt.get_id().clone(), answer_id.clone()]; |
| 526 | let settled = match fetch_reply( |
| 527 | &bridge, |
| 528 | &tenant, |
| 529 | &thread, |
| 530 | &fresh, |
| 531 | prompt.get_content().as_str().to_string(), |
| 532 | asker_role, |
| 533 | (history_turns, reply_cap), |
| 534 | ) |
| 535 | .await |
| 536 | { |
| 537 | Ok((text, truncated)) => { |
| 538 | service::chatbot_message::complete(&db, &answer_id, text, truncated).await |
| 539 | } |
| 540 | Err(code) => { |
| 541 | tracing::warn!("chat answer {} failed: {code}", answer_id.key()); |
| 542 | service::chatbot_message::fail(&db, &answer_id, &code).await |
| 543 | } |
| 544 | }; |
| 545 | match settled { |
| 546 | Ok(_) => {} |
| 547 | |
| 548 | |
| 549 | |
| 550 | Err(AppError::NotFound) => { |
| 551 | tracing::info!("chat answer {} was already settled", answer_id.key()); |
| 552 | } |
| 553 | Err(err) => tracing::error!("could not settle chat answer {}: {err}", answer_id.key()), |
| 554 | } |
| 555 | } |
| 556 | |
| 557 | |
| 558 | async fn fetch_reply( |
| 559 | bridge: &AiBridge, |
| 560 | tenant: &TenantExt, |
| 561 | thread: &ChatbotThreadId, |
| 562 | fresh: &[ChatbotMessageId; 2], |
| 563 | prompt: String, |
| 564 | asker_role: Role, |
| 565 | caps: (usize, usize), |
| 566 | ) -> Result<(ChatContent, bool), String> { |
| 567 | let (history_turns, reply_cap) = caps; |
| 568 | let db = &tenant.db; |
| 569 | let history = match history_for(db, thread, fresh, history_turns).await { |
| 570 | Ok(history) => history, |
| 571 | Err(err) => { |
| 572 | tracing::warn!("could not load chat history: {err}"); |
| 573 | return Err("internal".to_string()); |
| 574 | } |
| 575 | }; |
| 576 | let payload = serde_json::to_value(ChatRequestPayload { |
| 577 | message: prompt, |
| 578 | asker_role: asker_role.as_str().to_string(), |
| 579 | history, |
| 580 | }) |
| 581 | .map_err(|err| { |
| 582 | tracing::error!("could not encode a chat request: {err}"); |
| 583 | "internal".to_string() |
| 584 | })?; |
| 585 | |
| 586 | let raw = bridge |
| 587 | .dispatch(&tenant.slug, AI_CHAT_CAPABILITY, payload) |
| 588 | .await |
| 589 | .map_err(failure_code)?; |
| 590 | let reply: ChatReplyPayload = serde_json::from_value(raw).map_err(|err| { |
| 591 | tracing::warn!("AI service answered with an unreadable chat payload: {err}"); |
| 592 | "bad_reply".to_string() |
| 593 | })?; |
| 594 | |
| 595 | |
| 596 | |
| 597 | |
| 598 | |
| 599 | |
| 600 | let text: String = reply.text.chars().take(reply_cap).collect(); |
| 601 | if text.trim().is_empty() { |
| 602 | |
| 603 | |
| 604 | return Err("empty_reply".to_string()); |
| 605 | } |
| 606 | let truncated = text.chars().count() < reply.text.chars().count(); |
| 607 | if truncated { |
| 608 | tracing::warn!("clipped an AI chat reply to the school's {reply_cap}-character limit"); |
| 609 | } |
| 610 | let content = ChatContent::try_new(&text).map_err(|err| { |
| 611 | tracing::error!("a clipped AI reply was still not storable: {err}"); |
| 612 | "bad_reply".to_string() |
| 613 | })?; |
| 614 | Ok((content, truncated)) |
| 615 | } |
| 616 | |
| 617 | |
| 618 | |
| 619 | |
| 620 | async fn history_for( |
| 621 | db: &Database, |
| 622 | thread: &ChatbotThreadId, |
| 623 | fresh: &[ChatbotMessageId; 2], |
| 624 | turns: usize, |
| 625 | ) -> Result<Vec<ChatTurn>, AppError> { |
| 626 | |
| 627 | |
| 628 | |
| 629 | |
| 630 | |
| 631 | let tail = |
| 632 | service::chatbot_message::list_settled_tail(db, thread, turns.saturating_add(2)).await?; |
| 633 | let mut history: Vec<ChatTurn> = tail |
| 634 | .iter() |
| 635 | .filter(|message| !fresh.contains(message.get_id())) |
| 636 | .map(|message| ChatTurn { |
| 637 | role: match message.get_role() { |
| 638 | MessageRole::User => ChatRole::User, |
| 639 | MessageRole::Assistant => ChatRole::Assistant, |
| 640 | }, |
| 641 | content: message.get_content().as_str().to_string(), |
| 642 | }) |
| 643 | .collect(); |
| 644 | if history.len() > turns { |
| 645 | history.drain(..history.len() - turns); |
| 646 | } |
| 647 | Ok(history) |
| 648 | } |
| 649 | |
| 650 | |
| 651 | fn failure_code(err: AiError) -> String { |
| 652 | match err { |
| 653 | AiError::NoWorker(_) | AiError::Setup(_) => "unavailable".to_string(), |
| 654 | AiError::Busy(_) => "busy".to_string(), |
| 655 | AiError::Timeout(_) => "timed_out".to_string(), |
| 656 | AiError::Transport(_) => "transport".to_string(), |
| 657 | AiError::Protocol(_) | AiError::IdMismatch { .. } => "protocol".to_string(), |
| 658 | |
| 659 | |
| 660 | AiError::Remote { code, message } => { |
| 661 | tracing::warn!("AI chat service refused the request: {code}: {message}"); |
| 662 | if code.trim().is_empty() { |
| 663 | "service_error".to_string() |
| 664 | } else { |
| 665 | code |
| 666 | } |
| 667 | } |
| 668 | } |
| 669 | } |
| 670 | |
| 671 | |
| 672 | |
| 673 | |
| 674 | #[utoipa::path( |
| 675 | get, |
| 676 | path = "/threads/{id}/messages/{mid}", |
| 677 | tag = "chatbot", |
| 678 | security(("session_cookie" = [])), |
| 679 | params( |
| 680 | ("id" = String, Path, description = "ChatbotThread id"), |
| 681 | ("mid" = String, Path, description = "Message id"), |
| 682 | ), |
| 683 | responses( |
| 684 | (status = 200, description = "The turn, in whatever state it is", body = ChatbotMessageResponse), |
| 685 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 686 | (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse), |
| 687 | ), |
| 688 | )] |
| 689 | async fn read_message( |
| 690 | State(st): State<AppState>, |
| 691 | CurrentUser(user): CurrentUser, |
| 692 | Path((id, mid)): Path<(String, String)>, |
| 693 | ) -> Result<Json<ChatbotMessageResponse>, AppError> { |
| 694 | let message = own_message(&id, &mid, user.get_id(), &st.db).await?; |
| 695 | Ok(Json(ChatbotMessageResponse::new(&message))) |
| 696 | } |
| 697 | |
| 698 | |
| 699 | |
| 700 | |
| 701 | |
| 702 | |
| 703 | |
| 704 | |
| 705 | |
| 706 | |
| 707 | |
| 708 | |
| 709 | |
| 710 | async fn own_message( |
| 711 | thread: &str, |
| 712 | message: &str, |
| 713 | user: &UserId, |
| 714 | db: &Database, |
| 715 | ) -> Result<ChatbotMessage, AppError> { |
| 716 | own_thread(thread, user, db).await?; |
| 717 | service::chatbot_message::read_for(db, &ChatbotMessageId::from_key(message), user) |
| 718 | .await? |
| 719 | .filter(|message| message.get_thread_id().key() == thread) |
| 720 | .ok_or(AppError::NotFound) |
| 721 | } |
| 722 | |
| 723 | |
| 724 | |
| 725 | |
| 726 | |
| 727 | |
| 728 | |
| 729 | |
| 730 | |
| 731 | #[utoipa::path( |
| 732 | get, |
| 733 | path = "/threads/{id}/messages/{mid}/stream", |
| 734 | tag = "chatbot", |
| 735 | security(("session_cookie" = [])), |
| 736 | params( |
| 737 | ("id" = String, Path, description = "ChatbotThread id"), |
| 738 | ("mid" = String, Path, description = "Message id"), |
| 739 | ), |
| 740 | responses( |
| 741 | (status = 200, description = "SSE: `delta` (`{text}`) chunks, then `done` (`{message}`) or `error` (`{code, message}`)", content_type = "text/event-stream"), |
| 742 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 743 | (status = 404, description = "Not found (or not the caller's)", body = ErrorResponse), |
| 744 | ), |
| 745 | )] |
| 746 | async fn stream_message( |
| 747 | State(st): State<AppState>, |
| 748 | CurrentUser(user): CurrentUser, |
| 749 | Path((id, mid)): Path<(String, String)>, |
| 750 | ) -> Result<Sse<impl Stream<Item = Result<Event, axum::Error>>>, AppError> { |
| 751 | |
| 752 | |
| 753 | own_message(&id, &mid, user.get_id(), &st.db).await?; |
| 754 | |
| 755 | let (tx, rx) = mpsc::channel(REPLY_CHUNKS + 2); |
| 756 | let (message_id, user_id, db) = ( |
| 757 | ChatbotMessageId::from_key(&mid), |
| 758 | user.get_id().clone(), |
| 759 | st.db.clone(), |
| 760 | ); |
| 761 | tokio::spawn(async move { |
| 762 | let mut ticker = tokio::time::interval(Duration::from_millis(CHAT_STREAM_POLL_MS)); |
| 763 | loop { |
| 764 | |
| 765 | |
| 766 | |
| 767 | |
| 768 | |
| 769 | |
| 770 | |
| 771 | |
| 772 | |
| 773 | tokio::select! { |
| 774 | _ = ticker.tick() => {} |
| 775 | _ = tx.closed() => return, |
| 776 | } |
| 777 | let message = match service::chatbot_message::read_for(&db, &message_id, &user_id).await |
| 778 | { |
| 779 | Ok(Some(message)) => message, |
| 780 | |
| 781 | Ok(None) => { |
| 782 | send_error(&tx, "not_found", "this message no longer exists").await; |
| 783 | return; |
| 784 | } |
| 785 | Err(err) => { |
| 786 | tracing::warn!("chat stream read failed: {err}"); |
| 787 | send_error(&tx, "internal", "could not read the message").await; |
| 788 | return; |
| 789 | } |
| 790 | }; |
| 791 | |
| 792 | match message.get_status() { |
| 793 | |
| 794 | |
| 795 | |
| 796 | MessageStatus::Pending => continue, |
| 797 | MessageStatus::Complete => { |
| 798 | for chunk in slice_reply(message.get_content().as_str()) { |
| 799 | if send(&tx, "delta", json!({ "text": chunk })).await.is_err() { |
| 800 | return; |
| 801 | } |
| 802 | } |
| 803 | let done = json!({ "message": ChatbotMessageResponse::new(&message) }); |
| 804 | let _ = send(&tx, "done", done).await; |
| 805 | return; |
| 806 | } |
| 807 | MessageStatus::Failed => { |
| 808 | let code = message.get_error_code().unwrap_or("failed"); |
| 809 | send_error(&tx, code, "the assistant could not answer this message").await; |
| 810 | return; |
| 811 | } |
| 812 | } |
| 813 | } |
| 814 | }); |
| 815 | |
| 816 | Ok(Sse::new(ReceiverStream::new(rx)).keep_alive(KeepAlive::default())) |
| 817 | } |
| 818 | |
| 819 | type EventSender = mpsc::Sender<Result<Event, axum::Error>>; |
| 820 | |
| 821 | |
| 822 | async fn send(tx: &EventSender, name: &str, data: serde_json::Value) -> Result<(), ()> { |
| 823 | let event = Event::default() |
| 824 | .event(name) |
| 825 | .json_data(&data) |
| 826 | .unwrap_or_else(|err| { |
| 827 | tracing::error!("could not encode a chat SSE event: {err}"); |
| 828 | Event::default() |
| 829 | .event("error") |
| 830 | .data("{\"code\":\"internal\"}") |
| 831 | }); |
| 832 | tx.send(Ok(event)).await.map_err(|_| ()) |
| 833 | } |
| 834 | |
| 835 | async fn send_error(tx: &EventSender, code: &str, message: &str) { |
| 836 | let _ = send(tx, "error", json!({ "code": code, "message": message })).await; |
| 837 | } |
| 838 | |
| 839 | |
| 840 | |
| 841 | |
| 842 | |
| 843 | |
| 844 | |
| 845 | |
| 846 | |
| 847 | |
| 848 | |
| 849 | |
| 850 | fn slice_reply(text: &str) -> Vec<String> { |
| 851 | let chars: Vec<char> = text.chars().collect(); |
| 852 | if chars.is_empty() { |
| 853 | return Vec::new(); |
| 854 | } |
| 855 | let size = chars.len().div_ceil(REPLY_CHUNKS).max(MIN_CHUNK_CHARS); |
| 856 | chars |
| 857 | .chunks(size) |
| 858 | .map(|chunk| chunk.iter().collect()) |
| 859 | .collect() |
| 860 | } |
| 861 | |
| 862 | #[cfg(test)] |
| 863 | mod tests { |
| 864 | use super::*; |
| 865 | |
| 866 | #[tokio::test] |
| 867 | async fn slicing_preserves_the_answer_exactly() { |
| 868 | for text in [ |
| 869 | "", |
| 870 | "x", |
| 871 | "kısa cevap", |
| 872 | &"é".repeat(1_000), |
| 873 | &"a".repeat(7_999), |
| 874 | ] { |
| 875 | let chunks = slice_reply(text); |
| 876 | assert_eq!( |
| 877 | chunks.concat(), |
| 878 | text, |
| 879 | "chunks must rejoin into the original answer" |
| 880 | ); |
| 881 | assert!( |
| 882 | chunks.iter().all(|chunk| !chunk.is_empty()), |
| 883 | "an empty delta says nothing" |
| 884 | ); |
| 885 | assert!( |
| 886 | chunks.len() <= REPLY_CHUNKS, |
| 887 | "{} chunks for {} chars", |
| 888 | chunks.len(), |
| 889 | text.chars().count() |
| 890 | ); |
| 891 | } |
| 892 | |
| 893 | assert!(slice_reply("").is_empty()); |
| 894 | |
| 895 | assert_eq!(slice_reply("hi"), vec!["hi".to_string()]); |
| 896 | } |
| 897 | |
| 898 | #[tokio::test] |
| 899 | async fn history_reaches_past_failed_answers_to_fill_the_window() { |
| 900 | |
| 901 | |
| 902 | |
| 903 | let db = crate::database::init_mem().await.unwrap(); |
| 904 | |
| 905 | |
| 906 | db.query("CREATE chatbot_thread:c SET user_id = user:u, created_at = 0, updated_at = 0") |
| 907 | .await |
| 908 | .unwrap() |
| 909 | .check() |
| 910 | .unwrap(); |
| 911 | let thread = ChatbotThreadId::from_key("c"); |
| 912 | let user = UserId::from_key("u"); |
| 913 | let say = |text: String| ChatContent::try_new(&text).unwrap(); |
| 914 | |
| 915 | for turn in 0..10 { |
| 916 | service::chatbot_message::append_user(&db, &thread, &user, say(format!("soru {turn}"))) |
| 917 | .await |
| 918 | .unwrap(); |
| 919 | let answer = service::chatbot_message::append_pending_assistant(&db, &thread, &user) |
| 920 | .await |
| 921 | .unwrap(); |
| 922 | service::chatbot_message::complete( |
| 923 | &db, |
| 924 | answer.get_id(), |
| 925 | say(format!("cevap {turn}")), |
| 926 | false, |
| 927 | ) |
| 928 | .await |
| 929 | .unwrap(); |
| 930 | } |
| 931 | |
| 932 | for turn in 0..5 { |
| 933 | service::chatbot_message::append_user( |
| 934 | &db, |
| 935 | &thread, |
| 936 | &user, |
| 937 | say(format!("kayıp {turn}")), |
| 938 | ) |
| 939 | .await |
| 940 | .unwrap(); |
| 941 | let answer = service::chatbot_message::append_pending_assistant(&db, &thread, &user) |
| 942 | .await |
| 943 | .unwrap(); |
| 944 | service::chatbot_message::fail(&db, answer.get_id(), "timed_out") |
| 945 | .await |
| 946 | .unwrap(); |
| 947 | } |
| 948 | |
| 949 | let prompt = service::chatbot_message::append_user(&db, &thread, &user, say("yeni".into())) |
| 950 | .await |
| 951 | .unwrap(); |
| 952 | let pending = service::chatbot_message::append_pending_assistant(&db, &thread, &user) |
| 953 | .await |
| 954 | .unwrap(); |
| 955 | let fresh = [prompt.get_id().clone(), pending.get_id().clone()]; |
| 956 | |
| 957 | let history = history_for(&db, &thread, &fresh, 6).await.unwrap(); |
| 958 | let texts: Vec<&str> = history.iter().map(|turn| turn.content.as_str()).collect(); |
| 959 | assert_eq!( |
| 960 | texts, |
| 961 | [ |
| 962 | "cevap 9", "kayıp 0", "kayıp 1", "kayıp 2", "kayıp 3", "kayıp 4" |
| 963 | ], |
| 964 | "six settled turns, oldest first, reaching back over the failures" |
| 965 | ); |
| 966 | |
| 967 | assert!(!texts.contains(&"yeni")); |
| 968 | } |
| 969 | |
| 970 | #[tokio::test] |
| 971 | async fn failure_codes_are_stable_slugs() { |
| 972 | assert_eq!( |
| 973 | failure_code(AiError::NoWorker("chat.reply".into())), |
| 974 | "unavailable" |
| 975 | ); |
| 976 | assert_eq!(failure_code(AiError::Timeout(30_000)), "timed_out"); |
| 977 | assert_eq!( |
| 978 | failure_code(AiError::Remote { |
| 979 | code: "quota_exhausted".into(), |
| 980 | message: "no credit".into(), |
| 981 | }), |
| 982 | "quota_exhausted" |
| 983 | ); |
| 984 | |
| 985 | assert_eq!( |
| 986 | failure_code(AiError::Remote { |
| 987 | code: " ".into(), |
| 988 | message: String::new(), |
| 989 | }), |
| 990 | "service_error" |
| 991 | ); |
| 992 | } |
| 993 | } |