function api_get_reference_block
API endpoint that retrieves a reference block from the most recent chat response by block number and stores it as a reference document in the user's session.
/tf/active/vicechatdev/vice_ai/app.py
1527 - 1578
moderate
Purpose
This Flask route handler fetches a specific reference block from the chat engine's response history, extracts its content and metadata, stores it as a reference document associated with the authenticated user's session, and returns information about the stored block. It enables users to save and reference specific blocks of information from chat responses for later use in conversations.
Source Code
def api_get_reference_block(block_number):
"""Retrieve a reference block from the most recent chat response by block number"""
try:
if not chat_engine:
return jsonify({'error': 'Chat engine not available'}), 500
logger.info(f"🔍 Reference block request for block: {block_number}")
# Retrieve block from chat engine
block_info = chat_engine.get_block_by_number(block_number)
if not block_info:
logger.warning(f"⚠️ Reference block not found: {block_number}")
return jsonify({'error': 'Reference block not found'}), 404
# Extract content and metadata from block
content = block_info.get('content', '')
title = block_info.get('title', f'Block {block_number}')
source = block_info.get('source', 'Unknown Source')
# Store the block as a reference document in user session for use in chat
user_email = session['user'].get('email', 'unknown')
reference_doc_id = f"ref_block_{block_number}_{int(time.time())}"
# Create metadata for the reference block
metadata = {
'original_filename': f"{title}.txt",
'source': f'Reference Block {block_number}',
'block_number': block_number,
'file_type': 'reference_block',
'size': len(content),
'source_info': source
}
# Store in user document storage
store_document(user_email, reference_doc_id, None, content, metadata)
logger.info(f"✅ Reference block stored: {title} ({len(content)} chars)")
return jsonify({
'document_id': reference_doc_id,
'block_number': block_number,
'name': title,
'type': 'reference_block',
'content_length': len(content),
'source': source,
'preview': content[:500] + '...' if len(content) > 500 else content
})
except Exception as e:
logger.error(f"❌ Error retrieving reference block {block_number}: {e}")
return jsonify({'error': 'Failed to retrieve reference block'}), 500
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
block_number |
- | - | positional_or_keyword |
Parameter Details
block_number: Integer representing the unique identifier of the reference block to retrieve from the chat engine. This corresponds to a specific block in the most recent chat response. Must be a valid block number that exists in the chat engine's current context.
Return Value
Returns a Flask JSON response tuple. On success (200): JSON object containing 'document_id' (unique identifier for stored document), 'block_number' (the requested block number), 'name' (block title), 'type' (always 'reference_block'), 'content_length' (character count), 'source' (origin information), and 'preview' (first 500 characters or full content if shorter). On error: JSON object with 'error' message and HTTP status code 404 (block not found), 500 (chat engine unavailable or internal error).
Dependencies
flaskloggingtime
Required Imports
from flask import jsonify
from flask import session
import logging
import time
Usage Example
# Example Flask application setup
from flask import Flask, session, jsonify
import logging
import time
app = Flask(__name__)
app.secret_key = 'your-secret-key'
# Mock dependencies
logger = logging.getLogger(__name__)
class MockChatEngine:
def get_block_by_number(self, block_number):
if block_number == 1:
return {
'content': 'This is the content of reference block 1',
'title': 'Important Information',
'source': 'Chat Response #42'
}
return None
chat_engine = MockChatEngine()
def store_document(user_email, doc_id, file_obj, content, metadata):
# Store document logic
pass
def require_auth(f):
def wrapper(*args, **kwargs):
return f(*args, **kwargs)
return wrapper
@app.route('/api/reference-block/<int:block_number>', methods=['GET'])
@require_auth
def api_get_reference_block(block_number):
# Function implementation here
pass
# Client usage example:
# GET /api/reference-block/1
# Response: {
# 'document_id': 'ref_block_1_1234567890',
# 'block_number': 1,
# 'name': 'Important Information',
# 'type': 'reference_block',
# 'content_length': 42,
# 'source': 'Chat Response #42',
# 'preview': 'This is the content of reference block 1'
# }
Best Practices
- Ensure the chat_engine is properly initialized before the application starts accepting requests
- The function requires an authenticated user session with an 'email' field - verify authentication middleware is properly configured
- The store_document function must be implemented to handle document persistence for the user
- Block numbers should be validated by the chat engine's get_block_by_number method
- Consider implementing rate limiting to prevent abuse of the reference block storage
- The preview truncation at 500 characters is hardcoded - consider making this configurable
- Error logging includes emoji markers for visual distinction - ensure logging output supports Unicode
- The document_id uses timestamp-based uniqueness which may have collision risks under high concurrency
- Session data should be properly secured and validated to prevent unauthorized access
- Consider implementing cleanup logic for old reference blocks to prevent storage bloat
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function api_get_extensive_reference 81.8% similar
-
function api_get_reference_document 70.5% similar
-
function api_add_reference_document 65.8% similar
-
function api_send_chat_message 63.3% similar
-
function api_get_chat_session 61.4% similar