🔍 Code Extractor

function api_update_chat_config

Maturity: 48

Flask API endpoint that updates the configuration settings for a specific chat session by accepting JSON data, converting it to a ChatConfiguration object, and persisting the changes.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
2228 - 2248
Complexity:
moderate

Purpose

This endpoint allows clients to modify chat session settings such as model parameters, system prompts, or other configuration options for an existing chat session. It validates the session exists, processes the configuration data, and returns appropriate success or error responses. Used in web applications where users need to customize their chat experience mid-session.

Source Code

def api_update_chat_config(session_id):
    """Update chat session configuration"""
    try:
        data = request.get_json()
        config_data = data.get('config', {})
        
        logger.info(f"Updating chat config for session {session_id}: {config_data}")
        
        # Create ChatConfiguration object from the data
        config = ChatConfiguration.from_dict(config_data)
        
        # Update the chat session configuration
        success = chat_session_service.update_chat_config(session_id, config)
        
        if not success:
            return jsonify({'error': 'Chat session not found or update failed'}), 404
        
        return jsonify({'message': 'Chat configuration updated successfully'})
    except Exception as e:
        logger.error(f"Update chat config error: {e}")
        return jsonify({'error': 'Failed to update chat configuration'}), 500

Parameters

Name Type Default Kind
session_id - - positional_or_keyword

Parameter Details

session_id: String identifier for the chat session to update. Extracted from the URL path parameter. Must correspond to an existing chat session in the system, otherwise returns 404 error.

Return Value

Returns a Flask JSON response tuple. On success: (jsonify({'message': 'Chat configuration updated successfully'}), 200). On session not found or update failure: (jsonify({'error': 'Chat session not found or update failed'}), 404). On exception: (jsonify({'error': 'Failed to update chat configuration'}), 500).

Dependencies

  • flask
  • logging

Required Imports

from flask import request
from flask import jsonify
import logging
from models import ChatConfiguration
from services import ChatSessionService

Usage Example

# Client-side usage example (JavaScript fetch)
fetch('/api/chat-sessions/abc123/config', {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({
    config: {
      model: 'gpt-4',
      temperature: 0.7,
      max_tokens: 2000,
      system_prompt: 'You are a helpful assistant'
    }
  })
})
.then(response => response.json())
.then(data => console.log(data.message))
.catch(error => console.error('Error:', error));

# Server-side setup
from flask import Flask, request, jsonify
from models import ChatConfiguration
from services import ChatSessionService
import logging

app = Flask(__name__)
logger = logging.getLogger(__name__)
chat_session_service = ChatSessionService()

@app.route('/api/chat-sessions/<session_id>/config', methods=['POST'])
def api_update_chat_config(session_id):
    # Function implementation as provided

Best Practices

  • Always validate session_id exists before attempting updates to avoid unnecessary processing
  • Ensure ChatConfiguration.from_dict() properly validates all configuration fields to prevent invalid data persistence
  • Consider adding authentication/authorization checks to prevent unauthorized config modifications
  • Log configuration changes for audit trails and debugging purposes
  • Use transaction management in chat_session_service.update_chat_config() to ensure atomic updates
  • Consider rate limiting this endpoint to prevent abuse
  • Validate that the config dictionary contains only allowed fields before processing
  • Return more specific error messages in production for better client-side error handling
  • Consider adding request validation middleware to check JSON structure before processing

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_update_system_config 71.8% similar

    Flask API endpoint that allows administrators to update system configuration settings including system role, expertise, domain context, custom instructions, output style, and query languages, with persistence to disk.

    From: /tf/active/vicechatdev/docchat/app.py
  • function api_create_chat_session 71.4% 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_get_chat_session_v1 70.7% 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
  • function api_clear_chat_session 69.5% similar

    Flask API endpoint that clears the chat history for a specific chat session identified by session_id.

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