The repository
A start folder and the finish.
Open the kitembed in learn-tutor-starter
Build with Learn · Recipe
About 10 minutes with a coding assistant, an afternoon by hand.
What you'll build. Learn inside the product you already have. Your server gets one small route that keeps the key; your existing help or chat panel shows Learn's reply, its safety status and its receipt. Your product's look, sign-in and stack stay yours. Learn does the teaching.
FOREVERLEARNING_API_KEY, your API host in FOREVERLEARNING_BASE_URL (production: https://developers-api.foreverlearning.ai/v1; to test on staging: https://developers-api-staging.foreverlearning.ai/v1), and a long random string in LEARNER_ID_SECRET. If your key has more than one Learn assignment, also set FOREVERLEARNING_ASSIGNMENT_ID.embed/start: Practice Pad, a small practice product (Node 24 and Express) whose help panel gives a placeholder answer. The finished example is embed.Each turn that succeeds costs 5¢. A turn that fails costs nothing. Preparing a session is free.
Open your product's repository in your coding assistant, with the key and host in the environment it runs commands in, and paste the prompt. The assistant needs to read web pages and run commands. Before we publish a prompt, we run it three times in each of two coding assistants against the release you use. Coding assistants are your tools; they are not part of the Learn API.
Goal: the product in this folder gets Learn inside its own help panel. A learner asks for help and gets a hint from Learn, not the answer, in the product's own look.
Read first: https://developers.foreverlearning.ai/docs/learn/ (the Learn integration guide), and the Learn OpenAPI contract and the runnable examples linked there. Use only what they describe.
Start from: the existing app in this folder (your own product). Keep its stack, its look and its help or chat panel.
Build:
1. A small route in the existing server for the help panel to call. The route holds the Learn key, turns the signed-in user into a pseudonymous learner id, prepares one Learn session per learner (task kind "homework", with the subject your product already knows), and sends each message as a Guided turn.
2. Wire the existing help panel to that route. Show each reply, with both parts: what the tutor says (the conversation part) and the hint to work on (the display part, in Markdown).
3. Under each reply, in the same panel, show the safety status and the receipt: the request id, the turns billed and the charge.
4. Treat a turn as done only when Learn's final done event confirms it. Keep each confirmed receipt (request id, session id, learner id, posture, safety level, billable units, charge) where your product keeps records; in this sample app, append it as one JSON line to receipts.jsonl.
Rules:
- Keep the API key on the server, in the FOREVERLEARNING_API_KEY environment variable. Read the API host from FOREVERLEARNING_BASE_URL. If FOREVERLEARNING_ASSIGNMENT_ID is set, send it as X-Assignment-Id; it can be empty when your key has one assignment. Never send the key to the browser, print it or write it into a file.
- Render each reply's Markdown (headings, lists, bold, code) and its math. Learn writes math between \( and \) inline and between \[ and \] for display math, which often spans several lines. Use a math library, loaded the way your product loads its other code, so the learner never sees raw notation.
- Make the learner id a keyed hash of your own user id, with the secret in LEARNER_ID_SECRET (if it is not set, warn and use a development value). Never use a name or an email.
- Change only what embedding Learn needs. `npm start` must still start the app on $PORT (default 3000).
- Each message is a real turn, at 5¢ per turn that succeeds. Test with two or three messages, no more. Test as one user, keeping the same cookie for all your test messages: a test key admits only a limited number of new learners a day.
Done when:
- you ran `npm start`, asked a question in the existing help panel or through its route, and Learn's hint came back
- the safety status and the receipt show under the reply, in the product's own panel
- receipts.jsonl has one line for each confirmed turnPaste into your coding assistant.
The guide sections this recipe uses: Get the right access, Prepare without generating and Send a turn and validate its result.
Four pieces, whatever your stack:
X-User-Id. Learn never sees a name or an email.POST /v1/quest/sessions (free) and the task your product already knows, then a POST /v1/chat Guided turn for each message.content for the conversation part (what the tutor says) and the display part (the hint, in Markdown), then safety_status, quest_receipt and done. Show both parts, then the safety status and the receipt. A turn counts only when done arrives with the same request id; keep that receipt with your records.If a learner already has an open session (for example after your server restarts and forgets it, if you keep sessions only in memory), preparing a new one makes Learn close the earlier session first: that closeout is billed as its own request, and the first reply takes about ten seconds longer, about 19 seconds (A new session while one is open).
Starting from embed/start, add three files and change four. Then run npm install and npm start, and open http://localhost:3000.
File: learn.ts
// A small Learn API client for your server. The key is read from the environment
// and never leaves this process. Guide: https://developers.foreverlearning.ai/docs/learn/
import { randomUUID } from 'node:crypto';
const API_VERSION = '2026-12-01';
export type Posture = 'guided' | 'feedback' | 'explain';
export interface SafetyStatus {
level: 'unknown' | 'clear' | 'watch' | 'warning' | 'critical';
evaluated: boolean;
response_action: 'none' | 'support' | 'escalate';
source: string;
}
export interface Receipt {
request_id: string;
session_id: string;
posture: string;
turn_index: number;
billable_units: number;
charge_micro_usd: number;
settlement: string;
safety_level: string;
}
export interface TurnResult {
request_id: string;
session_id: string;
reply: string;
display: string;
safety: SafetyStatus;
receipt: Receipt;
}
export class LearnError extends Error {
status: number;
code: string;
requestId: string;
constructor(status: number, code: string, message: string, requestId = '') {
super(message);
this.status = status;
this.code = code;
this.requestId = requestId;
}
}
function settings() {
const key = process.env.FOREVERLEARNING_API_KEY ?? '';
const base = (process.env.FOREVERLEARNING_BASE_URL ?? 'https://developers-api.foreverlearning.ai/v1').replace(/\/+$/, '');
const assignment = process.env.FOREVERLEARNING_ASSIGNMENT_ID ?? '';
return { key, base, assignment };
}
export function isConfigured(): boolean {
return settings().key.length > 0;
}
function headers(learnerId: string, idempotencyKey?: string): Record<string, string> {
const { key, assignment } = settings();
const h: Record<string, string> = {
Authorization: 'Bearer ' + key,
'X-User-Id': learnerId,
'FL-API-Version': API_VERSION,
};
if (assignment) h['X-Assignment-Id'] = assignment;
if (idempotencyKey) {
h['Idempotency-Key'] = idempotencyKey;
h['Content-Type'] = 'application/json';
}
return h;
}
async function failure(response: Response): Promise<LearnError> {
let code = 'HTTP_' + response.status;
let message = 'Learn returned HTTP ' + response.status + '.';
let requestId = response.headers.get('x-request-id') ?? '';
try {
const body = await response.json() as { code?: string; message?: string; request_id?: string };
if (body.code) code = body.code;
if (body.message) message = body.message;
if (body.request_id) requestId = body.request_id;
} catch { /* keep the HTTP status */ }
return new LearnError(response.status, code, message, requestId);
}
// Prepare a session. No reply is generated and nothing is charged.
export async function createSession(learnerId: string, setup: Record<string, unknown>): Promise<string> {
const { base } = settings();
const response = await fetch(base + '/quest/sessions', {
method: 'POST',
headers: headers(learnerId, randomUUID()),
body: JSON.stringify({ setup }),
});
if (!response.ok) throw await failure(response);
const session = await response.json() as { session_id?: string };
if (!session.session_id) throw new LearnError(502, 'NO_SESSION', 'Learn did not return a session id.');
return session.session_id;
}
export interface TurnInput {
sessionId: string;
prompt: string;
posture?: Posture;
}
// Send one learner turn and pass on the reply when it arrives. onText receives each part of the
// reply: the "conversation" part (what the tutor says) and the
// "display" part (the hint or working to show, in Markdown). The result is returned
// only after Learn's final "done" event confirms the turn, with its safety status
// and receipt.
export async function sendTurn(
learnerId: string,
input: TurnInput,
onText: (part: 'conversation' | 'display', text: string) => void,
): Promise<TurnResult> {
const { base } = settings();
const body = {
session_id: input.sessionId,
prompt: input.prompt,
posture: input.posture ?? 'guided',
quest: { operation: 'turn', requested_support: 'auto', team_dialog: false },
};
const response = await fetch(base + '/chat', {
method: 'POST',
headers: headers(learnerId, randomUUID()),
body: JSON.stringify(body),
});
if (!response.ok || !response.body) throw await failure(response);
let requestId = '';
let sessionId = '';
let reply = '';
let display = '';
let safety: SafetyStatus | undefined;
let questReceipt: Record<string, unknown> | undefined;
let commercial: Record<string, any> | undefined;
const handle = (event: Record<string, any>) => {
switch (event.type) {
case 'metadata':
requestId = event.request_id;
sessionId = event.sessionId;
break;
case 'content':
if (event.part === 'conversation') {
reply += event.text;
onText('conversation', event.text);
} else if (event.part === 'display') {
display += event.text;
onText('display', event.text);
}
break;
case 'safety_status':
safety = event as SafetyStatus;
break;
case 'quest_receipt':
questReceipt = event.receipt;
break;
case 'done':
commercial = event.commercial;
break;
case 'error':
throw new LearnError(502, event.code ?? 'STREAM_ERROR', event.message ?? 'The turn did not complete.', event.request_id ?? requestId);
default:
break; // Unknown future events are ignored, never treated as success.
}
};
const decoder = new TextDecoder();
const reader = response.body.getReader();
let buffer = '';
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true }).replaceAll('\r\n', '\n');
let end: number;
while ((end = buffer.indexOf('\n\n')) >= 0) {
const frame = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
const data = frame.split('\n').filter((line) => line.startsWith('data:')).map((line) => line.slice(5).trimStart()).join('\n');
if (data) handle(JSON.parse(data));
}
}
// A reply is committed only when the final event arrived with the same identity.
if (!commercial || commercial.request_id !== requestId || !safety || !questReceipt) {
throw new LearnError(502, 'INCOMPLETE', 'The turn was not confirmed. Look it up with GET /v1/requests/' + requestId + ', as the same learner (X-User-Id), before sending again.', requestId);
}
if (sessionId !== input.sessionId) throw new LearnError(502, 'SESSION_MISMATCH', 'The reply belongs to a different session.', requestId);
return {
request_id: requestId,
session_id: sessionId,
reply,
display,
safety,
receipt: {
request_id: requestId,
session_id: sessionId,
posture: String(questReceipt.posture),
turn_index: Number(questReceipt.turn_index),
billable_units: Number(commercial.billable_units),
charge_micro_usd: Number(commercial.charge?.amount_micro_usd ?? 0),
settlement: String(commercial.settlement),
safety_level: safety.level,
},
};
}
File: learn-route.ts
// The Learn route for your existing server: POST /api/learn/turn.
// It keeps the key, maps your user to a pseudonymous learner id, keeps one Learn session
// per learner, sends the reply to your page when it arrives and keeps every receipt.
import { Router, type Request, type Response } from 'express';
import { createHmac } from 'node:crypto';
import { appendFile } from 'node:fs/promises';
import { join } from 'node:path';
import { createSession, sendTurn, LearnError } from './learn.ts';
const RECEIPTS = join(import.meta.dirname, 'receipts.jsonl');
const SECRET = process.env.LEARNER_ID_SECRET || 'change-this-secret';
if (SECRET === 'change-this-secret') console.warn('Set LEARNER_ID_SECRET so learner ids cannot be traced back to your users.');
// The session's task. Use what your product knows: the subject, the unit, the assignment.
const SETUP = { task: { kind: 'homework', subject: 'Linear equations' }, team_dialog: false };
// One Learn session per learner. Keep this in your database in production.
const sessions = new Map<string, string>();
// A pseudonymous learner id: a keyed hash of your own user id, never a name or an email.
export function learnerIdFor(userId: string): string {
return 'learner-' + createHmac('sha256', SECRET).update(userId).digest('hex').slice(0, 32);
}
function send(response: Response, event: string, data: unknown) {
response.write('event: ' + event + '\ndata: ' + JSON.stringify(data) + '\n\n');
}
export const learnRoute = Router();
learnRoute.post('/turn', async (request: Request, response: Response) => {
const message = String(request.body?.message ?? '').trim();
if (!message) return void response.status(400).json({ error: 'Type a question first.' });
const learner = learnerIdFor(String(response.locals.userId));
response.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-store' });
try {
let sessionId = sessions.get(learner);
if (!sessionId) {
sessionId = await createSession(learner, SETUP);
sessions.set(learner, sessionId);
}
const result = await sendTurn(learner, { sessionId, prompt: message, posture: 'guided' }, (part, text) => send(response, 'text', { part, text }));
await appendFile(RECEIPTS, JSON.stringify({ at: new Date().toISOString(), learner_id: learner, ...result.receipt }) + '\n');
send(response, 'done', { safety: result.safety, receipt: result.receipt });
} catch (error) {
const e = error instanceof LearnError ? error : new LearnError(500, 'SERVER_ERROR', (error as Error).message);
console.error('Learn turn failed:', e.status, e.code, e.message, e.requestId ? 'request ' + e.requestId : '');
send(response, 'failed', { status: e.status, code: e.code, message: e.message, request_id: e.requestId });
}
response.end();
});
File: public/learn-client.js
// Drop-in browser module for Learn replies. It talks only to your own server route.
// import { askLearn } from '/learn-client.js';
// await askLearn(message, element); // renders the reply, safety status and receipt into element
function escape(text) {
return text.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
}
function inline(text) {
return escape(text)
.replace(/`([^`]+)`/g, '<code>$1</code>')
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
.replace(/(^|[^*])\*([^*\s][^*]*)\*/g, '$1<em>$2</em>');
}
// Safe Markdown for the display part: paragraphs, lists, code, bold, italic.
export function markdown(text) {
// Keep each display-math block (\[ ... \], often over several lines) together in one
// paragraph, so the math library finds both delimiters.
const blocks = [];
text = text.replace(/\\\[[\s\S]*?\\\]/g, (block) => '\u0000' + (blocks.push(block) - 1) + '\u0000');
const html = [];
let list = null;
for (const line of text.split('\n')) {
const heading = /^\s*#{1,6}\s+(.*)$/.exec(line);
if (heading) {
if (list) { html.push('</' + list + '>'); list = null; }
html.push('<p class="heading"><strong>' + inline(heading[1]) + '</strong></p>');
continue;
}
const item = /^\s*(?:[-*]|(\d+)[.)])\s+(.*)$/.exec(line);
if (item) {
const kind = item[1] ? 'ol' : 'ul';
if (list !== kind) { if (list) html.push('</' + list + '>'); html.push('<' + kind + '>'); list = kind; }
html.push('<li>' + inline(item[2]) + '</li>');
continue;
}
if (list) { html.push('</' + list + '>'); list = null; }
if (line.trim()) html.push('<p>' + inline(line) + '</p>');
}
if (list) html.push('</' + list + '>');
return html.join('').replace(/\u0000(\d+)\u0000/g, (_, i) => escape(blocks[Number(i)]));
}
// Math in a reply (\( \) inline, \[ \] on its own line), rendered by KaTeX's auto-render,
// loaded in index.html. Without it the learner would see the raw notation.
function typeset(element) {
window.renderMathInElement?.(element, {
delimiters: [{ left: '\\(', right: '\\)', display: false }, { left: '\\[', right: '\\]', display: true }],
throwOnError: false,
});
}
async function* events(response) {
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
for (;;) {
const { done, value } = await reader.read();
if (done) return;
buffer += decoder.decode(value, { stream: true });
let end;
while ((end = buffer.indexOf('\n\n')) >= 0) {
const frame = buffer.slice(0, end);
buffer = buffer.slice(end + 2);
const event = /^event: (.*)$/m.exec(frame)?.[1];
const data = /^data: (.*)$/m.exec(frame)?.[1];
if (event && data) yield { event, data: JSON.parse(data) };
}
}
}
export async function askLearn(message, element, { endpoint = '/api/learn/turn' } = {}) {
const said = document.createElement('p');
const board = document.createElement('div');
board.className = 'learn-board';
const meta = document.createElement('div');
meta.className = 'learn-meta';
element.replaceChildren(said, board, meta);
element.classList.add('learn-waiting');
let conversation = '', display = '';
try {
const response = await fetch(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message }) });
if (!response.ok) throw new Error((await response.json().catch(() => ({}))).error ?? 'HTTP ' + response.status);
for await (const { event, data } of events(response)) {
if (event === 'text' && data.part === 'conversation') { conversation += data.text; said.innerHTML = inline(conversation); typeset(said); }
else if (event === 'text' && data.part === 'display') { display += data.text; board.innerHTML = markdown(display); typeset(board); }
else if (event === 'done') {
const r = data.receipt;
meta.innerHTML = '<span class="learn-safety learn-safety-' + escape(data.safety.level) + '">Safety: ' + escape(data.safety.level) + '</span>'
+ '<span>Receipt: ' + r.billable_units + ' turn · $' + (r.charge_micro_usd / 1e6).toFixed(2) + ' · ' + escape(r.settlement) + '</span>'
+ '<span>Request: ' + escape(r.request_id.slice(0, 12)) + '…</span>';
} else if (event === 'failed') {
said.textContent = 'Help is unavailable right now (' + data.code + '). Try again in a moment.';
}
}
} catch (error) {
said.textContent = 'Help is unavailable right now. ' + error.message;
} finally {
element.classList.remove('learn-waiting');
}
}
Mount the route in server.ts (the whole file, after the change):
File: server.ts
// Practice Pad: an existing product with a practice page and a help panel.
// The help panel now gets its help from Learn, through learn-route.ts.
import express from 'express';
import { randomUUID } from 'node:crypto';
import { join } from 'node:path';
import { learnRoute } from './learn-route.ts';
const app = express();
const PORT = Number(process.env.PORT ?? 3000);
// Stands in for your real sign-in: every visitor gets a user id in a cookie.
app.use((request, response, next) => {
const match = /(?:^|;\s*)user=([A-Za-z0-9_-]{1,64})/.exec(request.headers.cookie ?? '');
const id = match ? match[1] : 'u-' + randomUUID();
if (!match) response.setHeader('Set-Cookie', 'user=' + id + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=31536000');
response.locals.userId = id;
next();
});
app.use(express.json({ limit: '32kb' }));
app.use(express.static(join(import.meta.dirname, 'public')));
const problems = [
{ id: 'p1', text: 'Solve for x: 3x + 5 = 20' },
{ id: 'p2', text: 'Solve for x: 2(x - 4) = 10' },
{ id: 'p3', text: 'Solve for y: 7 - y = 2y + 1' },
];
app.get('/api/problems', (_request, response) => {
response.json({ unit: 'Unit 3: Linear equations', problems });
});
// The help panel calls this. Learn does the teaching; the key stays here.
app.use('/api/learn', learnRoute);
app.listen(PORT, () => console.log('Practice Pad is running at http://localhost:' + PORT));
Call askLearn from the help panel in public/app.js (the whole file, after the change):
File: public/app.js
// Practice Pad's page: the problem list and the help panel, now answered by Learn.
import { askLearn } from '/learn-client.js';
const list = document.querySelector('#problems');
const unit = document.querySelector('#unit');
const helpMessages = document.querySelector('#help-messages');
const helpForm = document.querySelector('#help-form');
const helpInput = document.querySelector('#help-input');
const data = await (await fetch('/api/problems')).json();
unit.textContent = data.unit;
for (const problem of data.problems) {
const item = document.createElement('li');
item.textContent = problem.text;
list.append(item);
}
function addHelp(role, text) {
const item = document.createElement('li');
item.className = 'help-message ' + role;
item.textContent = text;
helpMessages.append(item);
return item;
}
helpForm.addEventListener('submit', async (event) => {
event.preventDefault();
const message = helpInput.value.trim();
if (!message) return;
addHelp('learner', message);
helpInput.value = '';
const reply = addHelp('helper', '');
await askLearn(message, reply);
});
helpInput.addEventListener('keydown', (key) => {
if (key.key === 'Enter' && !key.shiftKey) { key.preventDefault(); helpForm.requestSubmit(); }
});
Load KaTeX for the math in replies, in public/index.html (the whole file, after the change):
File: public/index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Practice Pad</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css" integrity="sha384-nB0miv6/jRmo5UMMR1wu3Gz6NLsoTkbqJghGIsx//Rlm+ZU03BU6SQNC66uf4l5+" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.js" integrity="sha384-7zkQWkzuo3B5mTepMUcHkMB5jZaolc2xDwL6VFqjFALcbeS9Ggm/Yr2r3Dy4lfFg" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/contrib/auto-render.min.js" integrity="sha384-43gviWU0YVjaDtb/GhzOouOXtZMP/7XUzwPTstBeZFe/+rCMvRwr4yROQP43s0Xk" crossorigin="anonymous"></script>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<header class="top">
<strong>Practice Pad</strong>
<span id="unit"></span>
</header>
<div class="layout">
<main>
<h1>Today's practice</h1>
<ol id="problems"></ol>
</main>
<aside class="help" aria-label="Help">
<h2>Need a hand?</h2>
<ol id="help-messages" aria-live="polite"></ol>
<form id="help-form">
<label for="help-input" class="visually-hidden">Your question</label>
<textarea id="help-input" rows="2" placeholder="Ask about a problem" required></textarea>
<button type="submit">Ask</button>
</form>
</aside>
</div>
<script src="/app.js" type="module"></script>
</body>
</html>
Add the reply styles at the end of public/style.css:
Append to: public/style.css
.help-message.helper p { margin: 0 0 6px; }
.learn-board { border-left: 3px solid var(--accent); padding-left: 10px; }
.learn-board:empty, .learn-meta:empty { display: none; }
.learn-board p { margin: 0 0 6px; }
.learn-meta { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; font-size: 0.78rem; color: var(--muted); white-space: normal; }
.learn-meta span { background: #f0efea; border-radius: 999px; padding: 2px 8px; }
.learn-meta .learn-safety-clear { background: #e3f1e8; color: #2f7d4f; }
.learn-meta .learn-safety-watch { background: #f6edd6; color: #9a6b00; }
.learn-meta .learn-safety-warning, .learn-meta .learn-safety-critical, .learn-meta .learn-safety-unknown { background: #f8e3da; color: #a1122b; }
.learn-waiting::after { content: "Thinking…"; color: var(--muted); font-size: 0.9rem; }
code { font-family: ui-monospace, Consolas, monospace; background: #f3f1ec; padding: 0 4px; border-radius: 4px; }
.heading { margin: 8px 0 4px; }
.katex { font-size: 1.05em; }
The same route logic for a Python server, with the standard library only (Python 3.11 or later). Call send_turn(user_id, message) from your framework's route and forward each event to your page. Run python learn_embed.py "your message" to try one turn from the terminal.
File: learn_embed.py
"""Learn inside your own Python server. Python 3.11+, standard library only.
Call send_turn(user_id, message) from your web framework's route and forward each
("text", part, text) event to your page, then the ("done", safety, receipt) event.
python learn_embed.py "I'm stuck on 3x + 5 = 20. Can you just tell me what x is?"
runs one turn for a sample user. Reads FOREVERLEARNING_API_KEY, FOREVERLEARNING_BASE_URL,
LEARNER_ID_SECRET and (optional) FOREVERLEARNING_ASSIGNMENT_ID from the environment.
"""
import hashlib
import hmac
import json
import os
import sys
import urllib.error
import urllib.request
import uuid
BASE = os.environ.get("FOREVERLEARNING_BASE_URL", "https://developers-api.foreverlearning.ai/v1").rstrip("/")
KEY = os.environ["FOREVERLEARNING_API_KEY"]
ASSIGNMENT = os.environ.get("FOREVERLEARNING_ASSIGNMENT_ID", "")
SECRET = os.environ.get("LEARNER_ID_SECRET") or "change-this-secret"
SETUP = {"task": {"kind": "homework", "subject": "Linear equations"}, "team_dialog": False}
SESSIONS = {} # learner id -> Learn session id. Keep this in your database in production.
class LearnError(Exception):
pass
def learner_id_for(user_id):
"""A pseudonymous learner id: a keyed hash of your own user id, never a name or an email."""
return "learner-" + hmac.new(SECRET.encode(), user_id.encode(), hashlib.sha256).hexdigest()[:32]
def _post(learner, path, body):
headers = {"Authorization": "Bearer " + KEY, "X-User-Id": learner, "FL-API-Version": "2026-12-01",
"Content-Type": "application/json", "Idempotency-Key": str(uuid.uuid4()),
"User-Agent": "learn-tutor-starter/1.0 (python)"} # so your requests are easy to recognize
if ASSIGNMENT:
headers["X-Assignment-Id"] = ASSIGNMENT
request = urllib.request.Request(BASE + path, data=json.dumps(body).encode("utf-8"), headers=headers, method="POST")
try:
return urllib.request.urlopen(request, timeout=120)
except urllib.error.HTTPError as error:
raw = error.read()
try:
detail = json.loads(raw or b"{}")
except ValueError:
detail = {"message": raw[:200].decode("utf-8", "replace")}
raise LearnError(f"{error.code} {detail.get('code', '')}: {detail.get('message', '')} (request {detail.get('request_id', '')})")
def send_turn(user_id, message):
"""Yield ("text", part, text) when the reply arrives, then ("done", safety, receipt)."""
learner = learner_id_for(user_id)
if learner not in SESSIONS:
with _post(learner, "/quest/sessions", {"setup": SETUP}) as response:
SESSIONS[learner] = json.load(response)["session_id"]
session_id = SESSIONS[learner]
body = {"session_id": session_id, "prompt": message, "posture": "guided",
"quest": {"operation": "turn", "requested_support": "auto", "team_dialog": False}}
request_id = safety = receipt_event = commercial = None
with _post(learner, "/chat", body) as response:
data = []
for raw in response:
line = raw.decode("utf-8").rstrip("\r\n")
if line.startswith("data:"):
data.append(line[5:].lstrip())
continue
if line or not data:
continue
event, data = json.loads("\n".join(data)), []
kind = event.get("type")
if kind == "metadata":
request_id = event["request_id"]
elif kind == "content" and event["part"] in ("conversation", "display"):
yield ("text", event["part"], event["text"])
elif kind == "safety_status":
safety = event
elif kind == "quest_receipt":
receipt_event = event["receipt"]
elif kind == "done":
commercial = event["commercial"]
elif kind == "error":
raise LearnError(f"{event['code']}: {event['message']} (request {event['request_id']})")
if not commercial or commercial["request_id"] != request_id or not safety or not receipt_event:
raise LearnError(f"The turn was not confirmed. Look it up with GET /v1/requests/{request_id}, as the same learner (X-User-Id), before sending again.")
receipt = {"request_id": request_id, "session_id": session_id, "learner_id": learner, "posture": receipt_event["posture"],
"safety_level": safety["level"], "billable_units": commercial["billable_units"],
"charge_micro_usd": commercial["charge"]["amount_micro_usd"], "settlement": commercial["settlement"]}
with open("receipts.jsonl", "a", encoding="utf-8") as kept:
kept.write(json.dumps(receipt) + "\n")
yield ("done", safety, receipt)
if __name__ == "__main__":
sample_user = "u-" + str(uuid.uuid4()) # your product's own user id
for event in send_turn(sample_user, " ".join(sys.argv[1:]) or "I'm stuck on 3x + 5 = 20. Where do I start?"):
if event[0] == "text":
print(event[2], flush=True)
else:
_, safety, receipt = event
print(f"\nSafety: {safety['level']} | Receipt: {receipt['billable_units']} turn, "
f"${receipt['charge_micro_usd'] / 1e6:.2f}, {receipt['settlement']} | Request: {receipt['request_id']}")
The code sends its own User-Agent header, so your requests are easy to recognize in logs and support questions.
The two calls are the same as in step 1: prepare a session with POST /v1/quest/sessions, then send each message to POST /v1/chat. See step 1's cURL.
Start your app (npm start for the sample), open it, and ask the help panel about a problem. For example:
I'm stuck on 3x + 5 = 20. Can you just tell me what x is?
After about 10 to 20 seconds the whole reply appears in your product's help panel, in your product's look, in two parts:
conversation part): a sentence that names what the learner is working on and keeps the step theirs.display part, in Markdown): one question or move toward the next step. It does not give the value of x.A real reply, captured November 23, 2026, word for word:
You’ve set up the equation and reached the step where the value of x is still unknown. Let’s keep the next move yours.
In
3x + 5 = 20, which operation on the left side would you undo first: the multiplication by 3 or the addition of 5?
The reply arrives complete and checked. Nothing unchecked is ever shown.
Every reply is written fresh, so yours will use different words. It should still leave the next step to the learner.
Under the reply, in the same panel:
watch, warning and critical ask your product to act; unknown means the turn was not evaluated and is not an all-clear.req_…).Your product keeps each confirmed receipt with its own records. The sample appends one line per turn to receipts.jsonl:
{"request_id":"req_…","session_id":"…","learner_id":"learner-…","posture":"guided","safety_level":"clear","billable_units":1,"charge_micro_usd":50000,"settlement":"settled"}
/api/learn/turn in the sample), never the Learn API. No page or script contains the key.learner-…), never a name or an email.The reply arrives complete and checked, about 10 to 20 seconds after the request, with nothing sent before it. Set your client and proxy timeouts to allow for that. Nothing unchecked is ever shown.
Learn's replies use Markdown (headings, lists, bold, code) and can contain math, usually written between \( and \) inline and between \[ and \] for display math, which often spans several lines. The guide asks you to render each part "using safe text, Markdown, math and code rendering" (Send a turn and validate its result): render the Markdown, and the math with a math library such as KaTeX, so the learner never sees raw notation. The sample pages load KaTeX from a public CDN and call its auto-render on each reply. A product can serve the same files itself from the npm package, so the learner's browser does not fetch them from a third party.
| What you see | What it means | Fix |
|---|---|---|
401 DEVELOPER_AUTHENTICATION_REQUIRED | The key is missing or wrong on your server. | Check FOREVERLEARNING_API_KEY where your server runs, and restart it. |
| The panel waits, then shows nothing | Your server or a proxy holds back the events, or times out before the reply arrives. | Send Content-Type: text/event-stream, turn off response buffering or compression for the route, and allow at least 30 seconds before a timeout. |
429 DEVELOPER_NEW_USER_LIMIT: "Daily limit for new end users reached. End users already admitted are not affected; new end users can start after 00:00 UTC" | Your key or workspace has admitted its daily number of new learners. | Learners already admitted keep working. New ones can start after the Retry-After time (also in retry_after_seconds). When testing, keep the same learner id between test messages. |
402 DEVELOPER_BALANCE_EXHAUSTED when preparing a session | Your workspace has less than ten turns' worth left (50¢). | Add funds to your workspace, then prepare the session again. |
403 DEVELOPER_POLICY_BLOCKED | The safety screening refused the learner's message before it reached the tutor. | Show your own short message, such as "I can't help with that message. Try asking another way.", and let the learner continue. Never show the refusal's own text; log it with the request id for yourself. |
429, for example DEVELOPER_CAPACITY_LIMIT | Your workspace reached its allowance or rate limit, and the turn was refused. | Show the learner a short "busy, try again" message. Respect the Retry-After header if it is there. A refused turn is a confirmed failure, so you may send a new request for it, with a new Idempotency-Key (Recover the original operation). |
A turn that stops before done (a dropped connection, or an answer still in progress) is not confirmed. Send the same body again with the same Idempotency-Key, or look it up with GET /v1/requests/<request_id>, using the same key, assignment and learner X-User-Id as the original. A turn that committed replays its saved reply at no new charge. 409 REQUEST_IN_PROGRESS means it is still running: check again shortly. 409 REQUEST_FAILED means it failed and was not charged: send it again with a new Idempotency-Key (Recover the original operation). A request refused outright (a 400, 403 or 429 before it was admitted) leaves nothing to look up, and the look-up answers 401: fix the cause and send it again with a new Idempotency-Key.
A start folder and the finish.
Open the kitembed in learn-tutor-starter
One click to start.
DownloadThe same steps, by hand.
embedYour first tutor in ten minutes.
Start building