🔍 Code Extractor

function get_history

Maturity: 46

Flask API endpoint that retrieves chat message history for the current user's session from an in-memory chat_sessions dictionary.

File:
/tf/active/vicechatdev/docchat/blueprint.py
Lines:
315 - 326
Complexity:
simple

Purpose

This endpoint provides access to the conversation history for a specific chat session. It's used in a document chat application to restore previous messages when a user returns to their session or needs to view their conversation history. The function checks if a valid session_id exists in the Flask session and returns the associated messages from the chat_sessions global dictionary.

Source Code

def get_history():
    """Get chat history for current session"""
    try:
        session_id = session.get('chat_session_id')
        if session_id and session_id in chat_sessions:
            return jsonify({
                'messages': chat_sessions[session_id]['messages']
            })
        return jsonify({'messages': []})
    except Exception as e:
        logger.error(f"Error getting history: {e}")
        return jsonify({'error': str(e)}), 500

Return Value

Returns a Flask JSON response. On success: {'messages': [list of message objects]} where messages is an array from the session's chat history, or an empty array if no session exists. On error: {'error': error_message_string} with HTTP status code 500. The response is always a Flask jsonify object.

Dependencies

  • flask
  • flask-login
  • logging

Required Imports

from flask import Blueprint, jsonify, session
from flask_login import login_required
import logging

Usage Example

# Setup (in main application file)
from flask import Flask, session
from flask_login import LoginManager
import logging

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
login_manager = LoginManager()
login_manager.init_app(app)

# Global storage for chat sessions
chat_sessions = {}
logger = logging.getLogger(__name__)

# Register blueprint
from your_module import docchat_bp
app.register_blueprint(docchat_bp)

# Client-side usage (JavaScript fetch example)
fetch('/api/history', {
  method: 'GET',
  credentials: 'include',
  headers: {
    'Content-Type': 'application/json'
  }
})
.then(response => response.json())
.then(data => {
  console.log('Chat history:', data.messages);
})
.catch(error => console.error('Error:', error));

Best Practices

  • Ensure the global 'chat_sessions' dictionary is properly managed to avoid memory leaks in production (consider using Redis or database for persistence)
  • The function requires user authentication via @login_required decorator, ensure users are logged in before accessing
  • Session data is stored in-memory and will be lost on server restart; implement persistent storage for production use
  • Consider adding pagination for large message histories to improve performance
  • The session_id should be validated to prevent unauthorized access to other users' chat histories
  • Implement session cleanup mechanisms to remove old or inactive sessions from memory
  • Consider adding rate limiting to prevent abuse of the history endpoint
  • The error logging captures exceptions but returns generic error messages; consider more specific error handling for different failure scenarios

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_session_history 93.6% similar

    Flask API endpoint that retrieves the chat message history for the current user's session.

    From: /tf/active/vicechatdev/docchat/app.py
  • function api_clear_history 81.3% similar

    Flask API endpoint that clears the chat history for the current user session by removing stored conversation data associated with the session ID.

    From: /tf/active/vicechatdev/docchat/app.py
  • function api_get_chat_session 79.1% similar

    Flask API endpoint that retrieves a specific chat session by ID, verifying user access permissions before returning the session data.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function api_get_chat_session_v1 78.4% similar

    Flask API endpoint that retrieves a specific chat session by its ID and returns it as JSON.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function get_section_chat_history 78.0% similar

    Flask API endpoint that retrieves chat history for a specific text section, verifying user ownership before returning messages.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
← Back to Browse