The repository
A start folder and the finish.
Open the kit01-first-tutor in learn-tutor-starter
Build with Learn · Step 1
About 10 minutes with a coding assistant, 15 by hand.
What you'll build. A chat page where a learner asks for help with a problem and gets a hint from Learn, not the answer. Your server keeps the key; the page talks only to your server. Under each reply you see the turn's safety status and its receipt.
An account and a key. Sign in to the developer console, add Learn to your workspace, and create a server key in My APIs. Try a turn in the Sandbox first if you like.
Node 24 or later. The code uses no packages.
Your environment. Put your key in FOREVERLEARNING_API_KEY and your API host in FOREVERLEARNING_BASE_URL:
https://developers-api.foreverlearning.ai/v1https://developers-api-staging.foreverlearning.ai/v1If your key has more than one Learn assignment, also set FOREVERLEARNING_ASSIGNMENT_ID.
Start from an empty folder. The finished checkpoint is 01-first-tutor in learn-tutor-starter.
Each turn that succeeds costs 5¢. A turn that fails costs nothing. Preparing a session is free.
Open an empty folder in your coding assistant, with your 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, from an empty folder, against the release you use. Coding assistants are your tools; they are not part of the Learn API.
Goal: a chat page where a learner asks for help with a problem and gets a hint from Learn, not the answer.
Read first: https://developers.foreverlearning.ai/docs/learn/ (the Learn integration guide), and the Learn OpenAPI contract and the runnable TypeScript example linked there. Use only what they describe.
Start from: an empty folder.
Build, in TypeScript on Node 24 or later:
1. A small server with one route that the page calls for each message. The route holds the key, prepares one Learn session per learner (task kind "homework"), and sends each message as a Guided turn.
2. A pseudonymous learner id for each new browser, kept in a cookie.
3. A minimal chat page. Show each reply in it, with both parts: what the tutor says (the conversation part) and the hint to work on (the display part, in Markdown). Under the reply, 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. Then append its receipt (request id, session id, learner id, posture, safety level, billable units, charge) as one JSON line to receipts.jsonl on the server.
5. A package.json whose `npm start` serves the page at http://localhost:$PORT (default 3000), and a README that says how to run it.
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 page loads its other code, so the learner never sees raw notation.
- Use a pseudonymous learner id, never a name or an email. Make a new random id for each new browser; never reuse a fixed test id.
- Each message is a real turn, at 5¢ per turn that succeeds. Test with two or three messages, no more. Test as one learner, 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`, sent a message through your route, and the tutor's hint came back
- the safety status and the receipt show under the reply on the page
- receipts.jsonl has one line for each confirmed turnPaste into your coding assistant.
The guide sections this step uses: Prepare without generating, Choose a posture and Send a turn and validate its result.
Two calls do the work:
POST /v1/quest/sessions prepares a session for the learner, with the task ("kind": "homework"). It is free and returns a session_id.POST /v1/chat sends each message as a Guided turn. The reply comes back as server-sent events: metadata (the request id), content for the conversation part (what the tutor says) and the display part (the hint to work on, in Markdown), then safety_status, quest_receipt and done. A turn counts only when done arrives with the same request id.If a learner already has an open session (for example after your server restarts and forgets it), 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).
Every request carries Authorization: Bearer <key>, a pseudonymous X-User-Id, FL-API-Version: 2026-12-01, and, on a POST, a new Idempotency-Key.
Create these files in an empty folder, then run npm start and open http://localhost:3000.
File: package.json
{
"name": "learn-first-tutor",
"version": "1.0.0",
"private": true,
"type": "module",
"description": "Build with Learn, step 1: your first tutor.",
"engines": { "node": ">=24" },
"scripts": {
"start": "node --env-file-if-exists=.env server.ts"
}
}
File: .env.example
# Copy this file to .env and fill in your own values. Never commit .env.
# Your Learn server key, from My APIs in your developer workspace. It stays on your server.
FOREVERLEARNING_API_KEY=
# The API host, ending in /v1.
FOREVERLEARNING_BASE_URL=https://developers-api.foreverlearning.ai/v1
# To test on staging instead:
# FOREVERLEARNING_BASE_URL=https://developers-api-staging.foreverlearning.ai/v1
# Optional: your Learn assignment id, from My APIs. Leave empty if your key has one assignment.
FOREVERLEARNING_ASSIGNMENT_ID=
# The port for your local server.
PORT=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: server.ts
// Your first tutor: a small server that keeps the Learn key and a chat page that
// shows the reply. Node 24+, no packages. Start it with: npm start
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { readFile, appendFile } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
import { join } from 'node:path';
import { createSession, sendTurn, isConfigured, LearnError } from './learn.ts';
const PORT = Number(process.env.PORT ?? 3000);
const PUBLIC = join(import.meta.dirname, 'public');
const RECEIPTS = join(import.meta.dirname, 'receipts.jsonl');
// One Learn session per learner. A real app keeps this in its database.
const sessions = new Map<string, string>();
// The task every session in this checkpoint starts with.
const SETUP = { task: { kind: 'homework' }, team_dialog: false };
const FILES: Record<string, string> = {
'/': 'index.html',
'/app.js': 'app.js',
'/style.css': 'style.css',
};
const TYPES: Record<string, string> = { html: 'text/html; charset=utf-8', js: 'text/javascript; charset=utf-8', css: 'text/css; charset=utf-8' };
// A pseudonymous learner id kept in a cookie: never a name or an email.
function learnerId(request: IncomingMessage, response: ServerResponse): string {
const match = /(?:^|;\s*)learner=([A-Za-z0-9_-]{1,128})/.exec(request.headers.cookie ?? '');
if (match) return match[1];
const id = 'learner-' + randomUUID();
response.setHeader('Set-Cookie', 'learner=' + id + '; Path=/; HttpOnly; SameSite=Strict; Max-Age=31536000');
return id;
}
async function readJson(request: IncomingMessage): Promise<Record<string, unknown>> {
let raw = '';
for await (const chunk of request) {
raw += chunk;
if (raw.length > 20000) throw new Error('Message too long');
}
return JSON.parse(raw || '{}');
}
// What the learner sees when a request fails: your app's own short words. Learn's own message is
// for you, in the server log with the request id; never show it to the learner.
function forLearner(e: LearnError): string {
if (e.code === 'DEVELOPER_POLICY_BLOCKED') return "I can't help with that message. Try asking another way.";
if (e.status === 429) return 'The tutor is busy right now. Try again in a moment.';
return "That didn't go through. Try again in a moment.";
}
function send(response: ServerResponse, event: string, data: unknown) {
response.write('event: ' + event + '\ndata: ' + JSON.stringify(data) + '\n\n');
}
async function turn(request: IncomingMessage, response: ServerResponse) {
const learner = learnerId(request, response);
const { message } = await readJson(request);
if (typeof message !== 'string' || !message.trim()) {
response.writeHead(400, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: 'Type a message first.' }));
return;
}
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.trim(), posture: 'guided' }, (part, text) => send(response, 'text', { part, text }));
// Keep the receipt: one line per confirmed turn.
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: forLearner(e), request_id: e.requestId });
}
response.end();
}
const server = createServer(async (request, response) => {
response.setHeader('X-Content-Type-Options', 'nosniff');
try {
if (request.method === 'POST' && request.url === '/api/turn') return await turn(request, response);
const file = request.method === 'GET' ? FILES[(request.url ?? '/').split('?')[0]] : undefined;
if (!file) {
response.writeHead(404).end('Not found');
return;
}
learnerId(request, response);
const body = await readFile(join(PUBLIC, file));
response.writeHead(200, { 'Content-Type': TYPES[file.split('.').pop()!], 'Cache-Control': 'no-store' }).end(body);
} catch (error) {
if (!response.headersSent) response.writeHead(500).end('Server error');
console.error(error);
}
});
if (!isConfigured()) console.warn('FOREVERLEARNING_API_KEY is not set. Copy .env.example to .env and add your key.');
server.listen(PORT, '127.0.0.1', () => console.log('Your tutor is running at http://localhost:' + PORT));
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>My first tutor</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>
<main class="chat">
<header>
<h1>My first tutor</h1>
<p>Ask for help with a problem. You get a hint, not the answer.</p>
</header>
<ol id="messages" aria-live="polite"></ol>
<form id="composer">
<label for="message" class="visually-hidden">Your message</label>
<textarea id="message" name="message" rows="2" placeholder="Type your question" required></textarea>
<button type="submit">Send</button>
</form>
</main>
<script src="/app.js" type="module"></script>
</body>
</html>
File: public/app.js
// The chat page. It talks only to your own server (/api/turn), never to Learn directly.
const messages = document.querySelector('#messages');
const form = document.querySelector('#composer');
const input = document.querySelector('#message');
const button = form.querySelector('button');
// A small, safe Markdown renderer for the reply's display part:
// paragraphs, lists, `code`, **bold** and *italic*. Everything is escaped first.
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>');
}
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,
});
}
function add(role, text) {
const item = document.createElement('li');
item.className = 'message ' + role;
const bubble = document.createElement('div');
bubble.className = 'bubble';
if (text) bubble.textContent = text;
item.append(bubble);
messages.append(item);
item.scrollIntoView({ block: 'end' });
return item;
}
function chip(label, value, kind) {
const span = document.createElement('span');
span.className = 'chip ' + (kind ?? '');
span.textContent = label + ': ' + value;
return span;
}
function dollars(micro) {
return '$' + (micro / 1e6).toFixed(2);
}
// Read the server's events: the reply's "text" parts, then "done" or "failed".
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) };
}
}
}
form.addEventListener('submit', async (submit) => {
submit.preventDefault();
const text = input.value.trim();
if (!text) return;
add('learner', text);
input.value = '';
button.disabled = true;
const item = add('tutor', '');
const bubble = item.querySelector('.bubble');
const said = document.createElement('p');
const board = document.createElement('div');
board.className = 'board';
bubble.append(said, board);
bubble.classList.add('waiting');
let conversation = '';
let display = '';
try {
const response = await fetch('/api/turn', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message: text }),
});
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 meta = document.createElement('div');
meta.className = 'meta';
meta.append(
chip('Safety', data.safety.level, 'safety-' + data.safety.level),
chip('Receipt', data.receipt.billable_units + ' turn · ' + dollars(data.receipt.charge_micro_usd) + ' · ' + data.receipt.settlement),
chip('Request', data.receipt.request_id.slice(0, 12) + '…'),
);
item.append(meta);
} else if (event === 'failed') {
// Your app's own words (from the server); Learn's error text stays in the server log.
said.textContent = data.message;
item.classList.add('error');
}
item.scrollIntoView({ block: 'end' });
}
} catch {
said.textContent = 'The connection dropped. Try again.';
item.classList.add('error');
} finally {
bubble.classList.remove('waiting');
button.disabled = false;
input.focus();
}
});
input.addEventListener('keydown', (key) => {
if (key.key === 'Enter' && !key.shiftKey) {
key.preventDefault();
form.requestSubmit();
}
});
File: public/style.css
:root {
--bg: #f6f5f1;
--panel: #ffffff;
--ink: #1d1d1f;
--muted: #5d5d66;
--accent: #1f5f8b;
--learner: #e6eef5;
--line: #dedbd2;
--clear: #2f7d4f;
--watch: #9a6b00;
--warning: #b3471d;
--critical: #a1122b;
font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
color: var(--ink);
background: var(--bg);
}
* { box-sizing: border-box; }
body { margin: 0; }
.chat { max-width: 720px; margin: 0 auto; min-height: 100vh; display: flex; flex-direction: column; padding: 24px 16px; }
header h1 { margin: 0 0 4px; font-size: 1.5rem; }
header p { margin: 0 0 16px; color: var(--muted); }
#messages { list-style: none; margin: 0; padding: 0; flex: 1; display: flex; flex-direction: column; gap: 12px; }
.message { display: flex; flex-direction: column; max-width: 85%; }
.message.learner { align-self: flex-end; }
.bubble { margin: 0; padding: 10px 14px; border-radius: 14px; line-height: 1.45; background: var(--panel); border: 1px solid var(--line); }
.bubble p { margin: 0 0 6px; white-space: pre-wrap; }
.bubble p:last-child { margin-bottom: 0; }
.board { border-left: 3px solid var(--accent); padding-left: 10px; margin-top: 4px; }
.board:empty { display: none; }
.board ul, .board ol { margin: 4px 0; padding-left: 20px; }
code { font-family: ui-monospace, Consolas, monospace; background: #f0efe9; padding: 0 4px; border-radius: 4px; }
.learner .bubble { background: var(--learner); border-color: transparent; }
.bubble.waiting::after { content: "Thinking…"; color: var(--muted); font-size: 0.9rem; }
.error .bubble { border-color: var(--warning); }
.meta { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; }
.chip { font-size: 0.78rem; padding: 2px 8px; border-radius: 999px; background: #ecebe6; color: var(--muted); }
.chip.safety-clear { background: #e3f1e8; color: var(--clear); }
.chip.safety-watch { background: #f6edd6; color: var(--watch); }
.chip.safety-warning { background: #f8e3da; color: var(--warning); }
.chip.safety-critical, .chip.safety-unknown { background: #f7dde2; color: var(--critical); }
#composer { display: flex; gap: 8px; margin-top: 16px; }
#composer textarea { flex: 1; font: inherit; padding: 10px 12px; border: 1px solid var(--line); border-radius: 10px; resize: vertical; }
#composer button { font: inherit; padding: 0 18px; border: 0; border-radius: 10px; background: var(--accent); color: #fff; cursor: pointer; }
#composer button:disabled { opacity: 0.5; cursor: default; }
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
.heading { margin: 8px 0 4px; }
.katex { font-size: 1.05em; }
The same two calls in a terminal chat, with the standard library only (Python 3.11 or later). Run python tutor.py, or python tutor.py "your message" for one turn.
File: tutor.py
"""Your first tutor, in the terminal. Python 3.11+, standard library only.
python tutor.py # chat until you press Enter on an empty line
python tutor.py "I'm stuck on ..." # send one message and stop
Reads FOREVERLEARNING_API_KEY, FOREVERLEARNING_BASE_URL and (optional)
FOREVERLEARNING_ASSIGNMENT_ID from the environment. Each turn that succeeds costs 5 cents.
"""
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", "")
LEARNER = "learner-" + str(uuid.uuid4()) # pseudonymous: never a name or an email
def post(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()),
# Send your own User-Agent, so your requests are easy to recognize.
"User-Agent": "learn-tutor-starter/1.0 (python)",
}
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 SystemExit(f"Learn returned {error.code} {detail.get('code', '')}: {detail.get('message', '')} (request {detail.get('request_id', '')})")
def create_session():
"""Prepare a session. Nothing is generated and nothing is charged."""
with post("/quest/sessions", {"setup": {"task": {"kind": "homework"}, "team_dialog": False}}) as response:
return json.load(response)["session_id"]
def send_turn(session_id, prompt):
"""Send one Guided turn, print the reply when it arrives, and return the receipt."""
body = {"session_id": session_id, "prompt": prompt, "posture": "guided",
"quest": {"operation": "turn", "requested_support": "auto", "team_dialog": False}}
request_id = safety = receipt_event = commercial = None
with post("/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"):
print(event["text"], flush=True)
elif kind == "safety_status":
safety = event
elif kind == "quest_receipt":
receipt_event = event["receipt"]
elif kind == "done":
commercial = event["commercial"]
elif kind == "error":
raise SystemExit(f"{event['code']}: {event['message']} (request {event['request_id']})")
# A turn counts only when the final event confirms it with the same identity.
if not commercial or commercial["request_id"] != request_id or not safety or not receipt_event:
raise SystemExit(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")
print(f"\nSafety: {safety['level']} · Receipt: {commercial['billable_units']} turn, "
f"${commercial['charge']['amount_micro_usd'] / 1e6:.2f}, {commercial['settlement']} · Request: {request_id}\n")
return receipt
def main():
session_id = create_session()
if len(sys.argv) > 1:
send_turn(session_id, " ".join(sys.argv[1:]))
return
while message := input("You: ").strip():
send_turn(session_id, message)
if __name__ == "__main__":
main()
Python's default user agent is refused by the API host, so the script sends its own User-Agent header.
Prepare a session, then send one turn and read the events that come back. Run bash turn.sh.
File: turn.sh
#!/usr/bin/env bash
# Your first tutor with cURL: prepare a session (free), then send one Guided turn
# and read the events Learn sends back. Needs FOREVERLEARNING_API_KEY and FOREVERLEARNING_BASE_URL.
# bash turn.sh "I am stuck on 3x + 5 = 20. Can you just tell me what x is?"
set -euo pipefail
LEARNER="learner-$(date +%s)-$RANDOM$RANDOM" # pseudonymous: never a name or an email
MESSAGE="I am stuck on 3x + 5 = 20. Can you just tell me what x is?"
if [ $# -gt 0 ]; then MESSAGE="$1"; fi
ASSIGNMENT_HEADER=()
if [ -n "${FOREVERLEARNING_ASSIGNMENT_ID:-}" ]; then ASSIGNMENT_HEADER=(-H "X-Assignment-Id: $FOREVERLEARNING_ASSIGNMENT_ID"); fi
# 1. Prepare a session. Nothing is generated and nothing is charged.
SESSION=$(curl -sS "$FOREVERLEARNING_BASE_URL/quest/sessions" \
-H "Authorization: Bearer $FOREVERLEARNING_API_KEY" \
"${ASSIGNMENT_HEADER[@]}" \
-H "X-User-Id: $LEARNER" \
-H "FL-API-Version: 2026-12-01" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: setup-$LEARNER" \
--data '{"setup":{"task":{"kind":"homework"},"team_dialog":false}}' \
| grep -o '"session_id":"[^"]*"' | head -n 1 | cut -d'"' -f4)
echo "Session: $SESSION"
# 2. Send one Guided turn. The reply comes back as server-sent events, complete and checked:
# metadata, content (conversation, then display), safety_status, quest_receipt, done.
BODY=$(printf '{"session_id":"%s","prompt":"%s","posture":"guided","quest":{"operation":"turn","requested_support":"auto","team_dialog":false}}' \
"$SESSION" "$(printf '%s' "$MESSAGE" | sed 's/\\/\\\\/g; s/"/\\"/g')")
curl -sS --no-buffer "$FOREVERLEARNING_BASE_URL/chat" \
-H "Authorization: Bearer $FOREVERLEARNING_API_KEY" \
"${ASSIGNMENT_HEADER[@]}" \
-H "X-User-Id: $LEARNER" \
-H "FL-API-Version: 2026-12-01" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: turn-1-$LEARNER" \
--data "$BODY"
Run npm start, open http://localhost:3000, and ask for help with 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 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 that points at the next step. It does not give the value of x.A real reply, captured November 23, 2026, word for word:
You’re working with a linear equation and want the value of x. Let’s keep the solving step yours.
In
3x + 5 = 20, what operation undoes the added 5? Name that operation, then apply it to both sides.
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: Safety: clear for an ordinary question. The levels are clear, watch, warning and critical; unknown means the turn was not evaluated, and is not an all-clear. Step 5 shows how your app acts on each level.
Under the reply, from the turn's final done event:
GET /v1/requests/<id>) or ask us about it.In receipts.jsonl on your server, one line per confirmed turn, for example:
{"request_id":"req_…","session_id":"…","learner_id":"learner-…","posture":"guided","safety_level":"clear","billable_units":1,"charge_micro_usd":50000,"settlement":"settled"}
The key. Open your browser's developer tools: the page calls only your own server (/api/turn), never the Learn API, and no page or script contains the key.
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. | Check FOREVERLEARNING_API_KEY on the server, and restart it after changing .env. |
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. | 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). |
400 DEVELOPER_INVALID_REQUEST | The body does not match the contract. The error names the field and the issue, for example setup.task.kind and invalid_value; often it is a missing session_id or an empty prompt. | Prepare the session first and send its session_id with each turn. |
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 kit01-first-tutor in learn-tutor-starter
One click to start.
DownloadThe same steps, by hand.
01-first-tutorYour first tutor in ten minutes.
Start building