turn.rs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. use uuid::Uuid;
  2. use chrono::{DateTime, Utc};
  3. use sqlx::{PgPool, FromRow};
  4. use serde::Serialize;
  5. use crate::http_error::HttpError;
  6. #[derive(Serialize, FromRow)]
  7. pub struct Turn {
  8. pub id: Uuid,
  9. pub session_id: Uuid,
  10. pub tokens_used: i32,
  11. pub user_text: String,
  12. pub llm_text: String,
  13. pub created_at: DateTime<Utc>
  14. }
  15. impl Turn {
  16. pub fn new(
  17. session_id: Uuid,
  18. input_tokens: i32,
  19. output_tokens: i32,
  20. user_text: String,
  21. llm_text: String
  22. ) -> Self {
  23. Self {
  24. id: Uuid::now_v7(),
  25. session_id: session_id,
  26. tokens_used: input_tokens + (output_tokens * 2),
  27. user_text: user_text,
  28. llm_text: llm_text,
  29. created_at: Utc::now()
  30. }
  31. }
  32. pub async fn insert(&self, db: &PgPool) -> Result<(), HttpError> {
  33. sqlx::query(
  34. "INSERT INTO turns(id, session_id, tokens_used, user_text, llm_text, created_at)
  35. VALUES($1, $2, $3, $4, $5, $6)"
  36. )
  37. .bind(&self.id)
  38. .bind(&self.session_id)
  39. .bind(&self.tokens_used)
  40. .bind(&self.user_text)
  41. .bind(&self.llm_text)
  42. .bind(&self.created_at)
  43. .execute(db)
  44. .await?;
  45. Ok(())
  46. }
  47. pub async fn find_by_session(db: &PgPool, session_id: Uuid) -> Result<Vec<Turn>, HttpError> {
  48. let turns = sqlx::query_as::<_, Turn>(
  49. "SELECT *
  50. FROM turns
  51. WHERE session_id = $1
  52. ORDER BY created_at ASC"
  53. )
  54. .bind(session_id)
  55. .fetch_all(db)
  56. .await?;
  57. Ok(turns)
  58. }
  59. }