🔍 Code Extractor

function create_analysis_session

Maturity: 51

Creates a new data analysis session for a text section, verifying ownership and section type before linking the session to the section.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
5921 - 5960
Complexity:
moderate

Purpose

This Flask route handler creates a data analysis session for a specific text section. It validates that the data analysis service is available, verifies the user owns the text section, ensures the section is of type 'data_analysis', creates the analysis session through the data_analysis_service, and links the session ID back to the text section. This enables users to perform data analysis operations on their text sections.

Source Code

def create_analysis_session(section_id):
    """Create a new data analysis session for a text section"""
    if not DATA_ANALYSIS_AVAILABLE:
        return jsonify({'error': 'Data analysis service not available'}), 503
    
    user_email = get_current_user()
    data = request.get_json()
    
    # Get the text section to verify ownership
    text_section = text_section_service.get_text_section(section_id)
    if not text_section or text_section.owner != user_email:
        return jsonify({'error': 'Text section not found or access denied'}), 404
    
    # Check if section is data analysis type
    if text_section.section_type.value != 'data_analysis':
        return jsonify({'error': 'Section must be of type data_analysis'}), 400
    
    try:
        title = data.get('title', f'Analysis for {text_section.title}')
        
        # Create analysis session
        session = data_analysis_service.create_analysis_session(
            section_id=section_id,
            document_id=data.get('document_id', ''),
            user_id=user_email,
            title=title
        )
        
        # Link the session to the text section
        text_section.analysis_session_id = session.session_id
        text_section_service.update_text_section(text_section)
        
        return jsonify({
            'success': True,
            'session': session.to_dict()
        })
        
    except Exception as e:
        logger.error(f"Error creating analysis session: {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 text section. Used to retrieve and verify the text section from the database. Must correspond to an existing text section owned by the authenticated user and of type 'data_analysis'.

Return Value

Returns a Flask JSON response tuple. On success (200): {'success': True, 'session': <session_dict>} containing the created session details. On error: {'error': <error_message>} with status codes 503 (service unavailable), 404 (section not found/access denied), 400 (invalid section type), or 500 (internal error).

Dependencies

  • flask
  • logging
  • typing

Required Imports

from flask import jsonify, request
import logging

Usage Example

# Example API call to this endpoint:
# POST /api/text-sections/abc123/analysis
# Headers: Authorization: Bearer <token>
# Body: {"title": "My Analysis", "document_id": "doc456"}

import requests

section_id = 'abc123'
url = f'http://localhost:5000/api/text-sections/{section_id}/analysis'
headers = {'Authorization': 'Bearer YOUR_AUTH_TOKEN'}
payload = {
    'title': 'Sales Data Analysis',
    'document_id': 'doc456'
}

response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200:
    result = response.json()
    session_id = result['session']['session_id']
    print(f'Created analysis session: {session_id}')
else:
    print(f'Error: {response.json()["error"]}')

Best Practices

  • Always check DATA_ANALYSIS_AVAILABLE before attempting to create sessions to avoid service unavailability errors
  • Ensure the text section exists and belongs to the authenticated user before creating analysis sessions
  • Verify the section type is 'data_analysis' to prevent creating sessions for incompatible section types
  • Handle all exceptions gracefully and return appropriate HTTP status codes
  • Use the require_auth decorator to ensure only authenticated users can access this endpoint
  • The function automatically generates a default title if none is provided in the request
  • The analysis session is automatically linked back to the text section via analysis_session_id
  • Log errors with sufficient context for debugging production issues
  • Consider implementing rate limiting for session creation to prevent abuse
  • Validate that document_id exists if provided in the request payload

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function create_data_section_analysis_session 88.4% 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
  • function create_new_session 77.0% similar

    Flask route handler that creates a new analysis session with an optional title and description, returning a unique session ID.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function get_analysis_session 76.7% 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 data_section_analysis_chat 72.4% 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 analysis_chat 72.4% similar

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

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