🔍 Code Extractor

function analysis_chat

Maturity: 50

Flask route handler that processes chat messages for data analysis sessions, verifying user authentication and session ownership before delegating to the data analysis service.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
6013 - 6047
Complexity:
moderate

Purpose

This endpoint serves as the API interface for interactive data analysis conversations. It validates the user's access to a specific analysis session, processes their natural language query about data, and returns analysis results including text responses, generated plots, and processed data. It's designed for real-time, conversational data exploration within a web application.

Source Code

async def analysis_chat(session_id):
    """Process a chat message for data analysis"""
    if not DATA_ANALYSIS_AVAILABLE:
        return jsonify({'error': 'Data analysis service not available'}), 503
    
    user_email = get_current_user()
    data = request.get_json()
    
    # Get session and verify ownership
    session = data_analysis_service.get_analysis_session(session_id)
    if not session or session.user_id != user_email:
        return jsonify({'error': 'Session not found or access denied'}), 404
    
    user_message = data.get('message', '').strip()
    if not user_message:
        return jsonify({'error': 'Message cannot be empty'}), 400
    
    try:
        # Process the analysis request
        result = await data_analysis_service.process_analysis_request(
            session_id=session_id,
            user_message=user_message
        )
        
        return jsonify({
            'success': True,
            'response': result['response'],
            'plots': result.get('plots', []),
            'data': result.get('data', {}),
            'session': session.to_dict()
        })
        
    except Exception as e:
        logger.error(f"Error in analysis chat: {e}")
        return jsonify({'error': str(e)}), 500

Parameters

Name Type Default Kind
session_id - - positional_or_keyword

Parameter Details

session_id: String identifier for the data analysis session. Extracted from the URL path (/api/analysis-sessions/<session_id>/chat). Used to retrieve and verify the user's analysis session before processing the message.

Return Value

Returns a Flask JSON response with different structures based on outcome: On success (200): {'success': True, 'response': str (AI-generated analysis text), 'plots': list (plot data/URLs), 'data': dict (processed data results), 'session': dict (updated session state)}. On error: {'error': str (error message)} with status codes 503 (service unavailable), 404 (session not found/access denied), 400 (empty message), or 500 (processing error).

Dependencies

  • flask
  • logging
  • data_analysis_service

Required Imports

from flask import jsonify
from flask import request
import logging
from data_analysis_service import DataAnalysisService

Conditional/Optional Imports

These imports are only needed under specific conditions:

from auth.azure_auth import AzureSSO

Condition: Required for the require_auth decorator to verify user authentication

Required (conditional)
from functools import wraps

Condition: Required if implementing the require_auth decorator

Required (conditional)

Usage Example

# Server-side setup
from flask import Flask, jsonify, request
from data_analysis_service import DataAnalysisService
import logging

app = Flask(__name__)
logger = logging.getLogger(__name__)
DATA_ANALYSIS_AVAILABLE = True
data_analysis_service = DataAnalysisService()

def require_auth(f):
    def wrapper(*args, **kwargs):
        # Auth logic here
        return f(*args, **kwargs)
    return wrapper

def get_current_user():
    return 'user@example.com'

# Register the route
@app.route('/api/analysis-sessions/<session_id>/chat', methods=['POST'])
@require_auth
async def analysis_chat(session_id):
    # Function implementation here
    pass

# Client-side usage (JavaScript fetch example)
# fetch('/api/analysis-sessions/abc123/chat', {
#   method: 'POST',
#   headers: {'Content-Type': 'application/json'},
#   body: JSON.stringify({message: 'Show me the correlation between sales and revenue'})
# }).then(r => r.json()).then(data => console.log(data.response, data.plots))

Best Practices

  • Always check DATA_ANALYSIS_AVAILABLE flag before processing to ensure service availability
  • Verify session ownership (session.user_id != user_email) to prevent unauthorized access to other users' analysis sessions
  • Validate that user_message is not empty before processing to avoid unnecessary service calls
  • Use try-except blocks to catch and log errors from the data analysis service
  • Return appropriate HTTP status codes (503, 404, 400, 500) to help clients handle different error scenarios
  • The function is async, so ensure the Flask app is configured to handle async routes (Flask 2.0+)
  • Log errors with sufficient context (session_id, user_email) for debugging
  • Sanitize or validate user_message content if there are concerns about injection attacks
  • Consider rate limiting this endpoint to prevent abuse of computational resources
  • The session.to_dict() call should be implemented to avoid exposing sensitive session data

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function data_section_analysis_chat 91.7% similar

    Async Flask route handler that processes chat messages for data section analysis, managing conversation history and integrating with a statistical analysis service.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function get_analysis_session 77.5% similar

    Flask API endpoint that retrieves details of a specific data analysis session for an authenticated user, ensuring the user has access to the requested session.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function analyze_data 77.4% similar

    Flask route handler that initiates an asynchronous data analysis process based on user query, creating a background thread to perform the analysis and returning an analysis ID for progress tracking.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function export_analysis_content 75.0% similar

    Flask API endpoint that exports analysis session content for integration into documents, with authentication and authorization checks.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function create_data_section_analysis_session 74.8% similar

    Flask API endpoint that creates or retrieves an analysis session for a specific data section, ensuring user ownership and linking the session to the data section.

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