🔍 Code Extractor

function api_collections_v1

Maturity: 41

Flask API endpoint that retrieves and returns a list of available data collections from the chat engine instance.

File:
/tf/active/vicechatdev/vice_ai/app.py
Lines:
1246 - 1253
Complexity:
simple

Purpose

This endpoint provides a REST API interface to query available data collections that can be used for chat/RAG operations. It safely accesses the chat_engine's available_collections attribute and returns it as JSON, with error handling for cases where the chat engine is unavailable or the operation fails.

Source Code

def api_collections():
    """Get available data collections"""
    try:
        collections = getattr(chat_engine, 'available_collections', []) if chat_engine else []
        return jsonify({'collections': collections})
    except Exception as e:
        logger.error(f"Collections API error: {e}")
        return jsonify({'error': 'Failed to get collections'}), 500

Return Value

Returns a Flask JSON response. On success: {'collections': [list of collection names]} with HTTP 200. On error: {'error': 'Failed to get collections'} with HTTP 500. The collections list may be empty if no collections are available or if chat_engine is None.

Dependencies

  • flask
  • logging

Required Imports

from flask import jsonify
import logging

Usage Example

# Assuming Flask app setup with authentication
from flask import Flask, jsonify
import logging

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

# Mock chat_engine for example
class MockChatEngine:
    available_collections = ['collection1', 'collection2', 'collection3']

chat_engine = MockChatEngine()

# Mock auth decorator
def require_auth(f):
    return f

@app.route('/api/collections')
@require_auth
def api_collections():
    try:
        collections = getattr(chat_engine, 'available_collections', []) if chat_engine else []
        return jsonify({'collections': collections})
    except Exception as e:
        logger.error(f"Collections API error: {e}")
        return jsonify({'error': 'Failed to get collections'}), 500

# Client usage:
# GET request to http://your-server/api/collections
# Response: {"collections": ["collection1", "collection2", "collection3"]}

Best Practices

  • Always ensure the chat_engine is properly initialized before the Flask app starts accepting requests
  • The function safely handles None chat_engine by returning an empty collections list
  • Uses getattr with a default value to prevent AttributeError if available_collections doesn't exist
  • Implements proper error logging for debugging failed requests
  • Returns appropriate HTTP status codes (200 for success, 500 for server errors)
  • Requires authentication via decorator to protect access to collection information
  • Consider adding rate limiting for production environments
  • The global chat_engine variable should be thread-safe if the application handles concurrent requests

Related Versions

Other versions of this component:

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function api_collections 86.1% similar

    Flask API endpoint that retrieves and returns a list of available data collections from the RAG (Retrieval-Augmented Generation) engine.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function get_stats 70.5% similar

    Flask API endpoint that retrieves and returns statistics about a document collection from a RAG (Retrieval-Augmented Generation) system.

    From: /tf/active/vicechatdev/docchat/blueprint.py
  • function api_chat 65.1% similar

    Flask API endpoint that handles chat requests asynchronously, processing user queries through a RAG (Retrieval-Augmented Generation) engine with support for multiple modes, memory, web search, and custom configurations.

    From: /tf/active/vicechatdev/docchat/app.py
  • function api_templates_v2 65.0% similar

    Flask API endpoint that retrieves and returns a list of available instruction templates from the chat engine.

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