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