🔍 Code Extractor

function get_session_history

Maturity: 45

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

File:
/tf/active/vicechatdev/docchat/app.py
Lines:
950 - 957
Complexity:
simple

Purpose

This function serves as a REST API endpoint to fetch all chat messages associated with the current user's session. It checks for an active session ID, retrieves or creates the corresponding chat session, and returns the message history as JSON. This is typically used by frontend applications to display conversation history when a user returns to an active chat session or refreshes the page.

Source Code

def get_session_history():
    """Get chat history for current session"""
    session_id = session.get('session_id')
    if not session_id:
        return jsonify({'messages': []})
    
    chat_session = get_or_create_session(session_id)
    return jsonify({'messages': chat_session.get('messages', [])})

Return Value

Returns a Flask JSON response object containing a dictionary with a 'messages' key. The value is either an empty list (if no session exists) or a list of message objects from the chat session. Each message object typically contains fields like 'role', 'content', 'timestamp', etc. The HTTP status code is 200 by default.

Dependencies

  • flask
  • uuid
  • pathlib
  • functools
  • logging
  • datetime
  • threading
  • werkzeug
  • json
  • os
  • time
  • docx
  • reportlab
  • io
  • traceback

Required Imports

from flask import Flask
from flask import jsonify
from flask import session
from functools import wraps

Conditional/Optional Imports

These imports are only needed under specific conditions:

import config

Condition: Required if get_or_create_session function depends on application configuration settings

Required (conditional)
from auth.azure_auth import validate_azure_token

Condition: Required for the login_required decorator if using Azure SSO authentication

Required (conditional)

Usage Example

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

# Server-side testing:
from flask import Flask, session
from flask.testing import FlaskClient

app = Flask(__name__)
app.secret_key = 'test-secret-key'

# Assuming the route is registered
with app.test_client() as client:
    with client.session_transaction() as sess:
        sess['session_id'] = 'test-session-123'
    
    response = client.get('/api/session/history')
    data = response.get_json()
    print(data['messages'])  # Prints message history

Best Practices

  • Ensure the Flask session is properly configured with a secure SECRET_KEY in production
  • The login_required decorator should be implemented to prevent unauthorized access to chat history
  • Consider adding error handling for cases where get_or_create_session() might fail
  • Implement rate limiting to prevent abuse of this endpoint
  • Consider pagination if message history can grow very large
  • Add logging for debugging session retrieval issues
  • Validate session_id format before processing to prevent injection attacks
  • Consider adding cache headers to control client-side caching behavior
  • Ensure CORS is properly configured if the API is accessed from a different domain
  • The get_or_create_session() function should handle thread-safety if using in-memory storage

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_history 93.6% similar

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

    From: /tf/active/vicechatdev/docchat/blueprint.py
  • function api_get_chat_session_v1 82.2% 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 api_get_chat_session 80.9% 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_clear_chat_session 80.3% similar

    Flask API endpoint that clears the chat history for a specific chat session identified by session_id.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_clear_history 79.4% 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
← Back to Browse