archai-adaptive-engine / INTEGRATION_GUIDE.md
Builder-Neekhil's picture
Upload INTEGRATION_GUIDE.md with huggingface_hub
029b6e2 verified

ARCHAI Adaptive Assessment Engine β€” Integration Guide

πŸš€ What You Get

A deployed, SOTA-powered adaptive assessment backend that replaces your static 12-question quiz with an intelligent, personalized testing engine. The engine adapts question difficulty in real time based on each user's responses, stops early when measurement is precise enough, and generates structured learning paths with day/week/month granularity.

Live API: https://huggingface.co/spaces/Builder-Neekhil/archai-adaptive-engine


πŸ“Š Architecture Comparison

Feature Your Current App (v1) Adaptive Engine (v2)
Question order Fixed, always same Fisher-information optimal β€” adapts per user
Question count Always 12 Adaptive 6–12 β€” stops when SE < 0.3
Scoring Simple average of responses Bayesian latent ability estimation (ΞΈ per dimension)
Difficulty Same for everyone Calibrated IRT difficulties (-2 to +2 per question)
Precision None reported Standard error per dimension (Β±3% confidence)
Learning paths Static tool list Structured day/week/month actionables with projections

πŸ”Œ Integration Steps

Step 1: Replace Question Flow

Your current app loads q[dim][f] statically. Replace with API calls:

// BEFORE (static)
const questions = {
  literacy: [
    { q: "How well can you explain...", opts: [...] },
    // 2 questions per dimension, fixed order
  ],
  // ... all 6 dimensions
};

// AFTER (adaptive)
let sessionId = null;

async function startAssessment() {
  const res = await fetch(
    'https://Builder-Neekhil-archai-adaptive-engine.hf.space/api/v1/session/start',
    { method: 'POST' }
  );
  const data = await res.json();
  sessionId = data.session_id;
  renderQuestion(data.question);
  updateProgress(data.progress);
}

async function handleAnswer(questionId, optionIndex) {
  const res = await fetch(
    'https://Builder-Neekhil-archai-adaptive-engine.hf.space/api/v1/session/answer',
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        session_id: sessionId,
        question_id: questionId,
        option_index: optionIndex,  // 0 = lowest, 3 = highest
      }),
    }
  );
  const data = await res.json();

  if (data.status === 'complete') {
    // Assessment finished β€” fetch results
    const resultsRes = await fetch(
      `https://Builder-Neekhil-archai-adaptive-engine.hf.space/api/v1/session/${sessionId}`
    );
    const results = await resultsRes.json();
    renderResults(results);
  } else {
    renderQuestion(data.question);
    updateProgress(data.progress);
    // Optional: show interim radar with data.interim_scores
  }
}

Step 2: Render Results (Drop-in Compatible)

The API returns data in the same shape your frontend already expects:

// Results response structure
{
  "session_id": "abc123",
  "status": "complete",
  "overall_score": 64,              // ← Use for big number display
  "dimension_scores": {            // ← Use for radar chart
    "literacy": 64,
    "tooling": 63,
    "strategy": 63,
    "implementation": 66,
    "governance": 63,
    "data": 67,
  },
  "stage": {                        // ← Use for stage badge
    "id": "application",
    "label": "Application",
    "threshold": 60,
    "desc": "You use AI daily"
  },
  "archetype": {                    // ← Use for archetype card
    "id": "responsible-builder",
    "label": "The Responsible Builder",
    "desc": "Balances capability with caution"
  },
  "strengths": [                    // ← Use for strengths section
    { "dimension": "implementation", "label": "Implementation", "score": 66, "color": "#14B8A6" },
    { "dimension": "data", "label": "Data Fluency", "score": 67, "color": "#34D399" },
  ],
  "gaps": [                         // ← Use for gaps section
    { "dimension": "tooling", "label": "Tool Proficiency", "score": 63, "color": "#F43F5E" },
    { "dimension": "strategy", "label": "Strategic Thinking", "score": 63, "color": "#FB7185" },
  ],
  "percentile": 76,                 // ← "Top 76%" badge
  "questions_answered": 8,          // ← Shows adaptive efficiency
  "latent_abilities": { ... },      // ← Optional: raw ΞΈ values
  "measurement_precision": { ... },  // ← Optional: SE per dimension
}

Step 3: Generate Learning Path (After Budget/Hardware Selection)

After the user picks persona, hours, budget, hardware, preference:

async function generatePath(personaId, hoursPerWeek, budgetUsd, hardwareId, preference) {
  const res = await fetch(
    'https://Builder-Neekhil-archai-adaptive-engine.hf.space/api/v1/path/generate',
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        session_id: sessionId,
        persona_id: personaId,        // "ml-eng", "swe", "product", etc.
        hours_per_week: hoursPerWeek, // 2, 5, 10, 20
        budget_usd: budgetUsd,        // 0, 25, 100, 500
        hardware_id: hardwareId,      // "8gb", "16gb", "24gb", "64gb"
        preference: preference,       // "local", "api", "both"
      }),
    }
  );
  const path = await res.json();

  // Render Day-by-Day actions
  renderDays(path.learning_path.days);

  // Render Week-by-Week plan
  renderWeeks(path.learning_path.weeks);

  // Render Month-by-Month strategy
  renderMonths(path.learning_path.months);

  // Show projection
  renderProjection(path.projections);
}

Step 4: New UI Components to Add

A. Adaptive Progress Indicator

// Shows "Question 3 of ~8" instead of fixed "3 of 12"
function AdaptiveProgress({ progress }) {
  return (
    <div>
      <span>Question {progress.asked} of ~{progress.total}</span>
      <div className="dim-pills">
        {progress.dimensions_covered.map(d => (
          <span key={d} className="pill">{d}</span>
        ))}
      </div>
    </div>
  );
}

B. Day-by-Day Actionable Card

function DayActionCard({ day }) {
  return (
    <div className={`card ${day.quick_win ? 'highlight' : ''}`}>
      <div className="day-label">Day {day.day}</div>
      <h4>{day.title}</h4>
      <p>{day.description}</p>
      <div className="meta">
        <span>⏱ {day.estimated_time}</span>
        <span>🏷 {day.action_type}</span>
      </div>
      {day.resource_link && (
        <a href={day.resource_link} target="_blank">Open resource β†’</a>
      )}
      {day.why && <div className="why">πŸ’‘ {day.why}</div>}
    </div>
  );
}

C. Week-by-Week Milestone

function WeekPlanCard({ week }) {
  return (
    <div className="week-card">
      <div className="week-header">
        <h4>Week {week.week}: {week.theme}</h4>
        <span>Focus: {week.focus_dimension}</span>
        <span>~{week.estimated_hours} hrs</span>
      </div>
      {week.actions.map((action, i) => (
        <div key={i} className="action-row">
          <div className="action-title">{action.title}</div>
          <div className="action-meta">
            <span>{action.type}</span>
            <span>{action.estimated_hours}h</span>
            <span>{action.cost}</span>
          </div>
          <div className="deliverable">πŸ“‹ {action.deliverable}</div>
        </div>
      ))}
      <div className="checkpoint">βœ… {week.checkpoint}</div>
    </div>
  );
}

D. Month-by-Month Strategic Goals

function MonthGoalCard({ month }) {
  return (
    <div className="month-card">
      <h4>Month {month.month}: {month.theme}</h4>
      {month.strategic_goals.map((goal, i) => (
        <div key={i} className="goal">
          <div className="goal-title">🎯 {goal.title}</div>
          <div className="goal-metric">Metric: {goal.metric}</div>
          <ul>
            {goal.tactics.map((t, j) => <li key={j}>{t}</li>)}
          </ul>
        </div>
      ))}
      <div className="review">
        <h5>Monthly Reflection</h5>
        {month.review_questions.map((q, i) => (
          <div key={i} className="review-q">β€’ {q}</div>
        ))}
      </div>
    </div>
  );
}

E. Progress Projection Bar

function ProjectionBar({ projections }) {
  return (
    <div className="projection">
      <div className="projection-text">
        At <strong>{projections.at_hours_per_week} hrs/week</strong>,
        you'll reach <strong>{projections.next_stage}</strong> in
        <strong> ~{projections.estimated_weeks} weeks</strong>
        ({projections.projected_reach_date})
      </div>
      <div className="progress-bar">
        <div className="fill" style={{ width: `${(projections.gap_to_next / 20) * 100}%` }} />
      </div>
      <div className="gap-label">{projections.gap_to_next} points to next stage</div>
    </div>
  );
}

πŸ”§ API Reference

POST /api/v1/session/start

Initialize a new assessment session.

Response:

{
  "session_id": "abc123...",
  "question": {
    "id": "lit_3",
    "dimension": "literacy",
    "dimension_label": "AI Literacy",
    "text": "Can you explain what a transformer architecture is...",
    "options": ["No idea", "Vague understanding", "Can explain", "Can implement"],
    "difficulty": 0.5,
    "discrimination": 1.8,
    "concept_tags": ["transformers", "attention", "architecture"]
  },
  "progress": {"asked": 0, "total": 12, "dimensions_covered": []},
  "status": "in_progress"
}

POST /api/v1/session/answer

Submit an answer and get the next adaptive question.

Request:

{
  "session_id": "abc123...",
  "question_id": "lit_3",
  "option_index": 2
}

Response (in_progress):

{
  "session_id": "abc123...",
  "question": { /* next adaptive question */ },
  "progress": {"asked": 1, "total": 12, "dimensions_covered": ["literacy"]},
  "interim_scores": {"literacy": 73, "tooling": 50, ...},
  "status": "in_progress"
}

Response (complete):

{
  "session_id": "abc123...",
  "status": "complete",
  "overall_score": 64,
  "dimension_scores": {...},
  "stage": {...},
  "archetype": {...},
  "strengths": [...],
  "gaps": [...],
  "percentile": 76,
  "questions_answered": 8
}

GET /api/v1/session/{session_id}

Get current state or final results.

POST /api/v1/path/generate

Generate structured learning path.

Request:

{
  "session_id": "abc123...",
  "persona_id": "swe",
  "hours_per_week": 5,
  "budget_usd": 25,
  "hardware_id": "16gb",
  "preference": "both"
}

Response:

{
  "session_id": "abc123...",
  "overall_score": 64,
  "stage": {"id": "application", "label": "Application", ...},
  "archetype": {"id": "responsible-builder", ...},
  "dimension_scores": {...},
  "gaps": [...],
  "strengths": [...],
  "learning_path": {
    "days": [ /* 7 day actionables */ ],
    "weeks": [ /* 3-8 week plans */ ],
    "months": [ /* 3 month strategic goals */ ]
  },
  "projections": {
    "current_stage": "Application",
    "next_stage": "Integration",
    "gap_to_next": 11,
    "estimated_weeks": 5,
    "projected_reach_date": "May 28, 2026"
  },
  "meta": {
    "total_hours": 7.5,
    "estimated_weeks": 2,
    "generated_at": "2026-04-23T20:30:00"
  }
}

GET /api/v1/questions

Get the full calibrated question bank (24 questions, 4 per dimension).


🎨 Design Notes

Maintaining Your App's Essence

Your current design uses:

  • Background: #FFF9F5 (warm cream)
  • Primary: #14B8A6 (teal) + #34D399 (pista green)
  • Accent: #F97316 (orange)
  • Typography: Bricolage Grotesque + Figtree + IBM Plex Mono
  • Cards: glassmorphism (rgba(255,255,255,0.55) + blur(24px))

The adaptive engine data is structure-agnostic β€” it returns JSON that you can render with your existing design system. No visual changes required.

Recommended New Visual Elements

  1. Adaptive badge on the landing page: "Adaptive Assessment Β· Questions adjust to your level"
  2. Live precision indicator during assessment: "Measurement confidence: 87%" (derived from 1 - SE)
  3. Question difficulty indicator (subtle): Show a tiny dot color-coded by difficulty level
  4. Day/week/month toggle on the learning path page

πŸ§ͺ Testing

Manual API Test

# 1. Start session
curl -sX POST https://Builder-Neekhil-archai-adaptive-engine.hf.space/api/v1/session/start | python -m json.tool

# 2. Answer first question (replace SESSION_ID and Q_ID)
curl -sX POST https://Builder-Neekhil-archai-adaptive-engine.hf.space/api/v1/session/answer \
  -H "Content-Type: application/json" \
  -d '{"session_id":"SESSION_ID","question_id":"Q_ID","option_index":2}' | python -m json.tool

# 3. Get results
curl -s https://Builder-Neekhil-archai-adaptive-engine.hf.space/api/v1/session/SESSION_ID | python -m json.tool

# 4. Generate path
curl -sX POST https://Builder-Neekhil-archai-adaptive-engine.hf.space/api/v1/path/generate \
  -H "Content-Type: application/json" \
  -d '{"session_id":"SESSION_ID","persona_id":"swe","hours_per_week":5,"budget_usd":25}' | python -m json.tool

πŸ“ˆ Advanced: Adding More Questions

To expand the question bank, add entries to build_question_bank() in adaptive_engine.py:

Question("lit_5", Dimension.LITERACY,
    "Your new question here?",
    ["Option A", "Option B", "Option C", "Option D"],
    difficulty=1.0,    # Calibrate: -2 (easy) to +2 (hard)
    discrimination=1.5,  # Higher = better at separating high/low ability
    concept_tags=["tag1", "tag2"]
),

Re-deploy to Hugging Face Spaces after updating.


πŸ—οΈ Self-Hosting (Optional)

If you prefer to host the API yourself:

git clone https://huggingface.co/spaces/Builder-Neekhil/archai-adaptive-engine
cd archai-adaptive-engine
pip install -r requirements.txt
uvicorn main:app --host 0.0.0.0 --port 7860

Or deploy to:

  • Hugging Face Spaces (free, persistent)
  • Render/Railway/Fly.io (good for custom domains)
  • AWS Lambda + API Gateway (serverless, scales to zero)

πŸ“ CORS Configuration

The API is configured with allow_origins=["*"] for development. For production, restrict to your Netlify domain:

# In main.py
app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://your-ai-arch.netlify.app"],
    allow_credentials=True,
    allow_methods=["POST", "GET"],
    allow_headers=["Content-Type"],
)

🎯 Next Steps

  1. βœ… Test the API with the curl commands above
  2. βœ… Wire up startAssessment() and handleAnswer() in your React app
  3. βœ… Add day/week/month rendering components
  4. βœ… Style new components to match your existing design system
  5. πŸ”„ Iterate on question difficulty calibration based on real user data

Questions? The API docs are live at: https://Builder-Neekhil-archai-adaptive-engine.hf.space/docs