From ff5ae76a33ef1c4c96dd3fff13e352e44828e339 Mon Sep 17 00:00:00 2001 From: 404oops Date: Tue, 13 Oct 2026 14:50:33 +0200 Subject: [PATCH] Complete category cleanup recipe and runnable playground --- src/docs/src/examples.js | 6 + .../clean-up-imported-categories.html | 58 ++++++ .../recipes/clean-up-imported-categories.md | 55 +++--- .../clean-up-imported-categories.test.mjs | 168 +++++++++++++----- 4 files changed, 220 insertions(+), 67 deletions(-) create mode 100644 src/docs/src/playground/examples/clean-up-imported-categories.html diff --git a/src/docs/src/examples.js b/src/docs/src/examples.js index 2e27f19cc..94edb16f3 100644 --- a/src/docs/src/examples.js +++ b/src/docs/src/examples.js @@ -331,6 +331,12 @@ const examples = [ slug: 'ai-list-model-providers', source: '/playground/examples/ai-list-model-providers.html', }, + { + title: 'Suggest categories for imported labels', + description: 'Ask AI to map messy spreadsheet category labels to a fixed list of categories with Puter.js. Run and experiment with this example in the playground.', + slug: 'clean-up-imported-categories', + source: '/playground/examples/clean-up-imported-categories.html', + }, ], }, { diff --git a/src/docs/src/playground/examples/clean-up-imported-categories.html b/src/docs/src/playground/examples/clean-up-imported-categories.html new file mode 100644 index 000000000..3c1ea41c0 --- /dev/null +++ b/src/docs/src/playground/examples/clean-up-imported-categories.html @@ -0,0 +1,58 @@ + + +
Asking for suggestions...
+ + + + diff --git a/src/docs/src/recipes/clean-up-imported-categories.md b/src/docs/src/recipes/clean-up-imported-categories.md index 1ea64501f..06dabd593 100644 --- a/src/docs/src/recipes/clean-up-imported-categories.md +++ b/src/docs/src/recipes/clean-up-imported-categories.md @@ -37,16 +37,13 @@ what it holds before sending it anywhere. ## Ask for Suggestions -Send the distinct labels with the categories your app uses: +Send the distinct labels with the categories your app uses. This first try +takes the labels straight from the sample rows: -```js +```js;clean-up-imported-categories const CATEGORIES = ['Groceries', 'Dining', 'Transport', 'Income', 'Shopping', 'Other']; -async function proposeMapping (labels) { - if ( labels.length === 0 ) { - return { mapping: new Map(), problems: [] }; - } - +async function suggestCategories (labels) { const response = await puter.ai.chat([ { role: 'system', @@ -83,17 +80,24 @@ async function proposeMapping (labels) { }, }); - return parseProposal(response?.message?.content, labels); + return response?.message?.content; } + +const labels = [...new Set(rows.map(row => row.category))].sort(); +const reply = await suggestCategories(labels); ``` -The [`outputFormat`](/AI/chat/) schema asks for JSON that only uses the given -labels and categories, and [`normalize: true`](/AI/chat/#response-normalization) -makes the reply text a string for every model. To pick a model other than the -default, pass [`model`](/AI/chat/) with a name from the -[AI models list](https://developer.puter.com/ai/models/). Not every model -enforces the schema strictly, and a label can contain instructions, so the next -step checks the reply. +The reply is JSON text such as +`{"mappings":[{"label":"groceries","category":"Groceries"}]}`. The +[`outputFormat`](/AI/chat/) schema asks for JSON that only uses the given labels +and categories, and [`normalize: true`](/AI/chat/#response-normalization) makes +the reply text a string for every model. All the options are listed on +[`puter.ai.chat()`](/AI/chat/). Not every model enforces the schema strictly, +and a label can contain instructions, so the next step checks the reply. + +To try this request, run the code block above in the playground. It sends the +sample labels and shows the raw reply as text. The rest of this recipe checks +that reply and turns it into a review the user approves. ## Check the Proposal @@ -143,9 +147,12 @@ function parseProposal (content, labels) { ## Prepare the Review -The `prepareReview()` function checks the rows before anything is sent. The -cleaned category goes in a new `cleanCategory` column, so a file that already -has one is rejected. Each label is asked about once, exactly as written, so +The `prepareReview()` function checks the rows before it sends anything, then +calls `suggestCategories()` itself unless you pass in a reply you already have. +A reply passed in is checked like any other, so a missing or malformed one +leaves every label for the user without a new request. The cleaned category +goes in a new `cleanCategory` column, so a file that already has one is +rejected. Each label is asked about once, exactly as written, so `'Groceries '` is its own label and a missing category is `''`. The limits keep the request small and the review short enough to actually check. @@ -182,7 +189,7 @@ function distinctLabels (rows) { return labels; } -async function prepareReview (rows) { +async function prepareReview (rows, reply) { if ( rows.length === 0 ) { throw new Error('There are no rows to clean up.'); } @@ -191,7 +198,9 @@ async function prepareReview (rows) { let proposal; try { - proposal = await proposeMapping(labels); + // Only ask the AI when no reply was passed in, not when one was passed as undefined. + const content = arguments.length < 2 ? await suggestCategories(labels) : reply; + proposal = parseProposal(content, labels); } catch ( error ) { const reason = error?.message ?? error?.error?.message ?? 'the request failed'; proposal = { @@ -212,10 +221,12 @@ async function prepareReview (rows) { } ``` -Prepare the review from the parsed rows: +In your app, pass only the parsed rows. `await prepareReview(rows)` checks them +and then makes one request, or throws without a request if they are invalid. +For the sample rows, reuse the reply from the first try instead of asking again: ```js -const review = await prepareReview(rows); +const review = await prepareReview(rows, reply); ``` The review is plain data. If the AI leaves out `Groceries ` and suggests an diff --git a/src/docs/src/recipes/clean-up-imported-categories.test.mjs b/src/docs/src/recipes/clean-up-imported-categories.test.mjs index 0b916306b..327068b52 100644 --- a/src/docs/src/recipes/clean-up-imported-categories.test.mjs +++ b/src/docs/src/recipes/clean-up-imported-categories.test.mjs @@ -5,8 +5,10 @@ import { describe, expect, it, vi } from 'vitest'; // Executes the recipe's own JS blocks, in order, so the tests cover exactly the // code readers copy. The context has no DOM and only a mocked `puter.ai.chat`. const markdown = readFileSync(new URL('./clean-up-imported-categories.md', import.meta.url), 'utf8'); -const source = [...markdown.matchAll(/^```js\n([\s\S]*?)^```$/gm)].map(([, code]) => code).join('\n'); -const topLevelNames = [...source.matchAll(/^(?:async )?(?:function|const) (\w+)/gm)].map(([, name]) => name); +const blocks = [...markdown.matchAll(/^```js(?:;[\w-]+)?\n([\s\S]*?)^```$/gm)].map(([, code]) => code); +const source = blocks.join('\n'); +// The first try is every block up to and including the one with the first AI call. +const firstTry = blocks.slice(0, blocks.findIndex(code => code.includes('puter.ai.chat(')) + 1).join('\n'); const reply = mappings => ({ message: { content: JSON.stringify({ mappings }) } }); const plain = value => JSON.parse(JSON.stringify(value)); @@ -24,18 +26,89 @@ const sampleReply = () => reply([ ]); /** - * Runs every block as one async body, which also prepares and applies the - * recipe's sample review, and returns its top-level declarations. + * Runs the blocks as one async body, which for the full source also prepares + * and applies the recipe's sample review, and returns its top-level declarations. */ -async function loadRecipe (chat = vi.fn(async () => sampleReply())) { +async function loadRecipe (chat = vi.fn(async () => sampleReply()), code = source) { + const names = [...code.matchAll(/^(?:async )?(?:function|const) (\w+)/gm)].map(([, name]) => name); const context = vm.createContext({ puter: { ai: { chat } } }); const recipe = await vm.runInContext( - `(async () => {\n${ source }\nreturn { ${ topLevelNames.join(', ') } };\n})()`, + `(async () => {\n${ code }\nreturn { ${ names.join(', ') } };\n})()`, context, ); return { recipe, chat }; } +const expectLabelsOnly = (recipe, chat) => { + for ( const call of chat.mock.calls ) { + const [messages, options] = plain(call); + expect(JSON.parse(messages[1].content)).toEqual(SAMPLE_LABELS); + const { label, category } = options.outputFormat.schema.properties.mappings.items.properties; + expect(label.enum).toEqual(SAMPLE_LABELS); + expect(category.enum).toEqual(plain(recipe.CATEGORIES)); + + const sent = messages.map(message => message.content).join('\n'); + for ( const row of recipe.rows ) { + expect(sent).not.toContain(row.description); + expect(sent).not.toContain(row.amount); + } + } +}; + +describe('first try', () => { + it('runs on its own and returns the reply text for the sample labels', async () => { + const { recipe, chat } = await loadRecipe(undefined, firstTry); + + expect(chat).toHaveBeenCalledTimes(1); + expectLabelsOnly(recipe, chat); + expect(recipe.reply).toBe(sampleReply().message.content); + expect(recipe.prepareReview).toBeUndefined(); + }); +}); + +// The playground companion for the first try, run with a stub element that only accepts text. +const companionHtml = readFileSync(new URL('../playground/examples/clean-up-imported-categories.html', import.meta.url), 'utf8'); +const companionScript = companionHtml.match(/