Spaces:
Runtime error
Runtime error
File size: 23,599 Bytes
330b6e4 | 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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 | # Chat Agent API Documentation
This document describes the REST API endpoints for the multi-language chat agent.
## Base URL
All API endpoints are prefixed with `/api/v1/chat`
## Authentication
All endpoints (except health check and supported languages) require authentication via one of the following methods:
### Header-based Authentication (Development)
```
X-User-ID: your-user-id
```
### Token-based Authentication (Production)
```
Authorization: Bearer your-session-token
```
## Rate Limiting
The API implements rate limiting to prevent abuse:
- Default: 200 requests per day, 50 requests per hour
- Session creation: 10 requests per minute
- Session deletion: 5 requests per minute
- Other endpoints: 20-30 requests per minute
Rate limit exceeded responses return HTTP 429 with retry information.
## Endpoints
### 1. Get Supported Languages
Get a list of all supported programming languages.
**Endpoint:** `GET /api/v1/chat/languages`
**Authentication:** Not required
**Response:**
```json
{
"languages": [
{
"code": "python",
"name": "Python",
"syntax_highlighting": "python",
"file_extensions": [".py", ".pyw"]
},
{
"code": "javascript",
"name": "JavaScript",
"syntax_highlighting": "javascript",
"file_extensions": [".js", ".mjs"]
}
],
"default_language": "python",
"total_count": 8
}
```
### 2. Create Chat Session
Create a new chat session for a user.
**Endpoint:** `POST /api/v1/chat/sessions`
**Authentication:** Required
**Request Body:**
```json
{
"language": "python",
"metadata": {
"source": "web_app",
"user_preferences": {}
}
}
```
**Response (201 Created):**
```json
{
"session_id": "uuid-string",
"user_id": "user-123",
"language": "python",
"created_at": "2023-01-01T00:00:00",
"message_count": 0,
"metadata": {
"source": "web_app"
}
}
```
**Error Responses:**
- `400 Bad Request`: Invalid language or missing required fields
- `401 Unauthorized`: Missing or invalid authentication
- `429 Too Many Requests`: Rate limit exceeded
### 3. Get Chat Session
Retrieve information about a specific chat session.
**Endpoint:** `GET /api/v1/chat/sessions/{session_id}`
**Authentication:** Required (must own the session)
**Response (200 OK):**
```json
{
"session_id": "uuid-string",
"user_id": "user-123",
"language": "python",
"created_at": "2023-01-01T00:00:00",
"last_active": "2023-01-01T01:00:00",
"message_count": 5,
"is_active": true,
"metadata": {}
}
```
**Error Responses:**
- `403 Forbidden`: Session belongs to different user
- `404 Not Found`: Session does not exist
- `410 Gone`: Session has expired
### 4. List User Sessions
Get all sessions for the authenticated user.
**Endpoint:** `GET /api/v1/chat/sessions`
**Authentication:** Required
**Query Parameters:**
- `active_only` (boolean, default: true): Only return active sessions
**Response (200 OK):**
```json
{
"sessions": [
{
"session_id": "uuid-string",
"language": "python",
"created_at": "2023-01-01T00:00:00",
"last_active": "2023-01-01T01:00:00",
"message_count": 5,
"is_active": true,
"metadata": {}
}
],
"total_count": 1,
"active_only": true
}
```
### 5. Delete Chat Session
Delete a chat session and all associated data.
**Endpoint:** `DELETE /api/v1/chat/sessions/{session_id}`
**Authentication:** Required (must own the session)
**Response (200 OK):**
```json
{
"message": "Session deleted successfully",
"session_id": "uuid-string",
"messages_deleted": 10
}
```
**Error Responses:**
- `403 Forbidden`: Session belongs to different user
- `404 Not Found`: Session does not exist
### 6. Get Chat History
Retrieve chat history for a session.
**Endpoint:** `GET /api/v1/chat/sessions/{session_id}/history`
**Authentication:** Required (must own the session)
**Query Parameters:**
- `page` (integer, default: 1): Page number for pagination
- `page_size` (integer, default: 50, max: 100): Messages per page
- `recent_only` (boolean, default: false): Get only recent messages
- `limit` (integer, default: 10, max: 50): Number of recent messages (when recent_only=true)
**Response (200 OK):**
```json
{
"messages": [
{
"id": "uuid-string",
"role": "user",
"content": "Hello, can you help me with Python?",
"language": "python",
"timestamp": "2023-01-01T00:00:00",
"metadata": {}
},
{
"id": "uuid-string",
"role": "assistant",
"content": "Of course! I'd be happy to help you with Python.",
"language": "python",
"timestamp": "2023-01-01T00:01:00",
"metadata": {
"tokens": 15
}
}
],
"session_id": "uuid-string",
"total_count": 2,
"page": 1,
"page_size": 50,
"total_pages": 1
}
```
### 7. Search Chat History
Search messages within a session.
**Endpoint:** `GET /api/v1/chat/sessions/{session_id}/history/search`
**Authentication:** Required (must own the session)
**Query Parameters:**
- `q` (string, required, min: 3 chars): Search query
- `limit` (integer, default: 20, max: 50): Maximum results
**Response (200 OK):**
```json
{
"messages": [
{
"id": "uuid-string",
"role": "user",
"content": "How do I use Python lists?",
"language": "python",
"timestamp": "2023-01-01T00:00:00",
"metadata": {}
}
],
"session_id": "uuid-string",
"query": "Python",
"result_count": 1
}
```
**Error Responses:**
- `400 Bad Request`: Query too short or missing
### 8. Get Language Context
Get the current language context for a session.
**Endpoint:** `GET /api/v1/chat/sessions/{session_id}/language`
**Authentication:** Required (must own the session)
**Response (200 OK):**
```json
{
"session_id": "uuid-string",
"language": "python",
"prompt_template": "You are a helpful Python programming assistant...",
"syntax_highlighting": "python",
"language_info": {
"name": "Python",
"syntax_highlighting": "python",
"file_extensions": [".py", ".pyw"],
"prompt_template": "..."
},
"updated_at": "2023-01-01T00:00:00"
}
```
### 9. Update Language Context
Change the programming language for a session.
**Endpoint:** `PUT /api/v1/chat/sessions/{session_id}/language`
**Authentication:** Required (must own the session)
**Request Body:**
```json
{
"language": "javascript"
}
```
**Response (200 OK):**
```json
{
"session_id": "uuid-string",
"language": "javascript",
"prompt_template": "You are a helpful JavaScript programming assistant...",
"syntax_highlighting": "javascript",
"language_info": {
"name": "JavaScript",
"syntax_highlighting": "javascript",
"file_extensions": [".js", ".mjs"],
"prompt_template": "..."
},
"updated_at": "2023-01-01T01:00:00"
}
```
**Error Responses:**
- `400 Bad Request`: Unsupported language
### 10. Health Check
Check the health status of the API and its dependencies.
**Endpoint:** `GET /api/v1/chat/health`
**Authentication:** Not required
**Response (200 OK):**
```json
{
"status": "healthy",
"timestamp": "2023-01-01T00:00:00",
"services": {
"database": "connected",
"redis": "connected"
}
}
```
**Response (503 Service Unavailable):**
```json
{
"status": "unhealthy",
"timestamp": "2023-01-01T00:00:00",
"error": "Database connection failed"
}
```
## Error Responses
All error responses follow a consistent format:
```json
{
"error": "Error type",
"message": "Detailed error message"
}
```
### Common HTTP Status Codes
- `200 OK`: Request successful
- `201 Created`: Resource created successfully
- `400 Bad Request`: Invalid request data
- `401 Unauthorized`: Authentication required
- `403 Forbidden`: Access denied
- `404 Not Found`: Resource not found
- `410 Gone`: Resource expired
- `429 Too Many Requests`: Rate limit exceeded
- `500 Internal Server Error`: Server error
- `503 Service Unavailable`: Service temporarily unavailable
## Security Considerations
1. **Authentication**: All endpoints require valid authentication
2. **Authorization**: Users can only access their own sessions
3. **Rate Limiting**: Prevents abuse and manages API costs
4. **Input Validation**: All inputs are validated and sanitized
5. **Error Handling**: Errors don't expose sensitive information
## Usage Examples
### Create a Session and Send Messages
```bash
# Create session
curl -X POST http://localhost:5000/api/v1/chat/sessions \
-H "X-User-ID: user-123" \
-H "Content-Type: application/json" \
-d '{"language": "python"}'
# Get session info
curl -X GET http://localhost:5000/api/v1/chat/sessions/{session_id} \
-H "X-User-ID: user-123"
# Change language
curl -X PUT http://localhost:5000/api/v1/chat/sessions/{session_id}/language \
-H "X-User-ID: user-123" \
-H "Content-Type: application/json" \
-d '{"language": "javascript"}'
# Get chat history
curl -X GET http://localhost:5000/api/v1/chat/sessions/{session_id}/history \
-H "X-User-ID: user-123"
# Delete session
curl -X DELETE http://localhost:5000/api/v1/chat/sessions/{session_id} \
-H "X-User-ID: user-123"
```
### JavaScript/TypeScript Example
```javascript
const API_BASE = 'http://localhost:5000/api/v1/chat';
const USER_ID = 'user-123';
// Create session
const response = await fetch(`${API_BASE}/sessions`, {
method: 'POST',
headers: {
'X-User-ID': USER_ID,
'Content-Type': 'application/json'
},
body: JSON.stringify({
language: 'python',
metadata: { source: 'web_app' }
})
});
const session = await response.json();
console.log('Created session:', session.session_id);
// Get chat history
const historyResponse = await fetch(
`${API_BASE}/sessions/${session.session_id}/history`,
{
headers: { 'X-User-ID': USER_ID }
}
);
const history = await historyResponse.json();
console.log('Messages:', history.messages);
```
## WebSocket API Documentation
The chat agent also supports real-time communication via WebSocket for interactive chat sessions.
### WebSocket Connection
**Endpoint:** `ws://localhost:5000/socket.io/`
**Authentication:** Include user ID in connection query parameters or headers
**Connection Example:**
```javascript
const socket = io('http://localhost:5000', {
query: { user_id: 'user-123' },
transports: ['websocket']
});
```
### WebSocket Events
#### 1. Connect Event
Automatically triggered when client connects.
**Client sends:**
```javascript
// Connection is automatic, but you can send auth data
socket.emit('authenticate', {
user_id: 'user-123',
session_token: 'optional-token'
});
```
**Server responds:**
```javascript
socket.on('connected', (data) => {
console.log(data);
// {
// "status": "connected",
// "user_id": "user-123",
// "timestamp": "2023-01-01T00:00:00Z"
// }
});
```
#### 2. Send Message Event
Send a chat message to the assistant.
**Client sends:**
```javascript
socket.emit('message', {
session_id: 'session-uuid',
content: 'How do I create a Python list?',
language: 'python',
metadata: {
source: 'web_chat',
timestamp: new Date().toISOString()
}
});
```
**Server responds:**
```javascript
socket.on('message_response', (data) => {
console.log(data);
// {
// "session_id": "session-uuid",
// "message_id": "msg-uuid",
// "content": "To create a Python list, you can use square brackets...",
// "language": "python",
// "timestamp": "2023-01-01T00:01:00Z",
// "metadata": {
// "tokens": 45,
// "response_time": 0.85
// }
// }
});
```
#### 3. Streaming Response Event
For real-time streaming responses.
**Client sends:**
```javascript
socket.emit('message_stream', {
session_id: 'session-uuid',
content: 'Explain Python functions in detail',
language: 'python'
});
```
**Server responds with multiple events:**
```javascript
socket.on('stream_start', (data) => {
// { "session_id": "session-uuid", "message_id": "msg-uuid" }
});
socket.on('stream_chunk', (data) => {
// { "session_id": "session-uuid", "chunk": "A Python function is..." }
});
socket.on('stream_end', (data) => {
// { "session_id": "session-uuid", "complete_response": "..." }
});
```
#### 4. Language Switch Event
Change the programming language context.
**Client sends:**
```javascript
socket.emit('language_switch', {
session_id: 'session-uuid',
language: 'javascript'
});
```
**Server responds:**
```javascript
socket.on('language_switched', (data) => {
// {
// "session_id": "session-uuid",
// "previous_language": "python",
// "new_language": "javascript",
// "timestamp": "2023-01-01T00:02:00Z"
// }
});
```
#### 5. Typing Indicator Events
Show when user or assistant is typing.
**Client sends:**
```javascript
socket.emit('typing_start', {
session_id: 'session-uuid'
});
socket.emit('typing_stop', {
session_id: 'session-uuid'
});
```
**Server responds:**
```javascript
socket.on('assistant_typing', (data) => {
// { "session_id": "session-uuid", "typing": true }
});
socket.on('assistant_typing_stop', (data) => {
// { "session_id": "session-uuid", "typing": false }
});
```
#### 6. Error Events
Handle various error conditions.
**Server sends:**
```javascript
socket.on('error', (data) => {
console.error(data);
// {
// "error": "session_not_found",
// "message": "Session does not exist or has expired",
// "session_id": "session-uuid",
// "timestamp": "2023-01-01T00:03:00Z"
// }
});
```
### Complete WebSocket Example
```html
<!DOCTYPE html>
<html>
<head>
<title>Chat Agent WebSocket Example</title>
<script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
</head>
<body>
<div id="messages"></div>
<input type="text" id="messageInput" placeholder="Type your message...">
<select id="languageSelect">
<option value="python">Python</option>
<option value="javascript">JavaScript</option>
<option value="java">Java</option>
</select>
<button onclick="sendMessage()">Send</button>
<script>
const socket = io('http://localhost:5000', {
query: { user_id: 'demo-user' }
});
let currentSessionId = null;
// Create session first
fetch('/api/v1/chat/sessions', {
method: 'POST',
headers: {
'X-User-ID': 'demo-user',
'Content-Type': 'application/json'
},
body: JSON.stringify({ language: 'python' })
})
.then(response => response.json())
.then(data => {
currentSessionId = data.session_id;
console.log('Session created:', currentSessionId);
});
// Handle connection
socket.on('connected', (data) => {
console.log('Connected to chat agent:', data);
});
// Handle messages
socket.on('message_response', (data) => {
addMessage('Assistant', data.content);
});
// Handle streaming
let streamBuffer = '';
socket.on('stream_chunk', (data) => {
streamBuffer += data.chunk;
updateStreamingMessage(streamBuffer);
});
socket.on('stream_end', (data) => {
addMessage('Assistant', data.complete_response);
streamBuffer = '';
});
// Handle language switches
socket.on('language_switched', (data) => {
console.log('Language switched:', data);
addMessage('System', `Language changed to ${data.new_language}`);
});
// Handle errors
socket.on('error', (data) => {
console.error('Chat error:', data);
addMessage('Error', data.message);
});
function sendMessage() {
const input = document.getElementById('messageInput');
const message = input.value.trim();
if (message && currentSessionId) {
addMessage('You', message);
socket.emit('message', {
session_id: currentSessionId,
content: message,
language: document.getElementById('languageSelect').value
});
input.value = '';
}
}
function addMessage(sender, content) {
const messages = document.getElementById('messages');
const messageDiv = document.createElement('div');
messageDiv.innerHTML = `<strong>${sender}:</strong> ${content}`;
messages.appendChild(messageDiv);
messages.scrollTop = messages.scrollHeight;
}
// Language switching
document.getElementById('languageSelect').addEventListener('change', (e) => {
if (currentSessionId) {
socket.emit('language_switch', {
session_id: currentSessionId,
language: e.target.value
});
}
});
// Enter key to send message
document.getElementById('messageInput').addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
sendMessage();
}
});
</script>
</body>
</html>
```
## Advanced Usage Examples
### Error Handling and Retry Logic
```javascript
class ChatAPIClient {
constructor(baseURL, userID) {
this.baseURL = baseURL;
this.userID = userID;
this.maxRetries = 3;
this.retryDelay = 1000; // 1 second
}
async makeRequest(endpoint, options = {}) {
const url = `${this.baseURL}${endpoint}`;
const config = {
...options,
headers: {
'X-User-ID': this.userID,
'Content-Type': 'application/json',
...options.headers
}
};
for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
try {
const response = await fetch(url, config);
if (response.status === 429) {
// Rate limited - wait and retry
const retryAfter = response.headers.get('Retry-After') || this.retryDelay / 1000;
await this.sleep(retryAfter * 1000);
continue;
}
if (!response.ok) {
const error = await response.json();
throw new Error(`API Error: ${error.message}`);
}
return await response.json();
} catch (error) {
if (attempt === this.maxRetries) {
throw error;
}
console.warn(`Attempt ${attempt} failed, retrying...`, error.message);
await this.sleep(this.retryDelay * attempt);
}
}
}
async createSession(language = 'python') {
return await this.makeRequest('/api/v1/chat/sessions', {
method: 'POST',
body: JSON.stringify({ language })
});
}
async getChatHistory(sessionId, page = 1, pageSize = 50) {
return await this.makeRequest(
`/api/v1/chat/sessions/${sessionId}/history?page=${page}&page_size=${pageSize}`
);
}
async switchLanguage(sessionId, language) {
return await this.makeRequest(`/api/v1/chat/sessions/${sessionId}/language`, {
method: 'PUT',
body: JSON.stringify({ language })
});
}
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
// Usage
const client = new ChatAPIClient('http://localhost:5000', 'user-123');
try {
const session = await client.createSession('python');
console.log('Session created:', session.session_id);
const history = await client.getChatHistory(session.session_id);
console.log('Chat history:', history.messages);
await client.switchLanguage(session.session_id, 'javascript');
console.log('Language switched to JavaScript');
} catch (error) {
console.error('API operation failed:', error.message);
}
```
### Batch Operations
```python
import asyncio
import aiohttp
import json
class AsyncChatClient:
def __init__(self, base_url, user_id):
self.base_url = base_url
self.user_id = user_id
self.headers = {
'X-User-ID': user_id,
'Content-Type': 'application/json'
}
async def create_multiple_sessions(self, languages):
"""Create multiple sessions concurrently."""
async with aiohttp.ClientSession() as session:
tasks = []
for language in languages:
task = self._create_session(session, language)
tasks.append(task)
results = await asyncio.gather(*tasks, return_exceptions=True)
return results
async def _create_session(self, session, language):
url = f"{self.base_url}/api/v1/chat/sessions"
data = {"language": language}
async with session.post(url, headers=self.headers, json=data) as response:
if response.status == 201:
return await response.json()
else:
error = await response.json()
raise Exception(f"Failed to create {language} session: {error['message']}")
# Usage
async def main():
client = AsyncChatClient('http://localhost:5000', 'batch-user')
languages = ['python', 'javascript', 'java', 'cpp']
sessions = await client.create_multiple_sessions(languages)
for i, session in enumerate(sessions):
if isinstance(session, Exception):
print(f"Failed to create {languages[i]} session: {session}")
else:
print(f"Created {languages[i]} session: {session['session_id']}")
# Run the async function
asyncio.run(main())
```
## Implementation Notes
- The API uses SQLite for testing and PostgreSQL for production
- Redis is used for caching and session management
- Rate limiting uses in-memory storage by default (configure Redis for production)
- All timestamps are in ISO 8601 format (UTC)
- UUIDs are used for all resource identifiers
- The API supports both development (header-based) and production (token-based) authentication
- WebSocket connections are managed using Flask-SocketIO
- Streaming responses use Server-Sent Events (SSE) over WebSocket
- All WebSocket events include session_id for proper message routing
- Error handling includes automatic retry logic for transient failures
- The system supports concurrent operations across multiple sessions |