Helper functions cheat sheet¶
Every lab imports its helpers from common/llm.ts. They work the same with Claude, Gemini and OpenAI.
Info
The import says .js even though the file is llm.ts. That's how Node's module system names files; tsx finds the TypeScript file for you.
ask(): send text, plus any images or PDFs¶
const answer = await ask("In one sentence, what does this chart show?",
{ images: ["data/chart_revenue.png"] });
| Option | What it does |
|---|---|
prompt (first argument) |
Your instruction or question |
images: [...] |
File paths or Buffers. PNG, JPG and PDF work everywhere; audio works with Gemini |
system: "..." |
Standing instructions, such as a role or a policy |
maxTokens: 2000 |
The longest answer allowed |
verbose: false |
Hides the timing line |
cache: false |
Always calls the model, even if a saved answer exists |
Every helper is async, so put await in front of it.
askJson(): get structured data back¶
import { z } from "zod";
const Receipt = z.object({
merchant: z.string(),
date: z.string().nullish(), // may be missing
total: z.number(),
});
const r = await askJson("Extract this receipt exactly as printed.",
{ images: ["data/images/receipt_cafe.png"], schema: Receipt });
console.log(r.merchant, r.total); // typed: your editor knows the fields
- With
schema, you get a checked object back; without it, whatever JSON the model returned. - If the JSON doesn't match the schema, the helper sends the error back to the model once to fix it, then throws a
ZodErrorif it still fails.
| Zod | Means |
|---|---|
z.string(), z.number(), z.boolean() |
A required field of that type |
.nullish() |
The field may be null or missing |
z.array(Item) |
A list of Items |
z.enum(["APPROVE", "HUMAN_REVIEW"]) |
One of these exact values |
Invoice.extend({ due_date: z.string().nullish() }) |
An existing schema plus one more field |
transcribe(): speech to text¶
const tr = await transcribe("data/meeting.wav"); // local Whisper, on your laptop
const tr2 = await transcribe("data/meeting.m4a", "openai"); // or "gemini"
console.log(tr.text, tr.segments.slice(0, 3), tr.seconds, "seconds");
Each segment is { start, end, text }, with times in seconds. For local Whisper, .m4a and .mp3 files are converted to WAV first (with ffmpeg-static).
usageSummary(): what your calls cost¶
Prints a table of every call so far, with the model, seconds taken, input tokens, output tokens, number of images, and whether it was a saved answer.
Other helpers¶
| Helper | File | What it does |
|---|---|---|
show(path) |
common/llm.ts |
Prints an image's full path so you can Ctrl/Cmd + click it |
embedTexts(texts) |
common/embed.ts |
Text to vectors (MiniLM, on your laptop) |
clipEmbedImages(paths), clipEmbedTexts(texts) |
common/embed.ts |
Pictures and words to vectors on one map (CLIP) |
topK(query, vectors, k) |
common/embed.ts |
The k closest vectors, best first, with scores |
pdfBlocks(file) |
common/pdf.ts |
Every text block and picture position in a PDF, with page numbers |
renderPage(file, page) |
common/pdf.ts |
A picture of one PDF page, saved as PNG |
Switching provider or model¶
Edit .env, then run the step again:
LLM_PROVIDER=gemini # anthropic | gemini | openai
GEMINI_MODEL=... # only if the default name stops working
Patterns from the labs¶
| Pattern | Where you used it |
|---|---|
| Ask for data "exactly as printed", then check it with code | Lab 2 |
| Extract the table first, calculate in code | Lab 2 |
| Fill a schema from a transcript | Lab 3 |
| Describe figures in words so they can be searched | Lab 4 |
| "Answer only from the sources, cite [S1], else say not in the sources" | Lab 4, capstone |
| Treat text inside images as data; enforce the policy in code | Lab 5 |
| Hide personal data on your laptop before any API call | Lab 5 |
| Score against an answer key after every change | Lab 5 |