π API Key Management
π‘ Enter your API key once to enable all endpoint calls below. The key is stored in your browser session for demonstration purposes.
Clear Session API Key
Remove API key from server-side session.
-
DELETE /api/session/api-key Removes the API key from the current session.
Users
Manage user records and view onboarding progress.
-
GET /api/users List all users with metadata.
-
POST /api/users Create a new user by email.
-
POST /api/users/anonymous Create an anonymous user with a randomly generated email (user_MMDDHHMMSS@xxxx.com).
Interactive demo: pending questions by category
Filter unanswered survey questions for a respondent by supplying the target category. The API trims, lowercases, and replaces spaces with underscores before querying.
Enter a respondent ID and category to preview pending questions that still require answers.
Survey questions
Explore the required demographic baseline questions and user progress.
-
GET /api/survey-questions/baseline-questions Retrieve all baseline questions and options.
-
GET /api/survey-questions/pending?user_id=<id> Return unanswered question IDs grouped into baseline, all respondents, and specific respondents.
-
GET /api/survey-questions/pending/by-category?user_id=<id>&category=<label> Retrieve unanswered questions for a respondent limited to the normalized category.
-
GET /api/survey-questions/next?user_id=<id> Get the next prioritized unanswered question for a user (specific β baseline β general).
-
GET /api/survey-questions/<question_id> Retrieve the full question payload for a single question.
-
POST /api/survey-questions/lookup Submit a JSON body with
{ "question_id": <int> }to retrieve details.
Interactive demo: generate question session
Create a curated set of survey questions for a specific user. Generate a full session drawing from selected categories.
Fill out the form and click "Generate session" to create a question set.
Interactive demo: next question in category
Retrieve the next unanswered question for a user within a specific category. Perfect for category-focused survey flows.
Enter user ID and category, then click "Get next question".
Prediction prompts
Generate LLM-backed response rankings for outstanding survey questions.
Enter a respondent ID to load unanswered questions from /api/survey-questions/pending and run Template 1 predictions directly from this page.
Pending questions will appear here after loading a respondent.
Panel run predictions
POST /api/panel-run/predictSend a single survey question to multiple users in one call. The demo shows ranked answers per user plus an aggregate summary so you can compare cohorts in real time.
Batch predictions (Template-1)
POST /api/prediction-prompts/template-1/batchStart an asynchronous batch job to score multiple pending baseline questions in one request. The demo polls the batch status endpoint to surface progress, per-question outcomes, and any validation errors returned by the service.
Job progress
Batch results
Prediction Provider Health
Use this interactive panel to issue a fetch('/api/prediction-prompts/provider-health') request with the API key set above.
Refresh Health Status performs an authenticated GET call and renders each provider card, while Call API opens the raw JSON response in a new tab for quick inspection.
Enable auto-refresh when you want the UI to poll every 30 seconds during front-end development or demos.
Click "Refresh Health Status" to check provider healthβ¦
Question generate
Produce predictive survey questions from arbitrary focus text using structured responses.
-
POST /api/question-generate Submit
{ "focus_text": "..." }to receive three diagnostic survey questions. -
POST /api/question-generate/<user_id> Generate personalized follow-up questions for a respondent by ID, falling back to exploration when no prediction errors are found.
-
POST /api/question-generate/upload Persist a question object with answer options into the database.
User responses
Record and maintain answers submitted by users.
-
POST /api/responses Submit
{"user_id", "question_id", "option_id", "question_category"}to capture or update an answer. Category is REQUIRED. -
β οΈ BREAKING CHANGE: The
question_categoryfield is now REQUIRED. Requests without this field will return HTTP 400 Bad Request. -
Request Body Examples
// β CORRECT - Profile question { "user_id": 123, "question_id": 5, "option_id": 42, "question_category": "profile" } // β CORRECT - Seating preference question { "user_id": 123, "question_id": 1, "option_id": 11, "question_category": "seating" } // β CORRECT - Finance attitude question { "user_id": 123, "question_id": 201, "option_id": 2015, "question_category": "finance" } // β CORRECT - Technology opinion question { "user_id": 123, "question_id": 301, "option_id": 3022, "question_category": "technology" } // β INCORRECT - Missing category (will fail with 400) { "user_id": 123, "question_id": 5, "option_id": 42 // ERROR: Missing question_category }Validation Error Response
// HTTP 400 Bad Request { "error": "question_category is required and must be a non-empty string" }Common Categories:
seating- Initial seating/placement questionsprofile- General profile-building questionsfinance- Financial attitudes and behaviorstechnology- Technology usage and opinionsattitudes_about_money- Money-related beliefslifestyle- Lifestyle choices and habitsprediction- Prediction game questions
Categories are normalized to lowercase with spaces replaced by underscores.
-
GET /api/users/<user_id>/responses Return every question, option list, and the userβs selected response.
Pinecone configuration
View the current Pinecone namespace used for vector store isolation.
-
GET /api/pinecone-details/current-namespace Retrieve the active namespace for Pinecone vector operations.
System health
Monitor service readiness and infrastructure seeding.
-
GET /health Basic liveness check.
-
GET /health/ping Simple ping health check - returns immediate pong response.
System status
Monitor active users and prediction generation activity in real-time.
Click refresh to view current active users on the platform and whether predictions are being generated for them.
Click "Refresh Status" to load current system activity.
Prediction accuracy
Evaluate how accurately the system predicts user responses by comparing predictions against actual survey answers.
Enter a user ID to evaluate prediction accuracy. The endpoint compares predictions (made before responses) against actual user answers.
Click "Evaluate Accuracy" to load prediction performance metrics.
This endpoint filters to show only prediction errors (top-box failures) and provides error margin analysis showing where the actual response ranked.
Click "Show Errors" to load prediction errors.
Digital Twin Training
Trigger background training processes to update user digital twins with new responses and predictions.
Every run is now persisted in the training_sessions table so the platform can survive restarts, monitor progress, and audit history.
Enter a user ID to start training. The process runs in the background and automatically uploads responses to Pinecone and generates predictions.
Training Event Logs
Use this feed to stream structured events emitted by the training pipeline. The endpoint returns a request timestamp so the frontend can continue polling from the most recent event.
No log entries yet. Fetch logs to see recent activity.
π§βπ» Developer Integration Guide
Quick Start with cURL
# Start training
curl -X POST http://localhost:5000/api/training/start \
-H "Content-Type: application/json" \
-H "X-API-Key: your_api_key" \
-d '{"user_id": 42}'
# Check status
curl http://localhost:5000/api/training/status/42 \
-H "X-API-Key: your_api_key"
# Stop training
curl -X POST http://localhost:5000/api/training/stop \
-H "Content-Type: application/json" \
-H "X-API-Key: your_api_key" \
-d '{"user_id": 42}'
# List all active trainings
curl http://localhost:5000/api/training/active \
-H "X-API-Key: your_api_key"
JavaScript / Fetch API Example
// Start training
async function startTraining(userId) {
const response = await fetch('/api/training/start', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'your_api_key'
},
body: JSON.stringify({ user_id: userId })
});
const data = await response.json();
if (response.ok) {
console.log('Training started: session', data.session?.session_id, 'pid:', data.session?.pid);
// Start polling for completion
pollTrainingStatus(userId);
} else {
console.error('Failed to start training:', data.error);
}
}
// Poll status every 10 seconds
async function pollTrainingStatus(userId) {
const interval = setInterval(async () => {
const response = await fetch(`/api/training/status/${userId}`, {
headers: { 'X-API-Key': 'your_api_key' }
});
const data = await response.json();
if (data.status === 'not_running') {
clearInterval(interval);
console.log('Training completed for user', userId);
} else if (data.session) {
console.log('Training still running...', 'session', data.session.session_id, 'pid:', data.session.pid);
}
}, 10000);
// Auto-stop polling after 5 minutes
setTimeout(() => clearInterval(interval), 300000);
}
React Component Example
function TrainingButton({ userId, apiKey }) {
const [session, setSession] = React.useState(null);
const [isTraining, setIsTraining] = React.useState(false);
React.useEffect(() => {
let interval;
if (isTraining) {
interval = setInterval(async () => {
const res = await fetch(`/api/training/status/${userId}`, {
headers: { 'X-API-Key': apiKey }
});
const data = await res.json();
setSession(data.session ?? null);
if (data.status === 'not_running') {
setIsTraining(false);
}
}, 10000);
}
return () => clearInterval(interval);
}, [isTraining, userId, apiKey]);
const startTraining = async () => {
const res = await fetch('/api/training/start', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-API-Key': apiKey
},
body: JSON.stringify({ user_id: userId })
});
if (res.ok) {
setIsTraining(true);
}
};
return (
<div>
<button onClick={startTraining} disabled={isTraining}>
{isTraining ? 'Training...' : 'Start Training'}
</button>
{session ? (
<p>Session #{session.session_id} β {session.status} (pid: {session.pid ?? 'n/a'})</p>
) : (
<p>No active session</p>
)}
</div>
);
}
API Endpoints Summary
| Method | Endpoint | Description |
|---|---|---|
| POST | /api/training/start | Start training for a user |
| GET | /api/training/status/<user_id> | Check training status |
| POST | /api/training/stop | Stop running training |
| GET | /api/training/active | List all active trainings |
β οΈ Important Security Notes
- Never expose API keys in frontend code or commit them to version control
- Use environment variables for API keys in production
- Training processes run for up to 3 minutes automatically
- Only one training can run per user at a time
- Logs are stored in
logs/training_<user_id>_<timestamp>.log
π Full documentation: docs/TRAINING_API.md