|
2 | 2 |
|
3 | 3 | import json |
4 | 4 | import logging |
5 | | -from datetime import datetime |
| 5 | +from datetime import datetime, timezone |
6 | 6 | from typing import AsyncGenerator |
7 | 7 | from uuid import UUID |
8 | 8 |
|
| 9 | +from app.adapters.outbound.db.repositories.chat_session_repository_implementation import ( # noqa: E501 |
| 10 | + NotFound as SessionNotFound, |
| 11 | +) |
9 | 12 | from app.application.services.hybrid_search_service import HybridSearchService |
10 | 13 | from app.domain.entities.chat_message import ChatMessage |
| 14 | +from app.domain.entities.chat_session import ChatSession |
11 | 15 | from app.domain.ports.outbound.llm_port import LLMPort |
12 | 16 | from app.domain.ports.outbound.reranker import Reranker |
13 | 17 | from app.domain.services.citation_policy import ( |
@@ -44,6 +48,35 @@ def __init__( |
44 | 48 | self._model = model |
45 | 49 | self._usage_service = usage_service |
46 | 50 |
|
| 51 | + async def create_session( |
| 52 | + self, |
| 53 | + *, |
| 54 | + org_id: UUID, |
| 55 | + user_id: UUID, |
| 56 | + title: str, |
| 57 | + ) -> ChatSession: |
| 58 | + session = ChatSession.create(org_id=org_id, user_id=user_id, title=title) |
| 59 | + async with self._uow_factory() as uow: |
| 60 | + await uow.sessions.create_chat_session(session) |
| 61 | + await uow.commit() |
| 62 | + return session |
| 63 | + |
| 64 | + async def _ensure_session( |
| 65 | + self, uow, *, session_id: UUID, org_id: UUID, user_id: UUID |
| 66 | + ) -> None: |
| 67 | + try: |
| 68 | + await uow.sessions.get_chat_session(session_id) |
| 69 | + except SessionNotFound: |
| 70 | + session = ChatSession( |
| 71 | + id=session_id, |
| 72 | + org_id=org_id, |
| 73 | + user_id=user_id, |
| 74 | + title="New Chat", |
| 75 | + created_at=datetime.now(timezone.utc), |
| 76 | + updated_at=datetime.now(timezone.utc), |
| 77 | + ) |
| 78 | + await uow.sessions.create_chat_session(session) |
| 79 | + |
47 | 80 | async def ask_question( |
48 | 81 | self, |
49 | 82 | *, |
@@ -77,6 +110,9 @@ async def ask_question( |
77 | 110 | citations_as_dicts = [c.__dict__ for c in citations] |
78 | 111 |
|
79 | 112 | async with self._uow_factory() as uow: |
| 113 | + await self._ensure_session( |
| 114 | + uow, session_id=session_id, org_id=org_id, user_id=user_id |
| 115 | + ) |
80 | 116 | history = await uow.messages.get_recent_by_session(session_id, limit=6) |
81 | 117 |
|
82 | 118 | user_msg = ChatMessage.create_user_message( |
@@ -141,6 +177,10 @@ async def _persist_answer( |
141 | 177 | token_count: int, |
142 | 178 | ) -> None: |
143 | 179 | async with self._uow_factory() as uow: |
| 180 | + await self._ensure_session( |
| 181 | + uow, session_id=session_id, org_id=org_id, user_id=user_id |
| 182 | + ) |
| 183 | + |
144 | 184 | ai_msg = ChatMessage.create_assistant_message( |
145 | 185 | session_id=session_id, |
146 | 186 | org_id=org_id, |
|
0 commit comments