Spaces:
Running
Running
File size: 1,502 Bytes
a63c61f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | import json
from typing import List, Optional
from sqlalchemy.orm import Session
from src.core.ports.chat_history_port import ChatHistoryPort, ChatMessage
class Message(ChatMessage):
def __init__(self, role: str, content: str):
self.role = role
self.content = content
class PostgresAdapter(ChatHistoryPort):
def __init__(self, db_session: Session):
self.db = db_session
def get_history(self, session_id: str, limit: int = 6) -> List[ChatMessage]:
from src.core.domain.db_models import ChatHistory
past_messages = (
self.db.query(ChatHistory)
.filter(ChatHistory.session_id == session_id)
.order_by(ChatHistory.timestamp.asc())
.limit(limit)
.all()
)
return [Message(role=msg.role, content=msg.content) for msg in past_messages]
def save_interaction(self, session_id: str, user_query: str, ai_response: str,
retrieved_doc_ids: List[str], user_id: Optional[int] = None):
from src.core.domain.db_models import ChatHistory
user_msg = ChatHistory(session_id=session_id, role="user", content=user_query, user_id=user_id)
ai_msg = ChatHistory(
session_id=session_id,
role="assistant",
content=ai_response,
retrieved_doc_ids=json.dumps(retrieved_doc_ids),
user_id=user_id
)
self.db.add(user_msg)
self.db.add(ai_msg)
self.db.commit()
|