- AI APIs
- Reviews
- Node.js
Ollama structured output: classify app reviews locally
Use Ollama structured output with a Zod JSON schema to label app and extension reviews on your own machine, validate every answer and fix common failures.
- Author
- Extenify Team
- Published
- Reading time
- 13 min read

On this page
Ollama structured output lets a local model answer in JSON that follows a schema you define, which is exactly what review labeling needs. Instead of reading 2,000 store reviews to find out whether the latest version broke something, you ask a model running on your own machine to tag each one with a sentiment, one to three topics and a one-line bug summary, and you get back objects your code can count. Nothing leaves your machine, and the marginal cost per review is zero.
This guide builds that pipeline in Node.js for app and browser extension reviews: how the format parameter works, a label schema written once in Zod, a labeling script that validates every answer and retries once, a per-version summary, and the failures developers actually hit with Ollama structured output, from thinking models ignoring the format to JSON cut off halfway. It uses the ollama package 0.6.4 and zod 4.6.7 from npm.
Key takeaways
- Pass
format: "json"for any valid JSON, or a JSON Schema object for JSON with your fields and allowed values. Ollama's docs describe the second as the way to enforce "a specific structure".- Write the schema in Zod, convert it with
z.toJSONSchema(), and use the same Zod object to validate the reply. Validation is not optional.- Ollama recommends three things: put the schema in the prompt as well, set temperature to 0, and reuse the schema for validation.
- Check
done_reason. A reply that stopped at the token limit is cut-off JSON, and the default context is only 4k tokens on machines with under 24 GiB of VRAM.- Thinking models had a long-running bug where
formatwas ignored with thinking turned off. Run Ollama 0.34.4 or newer, whose notes say structured outputs on thinking models "now apply in a single pass."
What Ollama structured output does
Ollama's /api/chat endpoint takes a format parameter that "can be json or a JSON schema." The structured outputs page explains the difference:
format: "json"asks the model for valid JSON, but any JSON. The model decides the keys.format: <schema>constrains the reply to your schema: the keys, their types and, for anenum, the allowed values.
The feature arrived in December 2024, when Ollama's announcement post introduced it for the Python and JavaScript libraries and the REST API. It also works through the OpenAI-compatible endpoint with response_format, and with vision models. One limit matters if you plan to move work off your machine later: the docs state that "Ollama's cloud does not currently support structured outputs."
Why label reviews with a local model
Our guide to app review analysis with an LLM runs the same job through hosted APIs, where batch pricing makes 10,000 reviews cost less than a dollar. A local model is the better fit when:
- Reviews must not leave your infrastructure. Reviews contain names, emails people paste in anger and account details. Some teams cannot send them to a third-party API without a review.
- You re-run often. Changing a label definition means relabeling everything. Locally that costs time, not money.
- You want a stable model. A model you pulled does not get retired, as hosted models regularly are.
The trade-off is quality and speed: a small local model labels less accurately than a large hosted one, and a laptop is slower than a batch API. That is why this guide spends a section on measuring accuracy before you trust the numbers.
Step 1: Get reviews into one file
Labels are only useful next to the store, the version and the star rating, so start from a file that has them. Each store has its own source:
- Google Play: the Developer API returns the last week of reviews with the version code, and monthly CSV files hold the rest, as our Google Play review export guide shows.
- App Store: the App Store Connect API for your own apps, which needs an App Store Connect API key, or the public customer reviews feed, both covered in App Store review alerts.
- Chrome, Edge and Firefox: our Chrome extension review notifications guide covers each store, including the public Firefox ratings API.
Extenify merges reviews from all five stores into one stream for every app or extension you track, yours or a competitor's, and exports them as CSV or JSON from the Reviews tab on paid plans and during the free trial. The CSV has the columns this guide uses: platform, store, review_id, date, rating, author, version, helpful_votes, total_votes, language and body. Any file with review_id, platform, version, rating and body columns works with the scripts below.
Step 2: Define the labels once, as a Zod schema
A fixed set of labels is what makes the output countable. Free-text topics drift ("crash", "crashes", "app crashing") and cannot be trended across versions. Ollama's docs suggest defining the schema with Zod in JavaScript "so they can be reused for validation", and the prompt below also includes the schema as text, following the doc's tip that "it is ideal to also pass the JSON schema as a string in the prompt to ground the model's response."
// review-label.mjs: the labels, as one Zod schema that both Ollama and your code use.
import * as z from 'zod';
export const TOPICS = ['bug', 'performance', 'feature_request', 'pricing', 'ux', 'privacy', 'support', 'praise', 'other'];
export const Label = z.object({
sentiment: z.enum(['positive', 'neutral', 'negative']),
topics: z.array(z.enum(TOPICS)).min(1).max(3),
bug_summary: z.string().max(120).nullable(),
language: z.string(),
});
export const SCHEMA = z.toJSONSchema(Label);
export const PROMPT = `You label app and browser extension reviews for a product team.
Topics:
- bug: something is broken, crashes or gives wrong results
- performance: slow, laggy, heavy on memory or battery
- feature_request: asks for something the product does not do
- pricing: price, subscription, paywall, refunds
- ux: confusing, hard to find, layout or design complaints
- privacy: permissions, tracking, data collection
- support: contact, replies, account help
- praise: compliments with no other topic
- other: none of the above
Pick 1 to 3 topics. bug_summary is a short English summary of the bug, or null when there is no bug.
language is the ISO 639-1 code of the review text.
Return JSON that matches this schema:
${JSON.stringify(SCHEMA)}`;
This is the JSON Schema that z.toJSONSchema(Label) produced with Zod 4.6.7, and what Ollama receives as format:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"sentiment": { "type": "string", "enum": ["positive", "neutral", "negative"] },
"topics": {
"minItems": 1,
"maxItems": 3,
"type": "array",
"items": {
"type": "string",
"enum": ["bug", "performance", "feature_request", "pricing", "ux", "privacy", "support", "praise", "other"]
}
},
"bug_summary": { "anyOf": [{ "type": "string", "maxLength": 120 }, { "type": "null" }] },
"language": { "type": "string" }
},
"required": ["sentiment", "topics", "bug_summary", "language"],
"additionalProperties": false
}
Three design choices are worth copying. Every field is required, so a missing key is an error rather than a silent gap. Nullable fields (bug_summary) say "nothing to report" explicitly. And the topic definitions live in the prompt, because an enum restricts which words the model can pick, not what it understands them to mean.
Step 3: Label every review and validate the reply
The script reads the CSV, skips star-only ratings, sends one review per request with the schema as format, and validates the reply with the same Zod object. If the reply stopped at the token limit or fails validation, it tries once more, then records the review as failed instead of guessing. It needs ollama, zod and csv-parse, and a model you have pulled.
// label-reviews.mjs: label exported store reviews with a local model and Ollama structured output.
// Usage: OLLAMA_MODEL=<a model you pulled> node label-reviews.mjs reviews.csv > labels.jsonl
import { readFile } from 'node:fs/promises';
import { parse } from 'csv-parse/sync';
import ollama from 'ollama';
import { Label, SCHEMA, PROMPT } from './review-label.mjs';
const MODEL = process.env.OLLAMA_MODEL;
if (!MODEL) throw new Error('Set OLLAMA_MODEL to a model you pulled with `ollama pull`.');
async function labelReview(review) {
const messages = [
{ role: 'system', content: PROMPT },
{ role: 'user', content: `Stars: ${review.rating}\nReview: ${review.body.slice(0, 2000)}` },
];
for (let attempt = 1; attempt <= 2; attempt++) {
const res = await ollama.chat({
model: MODEL,
messages,
format: SCHEMA,
options: { temperature: 0, num_predict: 300 },
keep_alive: '15m',
});
if (res.done_reason === 'length') continue; // cut off mid-JSON: try once more
try {
const parsed = Label.safeParse(JSON.parse(res.message.content));
if (parsed.success) return parsed.data;
} catch {
// not JSON at all: fall through to the retry
}
}
return null;
}
const rows = parse(await readFile(process.argv[2], 'utf8'), { columns: true, skip_empty_lines: true });
let labeled = 0;
let failed = 0;
for (const row of rows) {
if (!row.body?.trim()) continue; // star-only ratings have no text to label
const label = await labelReview(row);
const meta = { review_id: row.review_id, platform: row.platform, version: row.version, rating: Number(row.rating) };
console.log(JSON.stringify(label ? { ...meta, ...label } : { ...meta, error: true }));
if (label) labeled++;
else failed++;
}
console.error(`${labeled} labeled, ${failed} failed validation twice`);
The settings each have a reason:
temperature: 0follows Ollama's tip for "more deterministic output". The same review should get the same label on every run, or your trends measure noise.num_predict: 300caps the reply. A label object is a few dozen tokens, so hitting the cap means something went wrong, anddone_reasonwill saylength.keep_alive: '15m'keeps the model loaded between requests. The API reference describes it as the "model keep-alive duration", and reloading a model for every review is the slowest part of a naive loop.- One review per request. Batching ten reviews into one prompt is faster, but one bad review then spoils ten labels, and the schema gets more complex.
- The star rating goes in the prompt. "Great app, but it crashes now" with one star is a bug report, not praise.
We checked the script's control flow against a stub of the /api/chat endpoint: valid replies were kept, a reply cut off with done_reason: "length" was retried, a reply with an empty topics array was rejected by Zod's .min(1) and retried, a non-JSON reply was retried, and a review that failed twice was written with error: true. That stub tells you nothing about label quality, which depends on your model and is the subject of Step 5.
Step 4: Count topics per store and version
Labels pay off when you compare them across versions and stores. This script turns the JSON Lines output into one line per store and version:
// topics-by-version.mjs: count labeled topics per store and version.
// Usage: node topics-by-version.mjs labels.jsonl
import { readFile } from 'node:fs/promises';
const lines = (await readFile(process.argv[2], 'utf8')).split('\n').filter(Boolean);
const groups = new Map();
for (const row of lines.map((line) => JSON.parse(line))) {
if (row.error) continue;
const key = `${row.platform} ${row.version || 'unknown'}`;
const group = groups.get(key) ?? { reviews: 0, negative: 0, topics: {} };
group.reviews++;
if (row.sentiment === 'negative') group.negative++;
for (const topic of row.topics) group.topics[topic] = (group.topics[topic] ?? 0) + 1;
groups.set(key, group);
}
for (const [key, group] of [...groups].sort()) {
const top = Object.entries(group.topics)
.sort((a, b) => b[1] - a[1])
.slice(0, 3)
.map(([topic, count]) => `${topic} ${Math.round((count / group.reviews) * 100)}%`);
const negative = Math.round((group.negative / group.reviews) * 100);
console.log(`${key.padEnd(24)} ${String(group.reviews).padStart(4)} reviews negative ${negative}% ${top.join(', ')}`);
}
Read the result the way you read ratings: a version whose bug share doubles against the previous version is the signal, not any single review. Run it on the reviews of a build that is still in a Google Play staged rollout and you can catch that before everyone has it. Our guide to reading review and rating trends covers how many reviews a version needs before a share means anything. To group similar bug summaries into recurring complaints, embed them and cluster them, as the pgvector guide shows.
Step 5: Measure accuracy before you trust the labels
A schema guarantees the shape of the answer, never that it is right. Before you put the numbers in a weekly report:
- Take a random sample of 100 to 200 reviews from several stores, languages and star ratings.
- Label them yourself, without looking at the model's answers.
- Compare. Count how often the sentiment matches and how often your main topic appears in the model's topics.
- Read every disagreement. Most come from one or two topic definitions that overlap, such as
uxandbugfor "the button does nothing". - Fix the definitions in the prompt, relabel the sample, and keep the version of the prompt that agrees with you most.
Try two or three models on the same sample. Smaller models are faster but tend to overuse a catch-all topic; the sample tells you which trade-off your data can live with. Re-run the sample whenever you change the model or the prompt.
Troubleshooting Ollama structured output
| Symptom | Likely cause | Fix |
|---|---|---|
| The reply is prose, not JSON, on a thinking model with thinking off | A bug tracked in ollama/ollama#14645, "format is ignored when think is disabled", reported on 0.17.6 and closed in July 2026; the reporter confirmed 0.31.2 fixed it | Upgrade. Ollama 0.34.4's notes add that structured outputs on thinking models "now apply in a single pass" |
JSON.parse fails on a reply that ends mid-string |
The reply hit num_predict or the context filled up; done_reason is length |
Shorten the input, raise num_predict, or raise the context with OLLAMA_CONTEXT_LENGTH; the default is 4k under 24 GiB of VRAM |
| Valid JSON, but a field is missing or extra | format was "json", not the schema, or the schema was passed as a string |
Pass the schema object itself, not JSON.stringify(schema) |
Valid JSON that Zod rejects (for example an empty topics array) |
Do not count on every JSON Schema keyword being enforced during generation; Ollama's docs do not list which are | Keep validating with Zod and retry once |
| Works locally, fails after moving to Ollama's cloud | The cloud "does not currently support structured outputs" | Keep labeling on your own hardware |
| You use the OpenAI SDK | Ollama's OpenAI-compatible API takes response_format instead of format |
Point the SDK at http://localhost:11434/v1/; it needs an API key value, which Ollama ignores |
| Labels are valid but wrong | Vague topic definitions, or a model too small for the task | Improve the definitions, add the star rating, compare models on your hand-labeled sample |
The thinking-model bug is worth understanding because it fails quietly. The issue's reporter explained that Ollama applied the format constraint only after the model's end-of-thinking token, and with thinking disabled the chat template had already closed the thinking block, so the constraint never engaged. Commenters reported the same symptom on several releases and models before the fix. If you pin an older Ollama on a server, test format with your exact model and think setting before relying on it.
Where Extenify fits
Labeling turns reviews into numbers; it does not collect them. Extenify does the collecting: it records ratings, rating counts, installs, versions and new reviews every day from the store listing data of the Chrome Web Store, Edge Add-ons, Firefox Add-ons, Google Play and the App Store, for your products and your competitors'. Alerts for rating drops, new low reviews and new versions go to email, Slack, Telegram, Discord or Teams, and the reviews export feeds the scripts above directly. It is an app review monitoring dashboard that needs no SDK; every plan starts with a 7-day free trial, no credit card required, and the pricing page lists what each plan tracks.
Frequently asked questions
What is the difference between format json and a JSON schema in Ollama?
format: "json" only guarantees valid JSON; the model chooses the keys and values. A JSON Schema object constrains the reply to your fields, types and allowed enum values, which is what you need when code reads the result.
Does Ollama structured output work with every model?
Ollama constrains generation to the schema rather than relying on the model to follow instructions, but label quality still varies by model, and thinking models had a bug where the format was ignored with thinking off. Use a recent Ollama and test your model on a hand-labeled sample.
Why is my Ollama structured output not valid JSON?
Usually the reply was cut off: check whether done_reason is length, then shorten the input or raise num_predict and the context length. On older versions with thinking models, upgrade Ollama.
Can I use Ollama structured output with the OpenAI SDK?
Yes. Ollama's docs list structured outputs through the OpenAI-compatible API via response_format. Set the base URL to http://localhost:11434/v1/ and pass any API key value.
Do I still need to validate if I pass a schema?
Yes. Validate every reply with the same schema, such as Zod's safeParse, and treat a failure as a retry or an error. A schema in the request is a strong hint to generation, not a contract your code can skip checking.
Is a local model accurate enough for review analysis?
For sentiment and broad topics, often yes; for subtle categories, it depends on the model. Measure agreement on 100 to 200 reviews you labeled yourself before you trust trend numbers.
Summary
Ollama structured output turns a local model into a review labeler your code can rely on: define the labels once in Zod, pass the generated JSON Schema as format, put the same schema and clear topic definitions in the prompt, set temperature to 0, and validate every reply with a single retry. Check done_reason for cut-off replies, run a recent Ollama if you use thinking models, and measure accuracy on a hand-labeled sample before the numbers reach a report. Then count topics per store and version, and let the change between versions, not individual reviews, tell you what to fix next.
Image credits
- Cover photo: A grey-white llama in a field, taking shade under the eaves of a wooden shed by Gary Jones on the WordPress Photo Directory, CC0.


