function api_add_reference_document
Flask API endpoint that accepts reference document text via POST request and stores it in the user's session for use as context in subsequent operations.
/tf/active/vicechatdev/vice_ai/new_app.py
2479 - 2515
simple
Purpose
This endpoint allows users to add reference documents (text content) to their session context without uploading physical files. It generates a unique document ID, stores the reference text in the session's uploaded_documents dictionary, and returns confirmation. This is useful for providing contextual information to AI models or other processing functions that need access to reference materials during a user's session.
Source Code
def api_add_reference_document():
"""Add a reference document to context"""
try:
data = request.get_json()
reference_text = data.get('text', '')
title = data.get('title', 'Reference Document')
if not reference_text:
return jsonify({'error': 'No reference text provided'}), 400
# Generate a document ID
import uuid
document_id = str(uuid.uuid4())
# Store as uploaded document in session
if 'uploaded_documents' not in session:
session['uploaded_documents'] = {}
session['uploaded_documents'][document_id] = {
'id': document_id,
'filename': f"{title}.txt",
'file_path': None, # No physical file for references
'text_content': reference_text,
'size': len(reference_text),
'uploaded_at': datetime.now().isoformat(),
'is_reference': True
}
return jsonify({
'document_id': document_id,
'message': 'Reference added to context',
'title': title
})
except Exception as e:
logger.error(f"Add reference error: {e}")
return jsonify({'error': 'Failed to add reference'}), 500
Return Value
Returns a JSON response with status code. On success (200): {'document_id': string (UUID), 'message': 'Reference added to context', 'title': string}. On error (400): {'error': 'No reference text provided'} if text is empty. On exception (500): {'error': 'Failed to add reference'}
Dependencies
flaskuuiddatetimelogging
Required Imports
from flask import Flask, request, jsonify, session
import uuid
from datetime import datetime
import logging
Conditional/Optional Imports
These imports are only needed under specific conditions:
import uuid
Condition: imported inside the function for generating document IDs
Required (conditional)Usage Example
# Client-side usage (JavaScript fetch example)
fetch('/api/add-reference-document', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_AUTH_TOKEN'
},
body: JSON.stringify({
text: 'This is my reference document content with important information.',
title: 'Project Guidelines'
})
})
.then(response => response.json())
.then(data => {
console.log('Document ID:', data.document_id);
console.log('Message:', data.message);
})
.catch(error => console.error('Error:', error));
# Python requests example
import requests
response = requests.post(
'http://localhost:5000/api/add-reference-document',
json={
'text': 'Reference content here',
'title': 'My Reference'
},
headers={'Authorization': 'Bearer YOUR_AUTH_TOKEN'}
)
result = response.json()
print(f"Document ID: {result['document_id']}")
Best Practices
- Always validate that reference_text is not empty before processing
- The function stores documents in session, which has size limitations - be mindful of large reference texts
- Session data is temporary and will be lost when the session expires or is cleared
- The document_id is a UUID4 string that should be stored by the client for future reference
- No physical file is created (file_path is None), all content is stored in memory/session
- The is_reference flag is set to True to distinguish these from uploaded files
- Ensure proper authentication is in place via the require_auth decorator
- Consider implementing size limits on reference_text to prevent session overflow
- The uploaded_at timestamp uses ISO format for consistency
- Error handling catches all exceptions but logs them for debugging
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function api_get_reference_document 75.1% similar
-
function add_existing_section_to_document 67.9% similar
-
function api_get_extensive_reference 67.7% similar
-
function api_chat_upload_document 66.7% similar
-
function add_data_section_to_document 66.6% similar