🔍 Code Extractor

function api_create_chat_session_v1

Maturity: 46

Flask API endpoint that creates a new chat session for a document section or retrieves an existing one if already present.

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
979 - 1010
Complexity:
moderate

Purpose

This endpoint manages chat sessions associated with document sections. It verifies user authentication and authorization, checks if a chat session already exists for the specified section, and either returns the existing session or creates a new one. The function ensures that only the document author can create chat sessions for their sections.

Source Code

def api_create_chat_session(doc_id, section_id):
    """Create or get chat session for a section"""
    try:
        document = get_document(doc_id)
        if not document:
            return jsonify({'error': 'Document not found'}), 404
        
        if document.author != get_user_id():
            return jsonify({'error': 'Access denied'}), 403
        
        section = document.get_section(section_id)
        if not section:
            return jsonify({'error': 'Section not found'}), 404
        
        # Check if section already has a chat session
        if section.chat_session_id:
            chat_session = get_chat_session(section.chat_session_id)
            if chat_session:
                return jsonify({'chat_session': chat_session.to_dict()})
        
        # Create new chat session
        chat_session = create_chat_session(section_id, doc_id)
        section.chat_session_id = chat_session.id
        save_document(document)
        
        return jsonify({
            'chat_session': chat_session.to_dict(),
            'message': 'Chat session created successfully'
        })
    except Exception as e:
        logger.error(f"Create chat session error: {e}")
        return jsonify({'error': 'Failed to create chat session'}), 500

Parameters

Name Type Default Kind
doc_id - - positional_or_keyword
section_id - - positional_or_keyword

Parameter Details

doc_id: String identifier for the document. Used to retrieve and verify the document from storage. Must correspond to an existing document in the system.

section_id: String identifier for the specific section within the document. Used to locate the section and associate it with a chat session. Must correspond to an existing section within the specified document.

Return Value

Returns a Flask JSON response tuple. On success (200): JSON object containing 'chat_session' (dictionary representation of the chat session) and optionally 'message' field. On error: JSON object with 'error' field and appropriate HTTP status code (404 for not found, 403 for access denied, 500 for server errors).

Dependencies

  • flask
  • logging

Required Imports

from flask import jsonify

Usage Example

# Example API call using requests library
import requests

# Assuming authentication is handled via session cookies
session = requests.Session()
# Login first to establish authenticated session
session.post('https://api.example.com/login', json={'username': 'user', 'password': 'pass'})

# Create or get chat session for a section
response = session.post(
    'https://api.example.com/api/documents/doc123/sections/section456/chat'
)

if response.status_code == 200:
    data = response.json()
    chat_session = data['chat_session']
    print(f"Chat session ID: {chat_session['id']}")
    if 'message' in data:
        print(f"Message: {data['message']}")
elif response.status_code == 404:
    print(f"Error: {response.json()['error']}")
elif response.status_code == 403:
    print("Access denied: You are not the document author")
else:
    print(f"Server error: {response.json()['error']}")

Best Practices

  • Always verify user authentication before accessing this endpoint (handled by require_auth decorator)
  • Ensure proper error handling for all database/storage operations
  • The function implements idempotent behavior by returning existing chat sessions instead of creating duplicates
  • Authorization is enforced by checking document.author against current user ID
  • All errors are logged for debugging purposes while returning user-friendly error messages
  • The function follows RESTful conventions with appropriate HTTP status codes
  • Transaction safety should be considered when saving document changes to prevent race conditions
  • Consider implementing rate limiting to prevent abuse of chat session creation

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_create_chat_session 95.3% similar

    Flask API endpoint that creates or retrieves a chat session associated with a specific document section, ensuring proper validation and linking between documents, sections, and chat sessions.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function api_create_section 79.3% similar

    Flask API endpoint that creates a new section within a specified document, handling section positioning, type, level, title, and content with proper authentication and authorization checks.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function api_get_chat_session 79.0% 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 create_chat_session 77.9% similar

    Creates a new chat session for a specific document section by generating a unique session ID, initializing a ChatSession object, storing it in application state with thread-safe locking, and persisting it to file.

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