Chat Log Embeddings Backfill Documentation
Overview
The embeddings backfill route (/api/backfill-embeddings) is designed to generate embeddings for all existing chat logs that don’t have embeddings yet. This enables the memory functionality for all existing users immediately, allowing the AI to search through past conversations for context.
Purpose
When the chat memory feature was initially deployed, only new chat logs received embeddings. This backfill route ensures that:- All historical chat logs have embeddings
- Users can immediately benefit from the memory search functionality
- The AI can reference past conversations for better context
Technical Details
Endpoint
- URL:
/api/backfill-embeddings - Methods:
POST- Run the backfill processGET- Check current status and statistics
Security
- Bearer authentication (required):
Authorization: Bearer $INTERNAL_API_TOKENon both GET and POST. Same env var and shared guard (lib/internal-auth.ts) as the other internal Lambda-only endpoints. Missing/wrong token → 401. - Environment Restriction: POST additionally 403s when
NODE_ENV === 'production'as defense-in-depth on top of the Bearer gate. - Database access: Uses Supabase service role internally, so RLS is bypassed — this is why the Bearer gate is mandatory.
Configuration
- Batch Size: 50 records per batch
- Rate Limiting: 250ms delay between batches
- Max Retries: 3 attempts per embedding generation
- Max Duration: 5 minutes (300 seconds)
- Embedding Model: OpenAI’s
text-embedding-3-small
Usage Instructions
1. Check Current Status
First, check how many chat logs need embeddings:- Number of chat logs without embeddings
- Number of chat logs with embeddings
- Total chat logs in the system
- Current configuration settings
2. Run the Backfill Process
Option A: Using the Test Script (Recommended)
- Check the current status
- Verify the environment is development
- Run the backfill if needed
- Display progress and statistics
- Show final results
Option B: Direct API Call
3. Monitor Progress
The backfill process provides detailed console output:- Progress percentage
- Number of records processed
- Success/failure counts
- Time estimates
- Any errors encountered
Response Format
Success Response
Error Response
Processing Strategy
- Batch Processing: Processes 50 records at a time to manage memory and API limits
- Skip Existing: Only processes rows where
embedding IS NULL - Error Recovery: Continues processing even if individual records fail
- Rate Limiting: 250ms delay between batches to avoid OpenAI rate limits
- Retry Logic: 3 attempts per record with exponential backoff
- Progress Tracking: Logs progress every 10 successful embeddings
Error Handling
The route handles several types of errors:- Environment errors: Blocks execution in production
- Database errors: Returns detailed error messages
- OpenAI API errors: Retries with backoff
- Rate limit errors: Automatic retry with delay
- Individual record failures: Logs and continues with next record
Performance Considerations
- Processing Time: ~0.3 seconds per record on average
- API Usage: One OpenAI embedding call per chat log
- Memory: Processes in batches to avoid memory issues
- Database Load: Minimal due to batch processing
Troubleshooting
Common Issues
-
401 Unauthorizedon the request- Set
INTERNAL_API_TOKENin.env.localand re-export it into your shell before running the script/curl. - Verify the value matches what Vercel/AWS Secrets Manager has for the same variable (they must agree).
- Set
-
“Endpoint not available” error
- Ensure
NODE_ENVis set todevelopment(POST only; GET returns metadata regardless). - Check environment variables.
- Ensure
-
Rate limit errors
- Increase
RATE_LIMIT_DELAYin the route - Reduce
BATCH_SIZE
- Increase
-
Timeout errors
- Increase
maxDurationin the route - Process in smaller batches
- Increase
-
No records to process
- All chat logs already have embeddings
- Check the database directly to verify
Verification
After running the backfill, verify success by:- Checking the GET endpoint for statistics
- Querying the database:
- Testing the chat memory functionality in the application
Best Practices
- Run during low-traffic periods to minimize impact on users
- Monitor OpenAI API usage to avoid unexpected costs
- Test on a subset first by modifying the query limit
- Keep logs of the backfill process for debugging
- Verify embeddings by testing chat memory after completion
Integration with Chat System
Once embeddings are generated:- The
searchChatHistorytool inapp/api/chat/chat-history-search-tool.tscan find relevant past conversations - The AI uses these embeddings for semantic search
- Users get more contextual and personalized responses
Future Improvements
Potential enhancements for the backfill process:- Add support for partial backfills (date ranges, specific users)
- Implement parallel processing for faster completion
- Add a web UI for monitoring progress
- Support for different embedding models
- Automatic scheduling for periodic backfills