Structured JSON outputs with Ollama

Structured outputs make a self-hosted Ollama model return JSON that matches a schema you define, which suits extraction and automation. This page covers how to set it up, validate results and plan around the cloud gap.

On this page

Structured JSON outputs with Ollama for extraction and automation

Ollama enforces a JSON schema on model responses through its structured outputs feature, so a downstream system receives fields and types it can parse instead of free text it has to guess at. Teams reach for this when a model's answer feeds a database row, a ticket, a workflow step or another service: invoice fields pulled from a scanned document, support messages sorted into categories, or records normalized before they enter a system of record. The feature is part of the local Ollama server. The Ollama structured outputs docs state that Ollama's cloud does not currently support structured outputs, so a design that depends on schema-constrained responses must run against a server you operate, not against direct cloud inference.

Before building, decide what the schema is responsible for. Keep the schema to the fields downstream systems actually use, mark which fields are required, and choose types that match the target system, such as enumerations for status values rather than open strings. Deeply nested or highly optional schemas increase the chance that a model satisfies the format while returning weak content, so test extraction quality on real documents from your own data set, not only on sample prompts. Record the schema in version control next to the application code that consumes it, because a schema change is an interface change that other teams will depend on.

Treat schema conformance as a contract you verify, not a guarantee you assume. Validate every response on the client side against the same schema, handle parse and validation failures explicitly with a retry limit or a review queue, and log rejected responses without storing sensitive field values in plain text. Confirm with your Ollama version and model which schema features your build supports, since capabilities change across releases, and check the release notes before each upgrade. Plan a test set with known correct outputs and rerun it after every model, quantization or Ollama version change, so a regression appears in your pipeline before it reaches production records.

How to set up structured outputs on a self-hosted Ollama server

This sequence takes a local Ollama server from a running default install to a model that returns JSON matching a schema you define, checked by your own code before any downstream system uses it. Your platform team owns each step, and the closing check shows whether the setup holds up against malformed and edge-case input.

  1. Confirm the server runs locally

    Start Ollama on the host that will serve the model and confirm it listens on 127.0.0.1 port 11434, the default bind address. Send a simple request to the local REST API from the same host and check that a response returns. If the server must accept calls from other machines, set the bind address with the OLLAMA_HOST environment variable and place authentication in front of it, because the local API does not require authentication. Done means a plain prompt returns text from the expected model on the expected host.

  2. Pick a model and confirm structured output support

    Choose a model that your approved catalog allows and pull it to the model storage location your team has planned. Check the model's documentation and test it directly, because structured output support depends on the model and not only on the Ollama version. Confirm the model license covers your use. Ask the model's publisher or your vendor contact to confirm any capability you cannot verify in your own environment. Done means the model is listed in your catalog and returns valid JSON for a sample schema on your hardware.

  3. Define the JSON schema

    Write a JSON Schema that describes the fields your application needs, their types, which fields are required and which values are allowed. Keep the schema small and flat where you can, since each added nested object or optional field gives the model more room to produce output your downstream system does not expect. Store the schema in version control next to the application code so changes are reviewed. Done means the schema file validates as a schema and a sample record that should pass matches it.

  4. Send the request with the format parameter

    Call the chat or generate endpoint of the local REST API, or the equivalent SDK method, and pass your JSON schema in the format parameter. Set the prompt so the model knows what to extract and that the output must match the schema. Keep the temperature low for extraction tasks so output is more consistent across runs. Use the same request shape in test and production so results are comparable. Done means the call returns a response body with the expected top-level structure.

  5. Validate the response in your application

    Do not treat the model output as trusted. Parse the response string and validate it against the same JSON Schema in your application code, using a validator library for your language. Reject or retry responses that fail parsing or validation, and log the failure with a request identifier so your team can trace it. Decide in advance what your application does on repeated failure, such as sending the item to a queue for human review. Done means every stored record has passed validation and every failure is logged.

  6. Test with malformed and edge-case input

    Build a test set that includes empty fields, very long text, text in unexpected languages, instructions embedded in the input, numbers written as words, and inputs that contain no matching data. Run each case through the full path and confirm that the output still parses and passes schema validation, or that your application rejects it cleanly. Record the pass and fail counts and repeat the run after any model, schema or prompt change. Done means the test set passes on the target model and the results are stored with the schema version.

  7. Document the setup and keep the cloud off

    Record the Ollama version, model name and version, schema version, bind address, and the validation rules in a runbook kept with your other configuration. Set OLLAMA_NO_CLOUD=1 or the equivalent server configuration if you want to prevent cloud features, and confirm the setting is active. Note that Ollama's cloud does not support structured outputs, so any cloud-hosted call must use a different approach. Done means another engineer can rebuild the same setup from the runbook and reproduce the test results.

Which configuration options fit which extraction workload

This table compares the output controls available for structured extraction on a self-hosted Ollama server, from plain JSON mode to a full schema, along with schema shape and sampling settings. Read each row as a trade-off: the more constraint you ask for, the more predictable the output shape, but the more you need to test the schema and the model together.

OptionWhen it fitsCost in reliability or latency
Plain JSON mode (format set to json)Exploratory extraction where your code tolerates loose field names and you will validate every response anywayOutput is valid JSON but field names and nesting can drift between calls, so client-side checks carry most of the load
Full JSON schema in the format parameterProduction extraction feeding a database, queue or downstream tool that expects fixed keys and typesConstrains output to the schema, but the schema is still passed with every request and must be tested against each model you run
Flat schema with simple field typesRecords with a few scalar fields such as dates, amounts, identifiers and short textFewest failure points; the model has less room to misplace values, which usually keeps results stable
Nested objects and arraysInvoices with line items, documents with repeated sections or entities with sub-recordsMore structure to fill correctly, so omissions and misplaced nested values become more likely; test with real samples
Required fields versus optional fieldsFields your pipeline cannot process without, such as an identifier or a total; optional for fields often absent in source documentsMarking too many fields required can push the model to invent values for missing data, so mark only what the source must contain
Low temperature (near deterministic sampling)Repeatable extraction where the same document should yield the same output across runsReduces variation between runs but does not guarantee correct values; check accuracy against a labeled sample
Higher temperature or wide samplingGenerating varied text alongside extraction, which is rarely needed in a pure extraction stepIncreases run-to-run variation in field values and can reduce consistency; avoid for pipelines that compare results

Designing schemas that models fill reliably

Schema design decides how often a model returns usable output, so treat the schema as part of the prompt rather than as a formatting afterthought. Keep each schema small, with only the fields your downstream system needs. Every extra field is another value the model must produce correctly on every call. Give fields descriptive names such as invoice_due_date instead of date2, and add a short description to each property, because the description is the main place where you tell the model what a value means and how to format it.

Mark fields as required only when the downstream step cannot proceed without them, and make the rest optional with a clear rule for when to leave them empty. For closed sets such as document types, currency codes or approval states, use an enum so the model chooses from known values instead of inventing labels. Avoid deep nesting when a flat object works. Nested arrays of objects with several levels are harder for a model to fill consistently, and a flat list with a type field is often easier to validate and to read in logs.

Schema complexity changes model behavior, so test each schema before it reaches production. Assemble a set of representative documents that includes clean inputs, incomplete inputs, scanned or messy text, and cases where the correct answer is null or unknown. Run the schema through the format parameter against each document on the exact model tag and settings you plan to use, then record which fields are missing, wrong or overfilled. Repeat the run after any change to the schema, the prompt or the model version, because a small edit can shift results for a field you did not touch.

Keep the client-side validation step in the test, not only the model run. Confirm that your validator rejects bad output and that your error handling routes those cases to a retry, a review queue or a fallback. Ask your team or partner to document the test set, the pass criteria and the results for each schema version, so that reviewers can see how the output was checked. Confirm with Ollama's structured outputs documentation how the current release handles the schema keywords you plan to use.

How a schema-constrained request moves through your stack

The flow starts in your client application, which sends a prompt and a JSON schema to the Ollama server on your internal network. Ollama constrains the model's generation to that schema, and the response returns to the client. The client parses and validates the output against the same schema before anything reaches a downstream system, so only records that pass validation are written. Check that the Ollama server stays inside the trust boundary, that the validation step cannot be skipped, and that failed responses are retried or routed to review rather than passed through.

Schema-constrained requests stay inside the Ollama trust boundary until the client validates them.

Why client-side validation still matters

Schema enforcement lowers the rate of malformed output, but it does not replace validation in your application code. The format parameter constrains what the model may produce, so your parser can usually rely on the shape of the JSON. It cannot confirm that a value is correct for your business. A model can return a valid amount field that is negative, a date in the wrong century, or a customer ID that does not exist in your system. Treat the schema as the first gate, then check types, ranges, enumerations and cross-field rules after parsing, using the same validation library your services already run.

Schema enforcement also does not cover every way a response can fail. Plan separate handling for refusals, truncated output and empty content. Check the response for a refusal or a stop reason that shows generation ended early, because a cut-off object can still look like a partial record your pipeline accepts. Set an output token limit deliberately, confirm how your client surfaces truncation, and test each path with prompts that force a long answer. Confirm the exact fields your Ollama version returns in its structured outputs documentation before you write these checks against them.

Decide what happens when validation fails before you go live. Log the raw response, the schema version, the model name and tag, the input identifier and the specific rule that failed, while keeping prompts and personal data out of general logs unless your data handling policy allows it. For transient failures such as a truncated response, a bounded retry with the same input is usually reasonable. For rule failures that repeat, route the record to a human review queue instead of retrying in a loop. Review failure rates by model version, because a model replacement or a Modelfile change can shift them without any code change.

Security and operational considerations for structured output services

A structured output service sits between a model and the systems that act on its answers, so the risks sit at both ends. The cards cover who can reach the API, what happens to prompts, how untrusted output is checked, and how failed extractions are seen before they cause harm.

No built-in API authentication

The local Ollama API at localhost:11434 does not require authentication. Any process or user that can reach the port can send prompts and set format schemas. If clients on other machines call the service, place a reverse proxy with authentication and TLS in front of it, and confirm which identities are allowed to call it. Test the proxy by sending a request without credentials and expecting a refusal.

Ollama API authentication

Default loopback binding

Ollama binds to 127.0.0.1 on port 11434 by default. Changing the bind address with OLLAMA_HOST is the step that exposes the service to the network, so treat it as a change that needs review. Check the listening address with your operating system's socket tools after every configuration change, and keep the port closed at the host firewall unless a proxy is intended to reach it.

Ollama FAQ

Prompts stay on the local server

Ollama states that when it runs locally it does not see your prompts or data. That statement covers local runs only. Extraction inputs often contain personal or financial records, so confirm that your applications call the local server and not a cloud endpoint. Set OLLAMA_NO_CLOUD=1 or the server configuration file so cloud features stay off in environments where that is required.

Ollama FAQ

Validate output before use

A schema constrains the shape of the response, not its truth. A value can match the schema and still be wrong, out of range or hostile, for example text that instructs a downstream system. Validate every parsed object against the same schema on the client, check value ranges and enumerations, and pass only validated fields to databases, APIs or workflow tools. Never build SQL, shell commands or tool arguments by string concatenation from model output.

Log and monitor extraction failures

Track how often responses fail parsing or schema validation, which schema and model version produced them, and how many requests the server queued or rejected. A rise in failures often signals a changed model, a truncated context or an input type nobody tested. Store failure records with the request identifier, without raw personal data where possible, so the team can investigate and retest. Set alert thresholds with your operations team.

Questions buyers ask about structured outputs with Ollama

What does it cost to add structured JSON outputs to Ollama?

The cost is mostly the time to design schemas, test them against real documents and wire validation into your application, and that effort depends on how many document types or response shapes you need. Your organization pays for the initial build once, then pays again for upkeep whenever a schema, prompt or model changes. Running Ollama on your own hardware carries no license fee for local use, so the recurring costs are hardware, operations and periodic regression testing. Ask any partner for a quote that lists each schema, each integration point, the test set and the retest cycle as separate line items, with the one-time and recurring parts marked. A fixed-scope quote is agreed in writing before work starts.

How long does a structured outputs pilot take?

Duration follows the scope the team agrees, mainly the number of schemas, the source document types and the number of downstream systems that consume the JSON. A narrow pilot covers one extraction task with one schema, one model and a defined test set, while a broader one adds several schemas, error handling and access controls. No duration is fixed by Ollama's documentation, so ask for a timeline tied to named deliverables such as the schema set, the validation layer and the reliability test report. Confirm in writing which model versions are in scope, since Ollama ships frequent releases, including v0.40.5 released on 14 October 2026.

What must our team provide before a structured outputs project starts?

Your team needs to provide the target output schemas or the fields you want extracted, representative sample documents with known correct answers, and a list of downstream systems that will receive the JSON. You also need a test server with enough memory and, if you use a GPU, the accelerator drivers in place, plus a named owner who can approve schema changes. Access is required to the host, the model store and the logging system, and to any application that will call the API. Before the work starts, confirm the sample set includes edge cases such as missing fields, malformed scans and unusual formats, because those drive most of the rework.

Can our internal team build structured outputs on Ollama alone?

Yes, a team with backend and data engineering skills can build it internally, because the feature is a documented request option in the Ollama API rather than a separate product. The work that usually stalls internal teams is schema design, a test set that reflects real documents, and a validation and retry path in the client code. Ollama's structured outputs documentation covers the mechanics, but it does not decide which fields are required or how failures should be handled. Consider a partner if you lack people to own the schemas over time, need an independent review before production, or must show evidence to a compliance team.

Do we need an Ollama paid plan to run structured outputs locally?

No. Ollama's pricing page states that running models on your own hardware is always unlimited, so local structured outputs do not require a paid plan. The paid tiers, Pro at $20 per month ($200 per year), Max at $100 per month, Team at $500 per month and Enterprise at custom pricing, apply to cloud models. The cloud does not support structured outputs at the time of writing, so a paid cloud plan would not give you this feature anyway. Confirm current pricing on the vendor's page before budgeting, because plan terms can change.

How do we test whether a schema-constrained output is reliable?

Reliability testing checks two things: whether every response parses against the schema, and whether the extracted values are correct. Build a labeled set of documents that covers typical inputs, missing fields, noisy text and boundary values, then run each one several times on the exact model, quantization and settings you will deploy. Record schema-conformance failures separately from wrong-value errors, and validate every response on the client side even though the format parameter constrains output. Repeat the test whenever you change the model, the prompt, the context length or the Ollama version, and keep the results as evidence for your change records.

Does Ollama's cloud support structured JSON outputs?

No. Ollama's documentation states that its cloud currently does not support structured outputs, so schema enforcement works only on local or self-hosted Ollama. If your application sends requests to direct cloud inference at ollama.com/api, the format constraint will not apply and your validation must catch the failures. Keep the request path pinned to your self-hosted server, and turn off cloud features with OLLAMA_NO_CLOUD=1 or the server configuration file if policy requires it. Confirm the cloud position again before you design around it, because vendor support can change.

How DeployOpen scopes and delivers structured output services

DeployOpen scopes structured output work as a fixed-scope engagement with deliverables and milestones agreed in writing before any build starts. For this topic, the scope usually covers four things: an Ollama server installed inside your own infrastructure, the JSON schemas that your extraction and automation jobs depend on, client-side validation code that runs against every response, and a security test of the API that applications will call. Each of these has a clear owner and a clear acceptance check, so the written scope should name them explicitly rather than describing the work as general Ollama support.

The schema and validation design starts from your documents, not from a generic template. DeployOpen works through a sample of the real inputs your team processes, such as invoices, claims, tickets or intake forms, and agrees with your stakeholders which fields are required, which values are enumerations, and how missing or ambiguous data should be represented. Because Ollama's structured outputs constrain the response to the schema you pass in the format parameter, the schema is the control point, so it is reviewed like code. The written scope should also state which validation failures trigger a retry, which go to a human review queue, and which are logged for later tuning. Confirm the exact behavior of your chosen model and Ollama version in a test run before accepting the design.

The Ollama API has no built-in authentication on the local port, so the security testing in the engagement targets the exposed endpoint: network binding, the reverse proxy and authentication layer placed in front of it, and what a caller can reach through it. Testing also covers the prompts and documents that flow through the service and how they are stored in logs. Once the service is in production, many clients choose an optional retainer for ongoing support, model and version upgrades, and periodic retesting. Ask any provider, including DeployOpen, for the retainer terms in writing, including response expectations and what is excluded, before you commit to one.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.