Skip to content

Commit 628a86e

Browse files
authored
Created get chat history endpoint. (#53)
1 parent 6bc5f3c commit 628a86e

File tree

9 files changed

+639
-40
lines changed

9 files changed

+639
-40
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
meta {
2+
name: Get Chat History
3+
type: http
4+
seq: 1
5+
}
6+
7+
get {
8+
url: {{base_url}}/api/{{api_version}}/chat/history/{{test_session_id}}
9+
body: none
10+
auth: none
11+
}
12+
13+
settings {
14+
encodeUrl: true
15+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"version": "1",
3+
"name": "RAG Manager API",
4+
"type": "collection",
5+
"ignore": [
6+
"node_modules",
7+
".git"
8+
]
9+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
vars {
2+
base_url: http://localhost:8000
3+
api_version: v1
4+
test_session_id: 550e8400-e29b-41d4-a716-446655440000
5+
}

RAGManager/app/api/routes/__init__.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22

33
from fastapi import APIRouter
44

5-
from app.api.routes import documents
5+
from app.api.routes import chat, documents
66

77
router = APIRouter(prefix="/api/v1")
88

9-
router.include_router(documents.router)
9+
router.include_router(documents.router)
10+
router.include_router(chat.router)

RAGManager/app/api/routes/chat.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
"""API routes for chat-related endpoints."""
2+
3+
import logging
4+
from uuid import UUID
5+
6+
from fastapi import APIRouter, Depends, HTTPException
7+
from sqlalchemy.orm import Session
8+
9+
from app.core.database_connection import get_db
10+
from app.schemas.chat import ChatHistoryResponse, ChatMessageResponse
11+
from app.services.chat import get_chat_history
12+
13+
logger = logging.getLogger(__name__)
14+
15+
router = APIRouter(prefix="/chat", tags=["chat"])
16+
17+
18+
@router.get("/history/{chat_session_id}", response_model=ChatHistoryResponse)
19+
async def get_chat_history_endpoint(
20+
chat_session_id: UUID,
21+
db: Session = Depends(get_db),
22+
) -> ChatHistoryResponse:
23+
"""
24+
Retrieve the last 10 messages from a chat session.
25+
26+
This endpoint returns the most recent 10 messages from the specified chat session,
27+
ordered by creation time (most recent first).
28+
29+
Args:
30+
chat_session_id: UUID of the chat session
31+
db: Database session dependency
32+
33+
Returns:
34+
ChatHistoryResponse containing the session_id, list of messages, and count
35+
36+
Raises:
37+
HTTPException: 404 if chat session doesn't exist
38+
HTTPException: 400 if invalid UUID format
39+
HTTPException: 500 for database errors
40+
"""
41+
logger.info(f"Received chat history request for session: {chat_session_id}")
42+
43+
try:
44+
# Get chat history from service
45+
messages = get_chat_history(db, chat_session_id)
46+
47+
# Convert SQLAlchemy models to Pydantic models
48+
message_responses = [
49+
ChatMessageResponse(
50+
id=msg.id,
51+
session_id=msg.session_id,
52+
sender=msg.sender,
53+
message=msg.message,
54+
created_at=msg.created_at,
55+
)
56+
for msg in messages
57+
]
58+
59+
return ChatHistoryResponse(
60+
session_id=chat_session_id,
61+
messages=message_responses,
62+
count=len(message_responses),
63+
)
64+
65+
except ValueError as e:
66+
logger.warning(f"Chat session not found: {e}")
67+
raise HTTPException(status_code=404, detail=str(e))
68+
except Exception as e:
69+
logger.error(f"Error retrieving chat history: {e}")
70+
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")

RAGManager/app/models/chat.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,8 @@ class ChatSession(Base):
1515
__tablename__ = "chat_sessions"
1616

1717
id = Column(PGUUID(as_uuid=True), primary_key=True, server_default="uuid_generate_v4()")
18-
user_id = Column(Text, nullable=True, index=True) # User ID for ownership validation
1918
created_at = Column(TIMESTAMP, default=datetime.utcnow, nullable=False)
20-
metadata = Column(JSONB, nullable=True)
19+
session_metadata = Column("metadata", JSONB, nullable=True) # Map to 'metadata' column in DB
2120

2221
# Relationship to messages
2322
messages = relationship("ChatMessage", back_populates="session", cascade="all, delete-orphan")

RAGManager/app/schemas/chat.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
"""Pydantic schemas for chat-related endpoints."""
2+
3+
from datetime import datetime
4+
from uuid import UUID
5+
6+
from pydantic import BaseModel
7+
8+
9+
class ChatMessageResponse(BaseModel):
10+
"""Response schema for a single chat message."""
11+
12+
id: int
13+
session_id: UUID
14+
sender: str # 'user', 'assistant', or 'system'
15+
message: str
16+
created_at: datetime
17+
18+
class Config:
19+
"""Pydantic config."""
20+
21+
from_attributes = True
22+
23+
24+
class ChatHistoryResponse(BaseModel):
25+
"""Response schema for chat history endpoint."""
26+
27+
session_id: UUID
28+
messages: list[ChatMessageResponse]
29+
count: int

RAGManager/app/services/chat.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""Service functions for chat-related operations."""
2+
3+
import logging
4+
from uuid import UUID
5+
6+
from sqlalchemy.orm import Session
7+
8+
from app.models.chat import ChatMessage, ChatSession
9+
10+
logger = logging.getLogger(__name__)
11+
12+
13+
def get_chat_history(db: Session, session_id: UUID) -> list[ChatMessage]:
14+
"""
15+
Retrieve the last 10 messages from a chat session.
16+
17+
Args:
18+
db: SQLAlchemy database session
19+
session_id: UUID of the chat session
20+
21+
Returns:
22+
List of ChatMessage objects ordered by created_at DESC (most recent first)
23+
24+
Raises:
25+
ValueError: If the chat session doesn't exist
26+
"""
27+
# First, validate that the session exists
28+
session = db.query(ChatSession).filter(ChatSession.id == session_id).first()
29+
if not session:
30+
raise ValueError(f"Chat session {session_id} not found")
31+
32+
# Query the last 10 messages for this session, ordered by created_at DESC
33+
messages = (
34+
db.query(ChatMessage)
35+
.filter(ChatMessage.session_id == session_id)
36+
.order_by(ChatMessage.created_at.desc())
37+
.limit(10)
38+
.all()
39+
)
40+
41+
# Reverse to get chronological order (oldest first)
42+
# But the plan says "most recent first", so we'll keep DESC order
43+
logger.info(f"Retrieved {len(messages)} messages for session {session_id}")
44+
return messages

0 commit comments

Comments
 (0)