function api_clear_chat_session
Flask API endpoint that clears the chat history for a specific chat session identified by session_id.
/tf/active/vicechatdev/vice_ai/new_app.py
2215 - 2225
simple
Purpose
This endpoint provides a RESTful API interface to delete all chat messages from a specific chat session while preserving the session itself. It's used when users want to start fresh in an existing chat session without creating a new one. The function handles error cases including non-existent sessions and service failures, returning appropriate HTTP status codes and JSON responses.
Source Code
def api_clear_chat_session(session_id):
"""Clear chat session history"""
try:
success = chat_session_service.clear_chat_history(session_id)
if not success:
return jsonify({'error': 'Chat session not found'}), 404
return jsonify({'message': 'Chat history cleared successfully'})
except Exception as e:
logger.error(f"Clear chat session error: {e}")
return jsonify({'error': 'Failed to clear chat session'}), 500
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
session_id |
- | - | positional_or_keyword |
Parameter Details
session_id: String identifier for the chat session whose history should be cleared. This is extracted from the URL path parameter. Must correspond to an existing chat session in the system, otherwise a 404 error is returned.
Return Value
Returns a Flask JSON response tuple. On success (200): {'message': 'Chat history cleared successfully'}. On session not found (404): {'error': 'Chat session not found'}. On internal error (500): {'error': 'Failed to clear chat session'}. Each error response includes an appropriate HTTP status code as the second element of the tuple.
Dependencies
flasklogging
Required Imports
from flask import jsonify
import logging
Usage Example
# Client-side usage example (JavaScript fetch)
fetch('/api/chat-sessions/abc123-session-id/clear', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
if (data.message) {
console.log('Success:', data.message);
} else if (data.error) {
console.error('Error:', data.error);
}
})
.catch(error => console.error('Request failed:', error));
# Python requests example
import requests
session_id = 'abc123-session-id'
response = requests.post(f'http://localhost:5000/api/chat-sessions/{session_id}/clear')
if response.status_code == 200:
print(response.json()['message'])
elif response.status_code == 404:
print('Session not found:', response.json()['error'])
else:
print('Error:', response.json()['error'])
Best Practices
- Always check the HTTP status code in addition to the response body to properly handle different error scenarios
- The endpoint uses POST method (not DELETE) which is appropriate for clearing/resetting operations that don't delete the resource itself
- Ensure proper authentication/authorization is implemented before this endpoint in production to prevent unauthorized session clearing
- The function logs errors using logger.error() which is important for debugging and monitoring in production
- The chat_session_service.clear_chat_history() method should be idempotent - calling it multiple times should have the same effect
- Consider implementing rate limiting on this endpoint to prevent abuse
- The session_id parameter should be validated/sanitized if not already handled by the service layer
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function api_clear_history 90.6% similar
-
function clear_session 85.8% similar
-
function get_session_history 80.3% similar
-
function api_clear_memory 78.1% similar
-
function get_history 77.7% similar