function api_create_chat_session
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.
/tf/active/vicechatdev/vice_ai/new_app.py
1825 - 1890
moderate
Purpose
This endpoint manages chat sessions for document sections in a document management system. It validates that the requested section belongs to the specified document, checks for existing chat sessions (either via section's chat_session_id or by querying the database), and creates a new chat session only if none exists. It handles edge cases like orphaned chat_session_id references and ensures data consistency by updating section records with the correct chat session ID.
Source Code
def api_create_chat_session(doc_id, section_id):
"""Create or get chat session for a section"""
try:
logger.info(f"🚀 DEBUG: Chat session request for doc {doc_id}, section {section_id}")
# Get the document and section
document = document_service.get_document(doc_id)
if not document:
logger.error(f"❌ DEBUG: Document not found: {doc_id}")
return jsonify({'error': 'Document not found'}), 404
# Get the section
section = text_section_service.get_text_section(section_id)
if not section:
logger.error(f"❌ DEBUG: Section not found: {section_id}")
return jsonify({'error': 'Section not found'}), 404
logger.info(f"🔍 DEBUG: Section found with chat_session_id: {section.chat_session_id} (type: {type(section.chat_session_id)})")
# Verify the section belongs to this document by checking document's sections
document_sections = document.sections or []
section_in_document = any(ds.section_id == section_id for ds in document_sections)
if not section_in_document:
logger.error(f"❌ DEBUG: Section {section_id} not found in document {doc_id}")
return jsonify({'error': 'Section not found in this document'}), 404
# Check if section already has a chat session
if section.chat_session_id:
logger.info(f"🔍 DEBUG: Section has existing chat_session_id: {section.chat_session_id}")
chat_session = chat_session_service.get_chat_session(section.chat_session_id)
if chat_session:
logger.info(f"✅ DEBUG: Existing chat session found and returned")
return jsonify({'chat_session': chat_session.to_dict()})
else:
logger.warning(f"⚠️ DEBUG: chat_session_id exists but session not found in DB")
# If no valid chat session found via section.chat_session_id, check by section_id
logger.info(f"🔍 DEBUG: Checking for existing chat session by section_id")
existing_chat_session = chat_session_service.get_chat_session_by_section(section_id)
if existing_chat_session:
logger.info(f"✅ DEBUG: Found existing chat session by section_id: {existing_chat_session.id}")
# Update the section to point to this existing session
success = text_section_service.update_chat_session_id(section_id, existing_chat_session.id)
if success:
logger.info(f"🔄 DEBUG: Updated section to point to existing chat session")
return jsonify({'chat_session': existing_chat_session.to_dict()})
# Create new chat session only if none exists
logger.info(f"🆕 DEBUG: Creating new chat session")
chat_session = chat_session_service.create_chat_session(section_id, doc_id)
# Update section with chat session ID
logger.info(f"💾 DEBUG: Updating section {section_id} with chat_session_id {chat_session.id}")
success = text_section_service.update_chat_session_id(section_id, chat_session.id)
if not success:
logger.warning(f"⚠️ DEBUG: Failed to update section with chat session ID: {section_id}")
else:
logger.info(f"✅ DEBUG: Successfully updated section with chat session ID")
return jsonify({
'chat_session': chat_session.to_dict(),
'message': 'Chat session created successfully'
})
except Exception as e:
logger.error(f"❌ DEBUG: 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: The unique identifier of the document. Used to validate that the section belongs to this document and to associate the chat session with the document context.
section_id: The unique identifier of the text section within the document. Used to retrieve the section, check for existing chat sessions, and create new chat sessions linked to this specific section.
Return Value
Returns a JSON response with status code. On success (200): {'chat_session': <chat_session_dict>} for existing sessions or {'chat_session': <chat_session_dict>, 'message': 'Chat session created successfully'} for new sessions. On error: {'error': <error_message>} with status codes 404 (document/section not found or section not in document) or 500 (internal server error).
Dependencies
flasklogging
Required Imports
from flask import jsonify
import logging
Usage Example
# This is a Flask route handler, typically called via HTTP request
# Example HTTP request:
# POST /api/documents/doc123/sections/section456/chat
# In a Flask application context:
from flask import Flask, jsonify
import logging
app = Flask(__name__)
logger = logging.getLogger(__name__)
# Assuming services are initialized:
# document_service = DocumentService()
# text_section_service = TextSectionService()
# chat_session_service = ChatSessionService()
@app.route('/api/documents/<doc_id>/sections/<section_id>/chat', methods=['POST'])
def api_create_chat_session(doc_id, section_id):
# Function implementation here
pass
# Client-side usage (e.g., JavaScript fetch):
# fetch('/api/documents/doc123/sections/section456/chat', {
# method: 'POST',
# headers: {'Content-Type': 'application/json'}
# })
# .then(response => response.json())
# .then(data => console.log(data.chat_session));
Best Practices
- This endpoint is idempotent - calling it multiple times with the same parameters will return the same chat session without creating duplicates
- Always validate that the section belongs to the document before creating or returning a chat session to prevent unauthorized access
- The function handles orphaned chat_session_id references by checking if the referenced session actually exists in the database
- Extensive logging is included for debugging - consider adjusting log levels for production use
- The function attempts to repair inconsistent state by updating section records when a chat session is found by section_id but not linked in the section record
- Error responses include appropriate HTTP status codes (404 for not found, 500 for server errors)
- Ensure proper transaction handling in the service layer to maintain data consistency when creating sessions and updating section records
- The function assumes service methods handle their own error cases and database transactions
- Consider implementing authentication/authorization checks before allowing chat session creation
- The to_dict() method on ChatSession should sanitize sensitive data before returning to client
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function api_create_chat_session_v1 95.3% similar
-
function api_get_chat_session 78.8% similar
-
function create_chat_session 78.3% similar
-
function api_create_section 76.8% similar
-
function api_get_chat_session_v1 75.9% similar