The supplier's email gives the price as $19.00. The catalogue stores prices in whole cents, but the model writes 19, the form saves it right away, and The Dancer appears in the catalogue at $0.19. This lesson shows how to add AI to a form so that this can't happen. The AI works inside the form you already have, not in a separate chat window. It suggests field values, drafts text and gives warnings. Then a person decides.
Imagine an intern at the Bookshop who fills in the new-book form in pencil. The intern is quick, but sometimes misreads. The admin checks the form, erases what's wrong, then signs it with a pen. In this picture, the intern is the AI, and the pencil entries are suggestions that can still be erased. The pen is the Save button, and the admin keeps it.
Four ways AI helps a form
| Way | Example in the "Add book" form |
|---|---|
| Smart autocomplete | The admin types "The Dancer", the author field suggests "Ahmad Tohari" |
| Content suggestions | A "Write synopsis" button drafts a synopsis in the textarea |
| Extraction | A supplier email is pasted, the AI fills in title, author, price, stock |
| Semantic validation | The AI warns when the synopsis mentions Belitung although the book is about Dukuh Paruk |
So AI makes filling in a form easier through smart autocomplete, semantic validation (checking that the input makes sense) and content suggestions. AI does not help by filling every field and saving on its own without the user, or by replacing the form with a chat.
Autocomplete and semantic validation are called with a debounce: the code waits until the admin stops typing for about half a second, then sends the request. That way there isn't a request on every letter.
Extracting fields from free text
The Dancer arrives with an email from the supplier:
Hi, this week's delivery: The Dancer by Ahmad Tohari, 3 copies.
Retail price $19.00. It's about Srintil, a ronggeng dancer in a small hamlet,
up to the political turmoil of 1965. If anything is missing, call me on 07700 900000
or email [email protected]. Regards, Darto
The server asks the model to turn that email into JSON with Structured Outputs: an OpenAI feature that makes the model's answer always follow a schema (a description of the JSON's shape). The schema goes in text.format, as in the Prompt Engineering lesson:
const SCHEMA = {
type: "object",
properties: {
title: { type: "string" },
author: { type: "string" },
price: { type: ["integer", "null"] }, // whole cents ($19.00 = 1900), null when not mentioned
stock: { type: ["integer", "null"] },
summary: { type: "string" },
},
required: ["title", "author", "price", "stock", "summary"],
additionalProperties: false,
};
const r = await client.responses.create({
model: "gpt-6-luna",
reasoning: { effort: "none" },
store: false, // don't keep this response at OpenAI
instructions: "Take the book data from <email>. If a value isn't mentioned, use null. Don't guess.",
input: `<email>${sanitize(removePersonalData(email))}</email>`,
text: { format: { type: "json_schema", name: "new_book", strict: true, schema: SCHEMA } },
});
const suggestion = JSON.parse(r.output_text);
["integer", "null"]means a whole number or null. The model may answer null, so it isn't forced to invent a price the email doesn't mention.- The "Don't guess" instruction matters. OpenAI's Structured Outputs guide says the model will always try to follow the schema, and that can lead to hallucinations (made-up answers) when the text doesn't fit the schema.
- Before the email goes into
input, two functions clean it:sanitizeescapes<and>(the Prompt Engineering lesson), andremovePersonalDatais covered in the Privacy section. - Here is an example answer. In the Lab, the answer is a stand-in (a hand-written replacement answer), not a model's output:
{"title":"The Dancer","author":"Ahmad Tohari","price":1900,"stock":3,"summary":"Srintil, a ronggeng dancer in a small hamlet, up to the political turmoil of 1965."}
Validating on the server
The schema guarantees the shape: price is always an integer or null. But the same guide says Structured Outputs can still contain mistakes. If the model writes 19 for "$19.00", the schema accepts it, because 19 is an integer too. So the contents are still checked on the server, even with strict: true in place. This validate function checks the shop's rules and returns a list of problems:
function validate(d) {
const problems = [];
if (!d.title.trim() || d.title.length > 200) problems.push("title empty or longer than 200 characters");
if (d.price !== null && (d.price < 100 || d.price > 1000000)) problems.push(`price ${d.price} cents outside $1 to $10,000`);
if (d.stock !== null && (d.stock < 0 || d.stock > 10000)) problems.push(`stock ${d.stock} makes no sense`);
return problems;
}
| Model's answer | validate |
What happens |
|---|---|---|
price: 1900, stock: 3 |
[] |
the fields are filled as suggestions |
price: 19, stock: 3 |
["price 19 cents outside $1 to $10,000"] |
the price field is marked red, the admin fixes it |
The same validation runs again on POST /books (the route that saves a book), because the admin can mistype too. A request that fails validation is answered with the status 422 and the list of problems.
The human stays in control
AI suggests, it never saves. The extraction endpoint (the server route that asks the model to read the email) only returns { suggestion, problems }. There's no INSERT (the SQL command that adds a row to the database) in it. The form has three rules:
- Fields the AI filled are marked "AI suggestion" until the admin edits or accepts them.
- Save only runs when the admin presses it. Nothing auto-submits (sends the form by itself) once extraction finishes.
- The database records who saved the book in the
created_bycolumn: the admin, not "the AI".
That way a model's misreading stops on the admin's screen and never reaches the catalogue that customers see.
Writing a synopsis: streaming into the textarea, with Cancel
Writing a synopsis takes a few seconds. To keep the admin from staring at an empty box, the text is streamed into the textarea piece by piece, as in the Streaming Responses lesson. A textarea is a text box that can hold many lines. There's also a Cancel button. In this code, readSSE is the stream-reading function from that lesson. cancelButton is the Cancel button on the page:
let control = null;
async function writeSynopsis(textarea, book) {
const before = textarea.value; // to bring back on Cancel
control = new AbortController();
textarea.readOnly = true;
textarea.value = "";
try {
const res = await fetch("/api/admin/synopsis", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: book.title, author: book.author, summary: book.summary }),
signal: control.signal,
});
await readSSE(res.body, (ev) => { textarea.value += ev.text; }); // the server sends data: {"text":"..."}
} catch (err) {
if (err.name !== "AbortError") throw err;
textarea.value = before; // Cancel: the admin's text comes back whole
} finally {
textarea.readOnly = false; // once done, the admin is free to edit
}
}
cancelButton.onclick = () => control?.abort();
readOnly(it can only be read) while streaming keeps the admin's typing from mixing with the incoming text.- Cancel stops the
fetchthroughAbortController, thencatchbrings back the previous text. The textarea isn't left holding half a sentence. - Only the title, author and summary are sent to the server, not the whole email.
Cancel is not the only way this stream can stop. The code above doesn't handle two other failures yet:
- The network drops: the error isn't an
AbortError, sothrow errruns before the old text is brought back. The textarea is left empty. - The server answers 500 or 429:
fetchthrows nothing.readSSEreads the error body, finds no event, and the textarea stays empty with no message.
So check res.ok (true only for the statuses 200 to 299), and bring the old text back on every failure. The try, catch and finally parts of writeSynopsis become the code below. messageEl is the element that shows the error message:
try {
const res = await fetch("/api/admin/synopsis", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: book.title, author: book.author, summary: book.summary }),
signal: control.signal,
});
if (!res.ok) throw new Error(`HTTP ${res.status}`); // fetch doesn't throw on its own for 4xx and 5xx
await readSSE(res.body, (ev) => { textarea.value += ev.text; });
} catch (err) {
textarea.value = before; // Cancel, a dropped network or HTTP 500: the old text comes back
if (err.name !== "AbortError") messageEl.textContent = "The synopsis could not be written. Try again.";
} finally {
textarea.readOnly = false;
}
Privacy: what you send to the provider
Everything in input goes from the Bookshop server to OpenAI. The supplier email at the start of this lesson carries Mr. Darto's phone number and email address. Nobody needs them to fill in book data, so remove them before sending. This function finds them with regexes (patterns for searching text) and replaces them with markers:
function removePersonalData(text) {
return text
.replace(/(\+44|0)7\d{3}[-\s]?\d{3}[-\s]?\d{3}/g, "[number hidden]")
.replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g, "[email hidden]");
}
The phone pattern above matches only the most common formats. Tested in Node 24, these three numbers still go out unhidden: "+44 7700 900123", "447700 900123" and "07700.900.123". And the order number "107700900123" becomes "1[number hidden]". The pattern below catches all three phone numbers and doesn't change the order number:
const PHONE_PATTERN = /(?<!\d)(?:\+44[ -]?|44|0)7\d{3}(?:[ .-]?\d{3}){2}(?!\d)/g;
console.log("Call +44 7700 900123 or 07700.900.123, order 107700900123".replace(PHONE_PATTERN, "[number hidden]"));
// Call [number hidden] or [number hidden], order 107700900123
According to OpenAI's "Your data" page (checked October 2026), three rules apply:
- API data isn't used to train models unless you opt in.
- Abuse monitoring logs may be kept for up to 30 days.
- The Responses API keeps responses for at least 30 days, unless the request uses
store: false.
Send only what's needed, and say in the shop's privacy policy that certain text is processed by an AI provider.
⚠️ Auto-save, trusting the schema, and sending too much
- Auto-submitting. Extraction that saves right away lets a price of 19 cents into the catalogue. AI only fills suggestions, and a person presses Save.
- Trusting that schema means correct.
strict: trueguarantees types, not values. Validate number ranges and text lengths on the server: in the extraction endpoint and inPOST /books. - Sending everything to the provider. Phone numbers, emails and customer data aren't needed to write a synopsis. Remove them first, and use
store: false. - Streaming without Cancel. The admin has to wait until the end, or her text in the textarea gets overwritten. Provide a Cancel that brings the old text back.
TL;DR: AI in a form suggests, a person saves. Four ways: smart autocomplete (with a debounce: the request goes out once the user stops typing), content suggestions (a "Write synopsis" button), extracting fields from free text, and semantic validation (checking that the input makes sense). Extraction uses Structured Outputs, which makes the model's answer follow a schema (a description of the JSON's shape): text.format, json_schema, strict: true, optional fields as ["integer", "null"], and a "don't guess" instruction. But the schema only guarantees the shape: a price of 19 cents for "$19.00" still passes it. So the server validates ranges and lengths and answers 422 when something is wrong. The extraction endpoint saves nothing, and the shop's admin presses Save. Long drafts stream into a readOnly textarea (no typing while it streams), with a Cancel button (AbortController) that brings the old text back. Before sending to the provider, remove personal data (phone numbers, emails) and use store: false (don't keep the response at OpenAI). By default OpenAI doesn't train on API data, but logs may be kept for up to 30 days.
⚡ AI works inside the form
Meaning: AI helps inside the form you already have, not in a chat window. There are four ways: smart autocomplete (suggesting a field value as you type), content suggestions (for example a draft synopsis), extracting fields from free text (for example the title, price and stock from a supplier's email), and semantic validation (checking that the input makes sense). AI only suggests; a person saves.
⚡ A schema guarantees shape, not content
Write:
function validate(d) {
const problems = [];
if (!d.title.trim() || d.title.length > 200) problems.push("title empty or longer than 200 characters");
if (d.price !== null && (d.price < 100 || d.price > 1000000)) problems.push(`price ${d.price} cents outside $1 to $10,000`);
if (d.stock !== null && (d.stock < 0 || d.stock > 10000)) problems.push(`stock ${d.stock} makes no sense`);
return problems;
}
Guess first: the model turns a supplier's email into JSON that follows a schema (a description of the JSON's shape), with price typed as an integer or null. Prices are stored in cents, and the model writes 19 for "$19.00". Does a schema with strict: true (the answer always follows the schema) reject it?
No. 19 is an integer (a whole number) too, so the schema accepts it. The contents must be checked on the server, for example with the validate function above: a price under 100 cents goes on the list of problems.
Meaning: validate checks the model's JSON (d) against the shop's rules that a schema doesn't guarantee: the title's length, the price range and the stock range. The same validation runs again on POST /books (the route that saves a book), and a request that fails it is answered with the status 422 and the list of problems.
⚡ The Save button stays human
Meaning: The extraction endpoint (the server route that asks the model to read the email) only returns { suggestion, problems }. There's no INSERT (the SQL command that adds a row to the database) in it. Fields the AI filled stay marked "AI suggestion" until the admin, who runs the shop's catalogue, accepts them. Then she presses Save herself.
⚡ Send only what's needed
Meaning: Everything in the request's input field goes to the provider (OpenAI). Remove phone numbers and emails before sending, and use store: false (don't keep the response at OpenAI).