function data_section_analysis_chat
Async Flask route handler that processes chat messages for data section analysis, managing conversation history and integrating with a statistical analysis service.
/tf/active/vicechatdev/vice_ai/new_app.py
4531 - 4580
complex
Purpose
This endpoint enables interactive chat-based data analysis for specific data sections. It verifies user ownership, validates the analysis session, processes queries through a data analysis service (statistical agent), maintains conversation history, and returns analysis responses. It's designed for real-time statistical consultation and data exploration within a document management system.
Source Code
async def data_section_analysis_chat(section_id):
"""Process analysis chat message for data section"""
if not DATA_ANALYSIS_AVAILABLE:
return jsonify({'error': 'Data analysis service not available'}), 503
user_email = get_current_user()
# Verify ownership
data_section = data_section_service.get_data_section(section_id)
if not data_section or data_section.owner != user_email:
return jsonify({'error': 'Data section not found or access denied'}), 404
if not data_section.analysis_session_id:
return jsonify({'error': 'No analysis session found'}), 400
data = request.get_json()
message = data.get('message', '').strip()
if not message:
return jsonify({'error': 'Message is required'}), 400
try:
# Get the analysis session
session = data_analysis_service.get_analysis_session(data_section.analysis_session_id)
if not session or session.user_id != user_email:
return jsonify({'error': 'Session not found or access denied'}), 404
# Process the message with statistical agent
response = await data_analysis_service.process_query(
session_id=data_section.analysis_session_id,
query=message
)
# Update conversation history in data section
data_section_refresh = data_section_service.get_data_section(section_id)
conversation = data_section_refresh.conversation_history or []
if isinstance(conversation, str):
conversation = json.loads(conversation)
conversation.append({'role': 'user', 'content': message})
conversation.append({'role': 'assistant', 'content': response.get('response', '')})
data_section_refresh.conversation_history = json.dumps(conversation)
data_section_service.update_data_section(data_section_refresh)
return jsonify(response)
except Exception as e:
logger.error(f"Error in analysis chat: {e}")
return jsonify({'error': str(e)}), 500
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
section_id |
- | - | positional_or_keyword |
Parameter Details
section_id: String identifier for the data section being analyzed. Used to retrieve the specific data section from the database and verify ownership. Must correspond to an existing DataSection record owned by the authenticated user.
Return Value
Returns a Flask JSON response. On success (200): JSON object containing the analysis response from the data analysis service, typically including 'response' field with the assistant's answer. On error: JSON object with 'error' field and appropriate HTTP status code (400 for missing message/session, 404 for not found/access denied, 503 for service unavailable, 500 for processing errors).
Dependencies
flaskjsonlogging
Required Imports
from flask import jsonify
from flask import request
import json
import logging
Conditional/Optional Imports
These imports are only needed under specific conditions:
from data_analysis_service import DataAnalysisService
Condition: Required for data analysis functionality; must be available or DATA_ANALYSIS_AVAILABLE flag should be False
Required (conditional)from services import DataSectionService
Condition: Required for data section operations
Required (conditional)from auth.azure_auth import get_current_user (or similar auth module)
Condition: Required for authentication; used by require_auth decorator and get_current_user function
Required (conditional)Usage Example
# Client-side usage example (JavaScript fetch)
const sectionId = 'section-123';
const response = await fetch(`/api/data-sections/${sectionId}/analysis/chat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer <token>'
},
body: JSON.stringify({
message: 'What is the mean of column A?'
})
});
const result = await response.json();
if (response.ok) {
console.log('Analysis response:', result.response);
} else {
console.error('Error:', result.error);
}
# Server-side setup example
from flask import Flask
from data_analysis_service import DataAnalysisService
from services import DataSectionService
from auth.azure_auth import require_auth, get_current_user
app = Flask(__name__)
DATA_ANALYSIS_AVAILABLE = True
data_section_service = DataSectionService()
data_analysis_service = DataAnalysisService()
logger = logging.getLogger(__name__)
# Function is then registered as route handler
Best Practices
- Always verify user ownership before processing requests to prevent unauthorized access
- Validate that analysis session exists and belongs to the user before processing queries
- Handle conversation history as JSON, checking if it's already parsed or needs parsing
- Refresh data section from database after async operations to ensure latest state
- Use try-except blocks to catch and log errors during analysis processing
- Return appropriate HTTP status codes (400, 404, 500, 503) for different error scenarios
- Strip and validate user input (message) before processing
- Maintain conversation history in chronological order with role-based messages
- Check DATA_ANALYSIS_AVAILABLE flag early to fail fast if service is unavailable
- Use async/await properly since this is an async function
- Log errors with sufficient context for debugging
- Ensure database transactions are properly committed when updating conversation history
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function analysis_chat 91.7% similar
-
function create_data_section_analysis_session 76.1% similar
-
function analyze_data 75.2% similar
-
function save_data_section_analysis 74.9% similar
-
function create_analysis_session 72.4% similar