API Overview

Quick links to live endpoints and their companion UI playgrounds.

API Documentation

πŸ” API Key Management

βœ— No API key set

πŸ’‘ 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.

Users

Manage user records and view onboarding progress.

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.

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.

POST /api/prediction-prompts/template-1 Temporal filtering with exact-option validation for ranked predictions.

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/predict

Send 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.

Provide at least two options. Order determines aggregate weighting.
Restrict the run to specific users or leave empty to target everyone.
Optional override for prediction timestamp.

Batch predictions (Template-1)

POST /api/prediction-prompts/template-1/batch

Start 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.

Question IDs help document your run but pending baseline questions are discovered automatically.

Job progress

Job ID β€”
Status β€”
Progress 0 / 0
Pending IDs β€”
Started β€”
Finished β€”
Elapsed β€”

Batch results

Prediction Provider Health

GET /api/prediction-prompts/provider-health Returns overall provider status plus per-provider latency, rate limits, and diagnostics.

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.

User responses

Record and maintain answers submitted by users.

Pinecone configuration

View the current Pinecone namespace used for vector store isolation.

System health

Monitor service readiness and infrastructure seeding.

System status

Monitor active users and prediction generation activity in real-time.

GET /api/status Returns active users (responses in last 5 minutes) and their prediction activity.

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.

GET /api/accuracy/<user_id> Calculate top-box, top-two-box, and top-three-box accuracy metrics for a specific user.

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.

GET /api/accuracy/errors/<user_id> Returns only questions where the system failed to predict top-box correctly, with error analysis.

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.

POST /api/training/start Start a background training process for a user's digital twin (runs for up to 3 minutes).

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.

Last updated: β€”

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