function get_stats
Flask API endpoint that retrieves and returns statistics about a document collection from a RAG (Retrieval-Augmented Generation) system.
/tf/active/vicechatdev/docchat/blueprint.py
275 - 283
simple
Purpose
This endpoint serves as a REST API route to fetch collection statistics from the DocChatRAG system. It's designed to provide authenticated users with metrics about the document collection, such as document counts, indexing status, or other relevant statistics. The endpoint handles errors gracefully and returns appropriate HTTP status codes.
Source Code
def get_stats():
"""Get collection statistics"""
try:
rag = DocChatRAG()
stats = rag.get_collection_stats()
return jsonify(stats)
except Exception as e:
logger.error(f"Error getting stats: {e}")
return jsonify({'error': str(e)}), 500
Return Value
Returns a Flask JSON response object. On success (HTTP 200), returns a JSON object containing collection statistics as defined by the DocChatRAG.get_collection_stats() method. On error (HTTP 500), returns a JSON object with an 'error' key containing the error message string.
Dependencies
flaskflask_loginlogging
Required Imports
from flask import jsonify
from flask_login import login_required
import logging
from rag_engine import DocChatRAG
Usage Example
# Assuming Flask app is set up with authentication
# Client-side usage (JavaScript fetch example):
fetch('/api/stats', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include' // Include session cookies
})
.then(response => response.json())
.then(data => {
console.log('Collection stats:', data);
})
.catch(error => {
console.error('Error fetching stats:', error);
});
# Server-side testing with Flask test client:
with app.test_client() as client:
# Login first (assuming login endpoint exists)
client.post('/login', data={'username': 'user', 'password': 'pass'})
# Get stats
response = client.get('/api/stats')
stats = response.get_json()
print(stats)
Best Practices
- Always ensure user is authenticated before calling this endpoint (handled by @login_required decorator)
- The endpoint returns 500 status code on errors, which is appropriate for server-side failures
- Error messages are logged before being returned to the client for debugging purposes
- The function creates a new DocChatRAG instance on each request - consider implementing connection pooling or singleton pattern if performance becomes an issue
- Ensure proper exception handling in the DocChatRAG.get_collection_stats() method to provide meaningful error messages
- Consider adding rate limiting to prevent abuse of this endpoint
- Consider caching statistics if they don't change frequently to improve performance
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function api_collections 76.6% similar
-
function api_collections_v1 74.6% similar
-
function index_v2 71.5% similar
-
function api_collections_v1 70.5% similar
-
function api_documents 68.6% similar