Chat API
AI chat conversation management and streaming endpoints
Chat API
The Chat API enables users to interact with AI assistants for academic support, question answering, and study assistance. Supports conversation management, message history, and AI-powered responses with streaming capabilities.
Chat Session Model
- id: Unique chat session identifier (string)
- title: Session title (string, 1-255 characters)
- userId: Owner user ID (string)
- createdAt: ISO datetime when created (string)
- updatedAt: ISO datetime when last updated (string)
- messages: Array of message objects
Message Model
- id: Unique message identifier (string)
- content: Message content (string)
- role: Message role (string: "user" | "assistant" | "system")
- chatSessionId: Parent chat session ID (string)
- createdAt: ISO datetime when created (string)
Endpoints
All chat endpoints require authentication and are scoped to the authenticated user.
Create Chat Session
Create a new chat conversation session with optional first message.
POST /api/chat/sessions
Content-Type: application/json
{
"title": "Biology Study Help",
"initialMessage": "I need help understanding cell division"
}Request Body Parameters
- title: Session title (optional, defaults to generated title)
- initialMessage: First user message (optional)
Response (201)
{
"success": true,
"data": {
"id": "chat_abc123",
"title": "Biology Study Help",
"userId": "user_123",
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-01T00:00:00.000Z",
"messages": [
{
"id": "message_abc123",
"content": "I need help understanding cell division",
"role": "user",
"chatSessionId": "chat_abc123",
"createdAt": "2024-01-01T00:00:00.000Z"
}
]
},
"message": "Chat session created successfully"
}Errors:
400: Invalid input data401: Authentication required
Get All Chat Sessions
Retrieve all chat sessions for the authenticated user.
GET /api/chat/sessions
# With search
GET /api/chat/sessions?search=biologyQuery Parameters
- search: Search in session titles and message content (optional)
Response (200)
{
"success": true,
"data": [
{
"id": "chat_abc123",
"title": "Biology Study Help",
"userId": "user_123",
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-01T12:00:00.000Z",
"messages": [
{
"id": "message_abc123",
"content": "I need help understanding cell division",
"role": "user",
"chatSessionId": "chat_abc123",
"createdAt": "2024-01-01T00:00:00.000Z"
}
]
}
],
"message": "Chat sessions retrieved successfully"
}Errors:
401: Authentication required
Get Chat Session by ID
Retrieve a specific chat session with all messages.
GET /api/chat/sessions/{sessionId}Path Parameters
- sessionId: Chat session ID (required)
Response (200)
Returns the same structure as the create chat session response.
Errors:
401: Authentication required404: Chat session not found
Send Message (Streaming)
Send a message in a chat session and receive AI response via Server-Sent Events (SSE).
POST /api/chat/sessions/{sessionId}/messages
Content-Type: application/json
{
"message": "Can you explain mitosis in simple terms?"
}Path Parameters
- sessionId: Chat session ID (required)
Request Body Parameters
- message: Message content (required, 1-10000 characters)
Response (200 - Streaming)
This endpoint returns a Server-Sent Events (SSE) stream for real-time AI responses:
data: {"type": "userMessage", "data": {"id": "message_def456", "content": "Can you explain mitosis in simple terms?", "role": "user", "chatSessionId": "chat_abc123", "createdAt": "2024-01-01T12:00:00.000Z"}}
data: {"type": "assistantMessageStart", "data": {"id": "message_ghi789", "chatSessionId": "chat_abc123"}}
data: {"type": "assistantMessageDelta", "data": {"content": "Mitosis is the process"}}
data: {"type": "assistantMessageDelta", "data": {"content": " where a cell divides"}}
data: {"type": "assistantMessageEnd", "data": {"id": "message_ghi789", "content": "Mitosis is the process where a cell divides to create two identical daughter cells...", "role": "assistant", "chatSessionId": "chat_abc123", "createdAt": "2024-01-01T12:00:01.000Z"}}
data: {"type": "done"}Event Types:
userMessage: User's message has been savedassistantMessageStart: AI response generation startedassistantMessageDelta: Incremental AI response contentassistantMessageEnd: AI response generation completeddone: Stream completed
Errors:
400: Invalid message content401: Authentication required404: Chat session not found
Update Chat Session
Update chat session metadata (title, etc.).
PUT /api/chat/sessions/{sessionId}
Content-Type: application/json
{
"title": "Updated Biology Discussion"
}Path Parameters
- sessionId: Chat session ID (required)
Request Body Parameters
- title: New session title (optional)
Response (200)
{
"success": true,
"data": {
"id": "chat_abc123",
"title": "Updated Biology Discussion",
"userId": "user_123",
"createdAt": "2024-01-01T00:00:00.000Z",
"updatedAt": "2024-01-01T12:00:00.000Z"
},
"message": "Chat session updated successfully"
}Errors:
400: Invalid input data401: Authentication required404: Chat session not found
Delete Chat Session
Delete a chat session and all associated messages.
DELETE /api/chat/sessions/{sessionId}Path Parameters
- sessionId: Chat session ID (required)
Response (200)
{
"success": true,
"message": "Chat session deleted successfully"
}Errors:
401: Authentication required404: Chat session not found
Usage Examples
Creating a Study Session
// Create a new chat session for studying
const response = await fetch('/api/chat/sessions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-token'
},
body: JSON.stringify({
title: 'Chemistry Study Session',
initialMessage: 'Help me understand chemical bonding'
})
});
const { data } = await response.json();
console.log('Session created:', data.id);Streaming Chat Messages
// Send a message and handle streaming response
const response = await fetch(`/api/chat/sessions/${sessionId}/messages`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-token'
},
body: JSON.stringify({
message: 'Explain covalent bonds'
})
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = JSON.parse(line.slice(6));
switch (data.type) {
case 'assistantMessageDelta':
// Update UI with incremental content
updateChatUI(data.data.content);
break;
case 'assistantMessageEnd':
// Final message is complete
finalizeChatMessage(data.data);
break;
}
}
}
}Integration Notes
- All endpoints support compression except streaming routes
- Streaming responses use Server-Sent Events (SSE) format
- Chat sessions are automatically scoped to the authenticated user
- Large context windows are supported for comprehensive academic discussions
- AI responses are contextually aware of course materials and previous conversations