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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# 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:

```javascript
// 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:

```javascript
// 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:

```javascript
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
```jsx
// 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
```jsx
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
```jsx
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
```jsx
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
```jsx
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:**
```json
{
  "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:**
```json
{
  "session_id": "abc123...",
  "question_id": "lit_3",
  "option_index": 2
}
```

**Response (in_progress):**
```json
{
  "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):**
```json
{
  "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:**
```json
{
  "session_id": "abc123...",
  "persona_id": "swe",
  "hours_per_week": 5,
  "budget_usd": 25,
  "hardware_id": "16gb",
  "preference": "both"
}
```

**Response:**
```json
{
  "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
```bash
# 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`:

```python
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:

```bash
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:

```python
# 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