Developer production · Server APIs
The Learn APIBy ForeverLearning

Build with Learn · Step 3

Photos of handwritten work

About 10 minutes with a coding assistant.

What you'll build. The learner attaches a photo of their handwritten page and gets help on their own lines: which line holds, which doesn't, and why.

Before you start

  • An account and a key, as in step 1, with your key in FOREVERLEARNING_API_KEY and your API host in FOREVERLEARNING_BASE_URL.
  • Start from step 2's checkpoint, 02-four-kinds-of-help. The finished step is 03-photos-of-work.

Uploading a photo is free. Each turn that succeeds costs 5¢, photos included. A turn that fails costs nothing.

Option A: hand it to your coding assistant

Open a copy of 02-four-kinds-of-help in your coding assistant, with your key and host in the environment it runs commands in, and paste the prompt. 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.

Paste this
Goal: the learner attaches a photo of their handwritten page and gets help on their own lines.

Read first: https://developers.foreverlearning.ai/docs/learn/ (the Learn integration guide, especially "Upload learner work separately"), and the Learn OpenAPI contract and the runnable TypeScript example linked there. Use only what they describe.

Start from: the app in this folder, a copy of the 02-four-kinds-of-help folder of learn-tutor-starter. Keep how it works and add to it.

Build:
1. On the chat page, a button to attach up to four photos (PNG, JPEG or WebP), with a small preview of each.
2. A server route that uploads each photo to Learn for the learner's teaching session, before the turn that uses it, and returns the attachment id to the page. Uploading is free.
3. Send the attachment ids with the learner's next message, in quest.attachment_ids, then clear the tray. Show the photos in the learner's message.
4. Everything else as before: the kind of help on each message, both parts of the reply, the safety status, the receipt, and 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. 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.
- The browser sends photos only to your own server, never to Learn. Keep the limits in the guide: up to four files per turn, 8 MiB per image.
- Each message is a real turn, at 5¢ per turn that succeeds. Test with one or two turns, 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. To test, make your own picture of a few handwritten-looking lines of algebra.

Done when:
- you ran `npm start`, attached a photo of some written work, asked for Feedback without typing the work out, and the reply speaks to the lines in the photo
- the safety status and the receipt show under the reply
- receipts.jsonl has one line for each confirmed turn

Paste into your coding assistant.

Option B: by hand

The guide section this step uses: Upload learner work separately.

  1. The page sends the photo to your server, never to Learn.
  2. Your server uploads it with POST /v1/quest/attachments: media_type (image/png, image/jpeg or image/webp), data (plain base64, not a data URL), an optional filename, and the learner's session_id. It is free and returns an attachment_id.
  3. The next turn carries it: "quest": {"attachment_ids": ["<id>"]}, up to four per turn, usually with "posture": "feedback".

Limits: 8 MiB per image, 6,000 pixels per side. An upload belongs to the learner and session it was made for, and expires 30 days after upload.

Starting from 02-four-kinds-of-help, replace these files. Then run 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;
  // Send the posture on every turn: leaving it out means Guided, except in a Diagnostic
  // session, where null leaves it out so the session stays Diagnostic.
  posture?: Posture | null;
  // 'opening' asks Learn to greet the learner, with an empty prompt. It is a turn like any other.
  operation?: 'turn' | 'opening';
  // Up to four uploaded files (photos of the learner's work) for this turn.
  attachmentIds?: string[];
}

// Upload one file of the learner's work. Free: no reply is generated. The returned id is
// private to this learner and session, and goes with a turn in quest.attachment_ids.
export async function uploadAttachment(learnerId: string, sessionId: string, mediaType: string, base64: string, filename: string): Promise<string> {
  const { base } = settings();
  const response = await fetch(base + '/quest/attachments', {
    method: 'POST',
    headers: headers(learnerId, randomUUID()),
    body: JSON.stringify({ session_id: sessionId, media_type: mediaType, data: base64, filename }),
  });
  if (!response.ok) throw await failure(response);
  const upload = await response.json() as { attachment_id?: string };
  if (!upload.attachment_id) throw new LearnError(502, 'NO_ATTACHMENT', 'Learn did not return an attachment id.');
  return upload.attachment_id;
}

// 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.operation === 'opening' ? '' : input.prompt,
    ...(input.posture === null ? {} : { posture: input.posture ?? 'guided' }),
    quest: {
      operation: input.operation ?? 'turn', requested_support: 'auto', team_dialog: false,
      ...(input.attachmentIds?.length ? { attachment_ids: input.attachmentIds } : {}),
    },
  };
  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

// Photos of handwritten work: the learner attaches photos of their page (up to four) and gets
// help on their own lines. Builds on step 2's four kinds of help. A small server that keeps
// the Learn key and a chat page that shows the reply. Node 24+, no packages. 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, uploadAttachment, 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, { id: string; diagnostic: boolean }>();

// The task for teaching sessions (Guided, Feedback, Explain): practice, so all three fit.
const SETUP = { task: { kind: 'practice', subject: 'Algebra' }, team_dialog: false };
// A Diagnostic session: the posture and the learner's finished work are set when it is prepared.
function diagnosticSetup(finishedWork: string) {
  return {
    task: { kind: 'practice', subject: 'Algebra', assignment: 'A finished practice quiz.' },
    posture: 'diagnostic',
    // The finished work can only be given here, when the session is prepared.
    assessment: {
      schema_version: 'fl.quest.assessment-input.v1',
      goal: 'Find what the learner understands from their finished practice quiz.',
      sources: [{ id: 'quiz', origin: 'submitted_work', text: finishedWork, attachment_id: null, locator: 'finished quiz', availability: 'available' }],
      items: [], targets: [], original_result: '', limitations: [],
    },
    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, limit = 20000): Promise<Record<string, unknown>> {
  let raw = '';
  for await (const chunk of request) {
    raw += chunk;
    if (raw.length > limit) 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');
}

// The learner's teaching session (Guided, Feedback, Explain), prepared the first time.
async function teachingSession(learner: string) {
  let session = sessions.get(learner);
  if (!session || session.diagnostic) {
    session = { id: await createSession(learner, SETUP), diagnostic: false };
    sessions.set(learner, session);
  }
  return session;
}

const IMAGE_TYPES = ['image/png', 'image/jpeg', 'image/webp'];

// A photo of the learner's work: uploaded to Learn before the turn that uses it. Free.
async function upload(request: IncomingMessage, response: ServerResponse) {
  const learner = learnerId(request, response);
  const { media_type, data, filename } = await readJson(request, 12_000_000);
  if (typeof media_type !== 'string' || !IMAGE_TYPES.includes(media_type) || typeof data !== 'string' || !data || data.length > 11_184_812) {
    response.writeHead(400, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: 'Attach a PNG, JPEG or WebP photo up to 8 MiB.' }));
    return;
  }
  try {
    const session = await teachingSession(learner);
    const id = await uploadAttachment(learner, session.id, media_type, data, typeof filename === 'string' ? filename.slice(0, 120) : 'work');
    response.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify({ attachment_id: id }));
  } catch (error) {
    const e = error instanceof LearnError ? error : new LearnError(500, 'SERVER_ERROR', (error as Error).message);
    console.error('Upload failed:', e.status, e.code, e.message, e.requestId ? 'request ' + e.requestId : '');
    response.writeHead(e.status >= 400 && e.status < 600 ? e.status : 502, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: forLearner(e), code: e.code }));
  }
}

const KINDS = ['guided', 'feedback', 'explain', 'diagnostic'] as const;
type Kind = typeof KINDS[number];

async function turn(request: IncomingMessage, response: ServerResponse) {
  const learner = learnerId(request, response);
  const { message, kind, attachment_ids } = await readJson(request);
  const attachmentIds = Array.isArray(attachment_ids) ? attachment_ids.filter((a): a is string => typeof a === 'string').slice(0, 4) : [];
  if (typeof message !== 'string' || !message.trim() || !KINDS.includes(kind as Kind)) {
    response.writeHead(400, { 'Content-Type': 'application/json' }).end(JSON.stringify({ error: 'Choose a kind of help and type a message first.' }));
    return;
  }
  response.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-store' });
  try {
    // Guided, Feedback and Explain share one session: the posture goes with each turn.
    // Diagnostic is chosen when the session is prepared, with the finished work, so it gets a
    // session of its own; later Diagnostic messages are the learner's answers, sent with no posture.
    // Starting either kind of session closes the learner's other open one (its closeout is a turn).
    const diagnostic = kind === 'diagnostic';
    let session = sessions.get(learner);
    let opening = false;
    if (!session || session.diagnostic !== diagnostic) {
      // Diagnostic: the learner's finished quiz goes into the session's setup, then the session opens.
      const setup = diagnostic ? diagnosticSetup(message.trim()) : SETUP;
      session = { id: await createSession(learner, setup), diagnostic };
      opening = diagnostic;
      sessions.set(learner, session);
    }
    const posture = diagnostic ? null : kind as 'guided' | 'feedback' | 'explain';
    // Photos go with teaching turns; they belong to the session they were uploaded to.
    const result = await sendTurn(learner, { sessionId: session.id, prompt: opening ? '' : message.trim(), posture, operation: opening ? 'opening' : 'turn', attachmentIds: diagnostic ? [] : attachmentIds }, (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);
    if (request.method === 'POST' && request.url === '/api/upload') return await upload(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>Photos of your work</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>Photos of your work</h1>
      <p>Attach a photo of your page and get help on your own lines. Choose the help you want for each message.</p>
    </header>
    <ol id="messages" aria-live="polite"></ol>
    <form id="composer">
      <fieldset class="kinds">
        <legend class="visually-hidden">Kind of help</legend>
        <label><input type="radio" name="kind" value="guided" checked> <span><strong>Guided</strong> I'm working on it</span></label>
        <label><input type="radio" name="kind" value="feedback"> <span><strong>Feedback</strong> Check my work</span></label>
        <label><input type="radio" name="kind" value="explain"> <span><strong>Explain</strong> A worked example I don't follow</span></label>
        <label><input type="radio" name="kind" value="diagnostic"> <span><strong>Diagnostic</strong> I finished a quiz</span></label>
      </fieldset>
      <div class="attach">
        <label class="attach-button">Attach a photo of your work <input id="photos" type="file" accept="image/png,image/jpeg,image/webp" multiple></label>
        <ul id="thumbs"></ul>
      </div>
      <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 and /api/upload), never to Learn directly.
const messages = document.querySelector('#messages');
const form = document.querySelector('#composer');
const input = document.querySelector('#message');
const button = form.querySelector('button[type="submit"], button:not([type])');
const photos = document.querySelector('#photos');
const thumbs = document.querySelector('#thumbs');
let attached = []; // { id, url } for each uploaded photo, up to four

// Upload each chosen photo to your server, which uploads it to Learn. Free: no reply is made.
photos.addEventListener('change', async () => {
  for (const file of [...photos.files].slice(0, 4 - attached.length)) {
    const item = document.createElement('li');
    const img = document.createElement('img');
    img.src = URL.createObjectURL(file);
    img.alt = 'Your photo: ' + file.name;
    item.append(img);
    thumbs.append(item);
    item.classList.add('uploading');
    const data = await new Promise((resolve) => { const r = new FileReader(); r.onload = () => resolve(String(r.result).split(',')[1]); r.readAsDataURL(file); });
    const response = await fetch('/api/upload', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ media_type: file.type, data, filename: file.name }) });
    const body = await response.json();
    item.classList.remove('uploading');
    if (response.ok) attached.push({ id: body.attachment_id, url: img.src });
    else { item.classList.add('failed'); item.title = body.error; }
  }
  photos.value = '';
});

// 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) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[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;
  // The kind of help goes with every message. Diagnostic starts a session of its own.
  const kind = form.querySelector('input[name="kind"]:checked').value;
  const learnerItem = add('learner', text);
  learnerItem.querySelector('.bubble').dataset.kind = kind;
  // The photos go with this message, then the tray clears.
  const sent = attached;
  attached = [];
  thumbs.replaceChildren();
  for (const p of sent) { const img = document.createElement('img'); img.src = p.url; img.alt = 'Your photo'; img.className = 'sent-photo'; learnerItem.append(img); }
  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, kind, attachment_ids: sent.map((p) => p.id) }),
    });
    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('Kind', data.receipt.posture),
          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); }
.kinds { display: flex; flex-wrap: wrap; gap: 6px; border: 0; padding: 0; margin: 0 0 8px; width: 100%; }
.kinds label { flex: 1 1 150px; display: flex; gap: 6px; align-items: flex-start; padding: 8px 10px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); cursor: pointer; font-size: 0.88rem; }
.kinds label:has(input:checked) { border-color: var(--accent); background: #eaf1f7; }
.kinds strong { display: block; }
#composer { flex-wrap: wrap; }
.bubble[data-kind]::before { content: attr(data-kind); display: block; font-size: 0.72rem; text-transform: uppercase; letter-spacing: 0.04em; color: var(--muted); }
.attach { width: 100%; display: flex; align-items: center; gap: 10px; margin-bottom: 6px; }
.attach-button { font-size: 0.88rem; color: var(--accent); border: 1px dashed var(--accent); border-radius: 10px; padding: 6px 10px; cursor: pointer; }
.attach-button input { position: absolute; width: 1px; height: 1px; opacity: 0; }
#thumbs { list-style: none; display: flex; gap: 6px; margin: 0; padding: 0; }
#thumbs img { width: 56px; height: 44px; object-fit: cover; border-radius: 6px; border: 1px solid var(--line); }
#thumbs .uploading img { opacity: 0.4; }
#thumbs .failed img { outline: 2px solid var(--warning); }
.sent-photo { max-width: 220px; border-radius: 8px; border: 1px solid var(--line); margin-top: 4px; align-self: flex-end; }
.heading { margin: 8px 0 4px; }
.katex { font-size: 1.05em; }

Check it works

Run npm start, open http://localhost:3000, choose Feedback, attach a photo of a page of written work, and ask for a check without typing the work out. For example, this page (a distribution slip on line 2):

Solve 2(x - 4) = 10 2x - 4 = 10 2x = 14 x = 7 check: 2(7) - 4 = 10 ✓

Your message

Your photo appears in your message, as a small image.

The reply

After about 10 to 20 seconds, a reply that speaks to the lines in the photo: which ones hold, the first one that does not and why, and what to practice.

A real reply, captured November 23, 2026, word for word:

You translated the equation into successive algebra steps and included a check line. I’ll read each line in order, then trace the first change that affects everything after it.

What holds

  • 2(x - 4) = 10 is the equation you were asked to solve.
  • In 2x - 4 = 10, the 2x part is carried correctly; the constant term is the part that changes incorrectly.
  • In 2x = 14, the move of adding the same quantity to both sides is the intended operation, but the value carried into it is off.
  • In x = 7, dividing by 2 is the intended final operation, but it is applied to the earlier value.
  • Your check line includes the proposed value and attempts substitution, but it changes the original grouped expression.

First issue

2x - 4 = 10 does not hold: this is a distribution error. The 2 must multiply both terms inside the parentheses, so the line should read 2x - 8 = 10, because 2(x - 4) = 2x - 2(4).

Then continue from that corrected line:

  • 2x - 8 = 10 leads to 2x = 18 after adding 8 to both sides.
  • Dividing both sides by 2 gives x = 9.

Your check, 2(7) - 4 = 10, does not hold as a check of the original equation: it uses 2x - 4 instead of keeping the parentheses. Using the corrected value in the original form gives 2(9 - 4) = 2 × 5 = 10.

Practice keeping the outside factor attached to every term inside parentheses, and preserve the parentheses when substituting into the original equation.

The reply arrives complete and checked. Nothing unchecked is ever shown. Every reply is written fresh, so yours will use different words.

Under the reply

Safety: clear, and the receipt: 1 turn · $0.05 · settled with the request id. The upload itself was free. receipts.jsonl gets one line for the turn.

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 stays private

The photo goes from the page to your server, then to Learn, never straight from the browser to Learn. It belongs to that learner and session, and expires 30 days after upload.

If something goes wrong

What you seeWhat it meansFix
400 on the uploadThe type, size or encoding is wrong.Send PNG, JPEG or WebP up to 8 MiB, as plain base64 with no data: prefix.
The reply asks you to type the workThe photo was not legible, or did not reach the turn.Check the photo shows the work clearly, and that its id is in quest.attachment_ids on that turn.
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 sessionYour workspace has less than ten turns' worth left (50¢).Add funds to your workspace, then prepare the session again.
403 DEVELOPER_POLICY_BLOCKEDThe 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_LIMITYour workspace reached its allowance or rate limit, and the turn was refused. An upload can also be refused with 429 DEVELOPER_CAPACITY_LIMIT at the per-learner and workspace upload limits.Respect the Retry-After header if it is there. Send a refused upload again after that time, or delete uploads you no longer need. 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.

The kit.

The repository

A start folder and the finish.

Open the kit

03-photos-of-work in learn-tutor-starter

Next

Your first tutor in ten minutes.

Start building