function api_clear_memory
Flask API endpoint that clears the chat memory from the server-side chat engine, removing all stored conversation messages.
/tf/active/vicechatdev/vice_ai/app.py
1314 - 1341
simple
Purpose
This endpoint provides a way to reset the conversational context by clearing all messages stored in the chat engine's memory. It's useful for starting fresh conversations, managing memory usage, or implementing session reset functionality. The function includes logging to track the number of messages cleared and handles cases where the chat engine or memory is unavailable.
Source Code
def api_clear_memory():
"""Clear the chat memory on the server side"""
try:
if not chat_engine:
return jsonify({'error': 'Chat engine not available'}), 500
if hasattr(chat_engine, 'chat_memory') and chat_engine.chat_memory:
messages_before = len(chat_engine.chat_memory.messages) if hasattr(chat_engine.chat_memory, 'messages') else 0
logger.info(f"๐งน Clearing chat memory - {messages_before} messages before clearing")
# Clear the chat memory
chat_engine.chat_memory.messages = []
# Verify memory was cleared
messages_after = len(chat_engine.chat_memory.messages) if hasattr(chat_engine.chat_memory, 'messages') else 0
logger.info(f"โ
Chat memory cleared - {messages_after} messages after clearing")
return jsonify({
'message': 'Chat memory cleared successfully',
'messages_cleared': messages_before
})
else:
logger.warning("โ ๏ธ Chat engine does not have chat_memory attribute or it's None")
return jsonify({'message': 'No chat memory to clear'})
except Exception as e:
logger.error(f"Clear memory API error: {e}")
return jsonify({'error': 'Failed to clear chat memory'}), 500
Return Value
Returns a Flask JSON response tuple. On success: {'message': 'Chat memory cleared successfully', 'messages_cleared': <int>} with status 200. If no memory exists: {'message': 'No chat memory to clear'} with status 200. On error: {'error': 'Chat engine not available'} or {'error': 'Failed to clear chat memory'} with status 500.
Dependencies
flasklogging
Required Imports
from flask import jsonify
import logging
Usage Example
# Server-side setup (in main Flask app)
from flask import Flask, jsonify
import logging
app = Flask(__name__)
logger = logging.getLogger(__name__)
# Initialize chat engine (example)
from hybrid_rag_engine import OneCo_hybrid_RAG
chat_engine = OneCo_hybrid_RAG()
# Apply route and auth decorators
@app.route('/api/clear-memory', methods=['POST'])
@require_auth
def api_clear_memory():
# ... function code ...
pass
# Client-side usage (JavaScript/fetch)
fetch('/api/clear-memory', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer <token>'
}
})
.then(response => response.json())
.then(data => {
console.log(`Cleared ${data.messages_cleared} messages`);
})
.catch(error => console.error('Error:', error));
Best Practices
- Ensure the global 'chat_engine' object is properly initialized before this endpoint is called
- The endpoint requires authentication via the 'require_auth' decorator - ensure users are authenticated
- This is a destructive operation - consider adding confirmation mechanisms in the client UI
- The function logs the number of messages cleared, which is useful for monitoring and debugging
- Error handling is comprehensive, catching both missing chat engine and general exceptions
- The function verifies that memory was actually cleared by checking message count after clearing
- Consider implementing backup/restore functionality if users might need to recover cleared conversations
- This endpoint uses POST method appropriately as it modifies server state
- The function gracefully handles cases where chat_memory doesn't exist or is None
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function clear_session 80.6% similar
-
function api_clear_history 80.3% similar
-
function api_clear_chat_session 78.1% similar
-
function clear_text_section_chat 70.6% similar
-
function clear_session_v1 65.3% similar