Pass a JSON schema in the chat request’s response format to constrain the text that llama-server generates. Parse the normal HTTP response first, then parse the chat message content as a second JSON document. Check the fields against the original source before handing them to any script. The schema can make the shape predictable. The source still determines which values belong in the record.

This guide assumes llama.cpp is installed and a compatible GGUF text instruction model is already downloaded to your Mac. Keep the experiment on loopback and use a short source note with visible answers. You will turn two fictional equipment notes into three-field records and distinguish successful decoding from correct extraction. That distinction matters if the output will feed any later processing.

Start a single chat server deliberately

Use the command below from a Terminal where the llama-server executable is available. Replace the model path with the actual file on your Mac. If a listener already serves the selected model, check its address and version and use that listener instead. This example uses a local port of 8080. A separate Terminal will send requests while the server is running.

llama-server -m '/absolute/path/to/chat-model.gguf' \
  --host 127.0.0.1 --port 8080

Wait for the initial load to finish. A port can accept connections before a model is ready for a normal response. The project’s server reference lists a health endpoint, which is useful for distinguishing that brief setup state from a malformed request. Once ready, read the models listing and copy the identifier actually presented by your server. The model’s visible name comes from its configuration. A nearby filename or label in another application can differ.

curl -sS http://127.0.0.1:8080/health
curl -sS http://127.0.0.1:8080/v1/models

Use the server reference for the release you installed, especially if a key in this example yields an unsupported option error. llama.cpp documents plain JSON mode and schema-constrained variants. This exercise uses the documented JSON object form with a schema attached to it. It also uses the Chat Completions path, where messages carry roles, instead of composing the rendered chat prompt yourself. llama.cpp server Chat Completions reference.

Choose a schema with a visible purpose

The synthetic source says a hand cart has seven spare wheels and a hold flag of yes. The output has an exact field for the item code, an integer count, and a Boolean flag. These types make subtle mistakes visible. A quoted number is a different type from an integer. The string yes has a recognizable meaning in the source but the consumer expects a Boolean. The prompt provides this translation rule explicitly.

Use short fixed field names for the first exercise. List all three as required and disallow extra fields. These are ordinary JSON schema choices and keep the acceptance check easy to read. Avoid combining this first test with complicated alternatives, references, or expressions. The upstream project describes a supported subset of JSON Schema conversion. A schema that validates in another service can include constraints the installed build handles differently. llama.cpp JSON schema and grammar guide.

Save the example under a new test directory as record-request.json and replace the model field before sending it. This external file makes it easy to keep the request for the second input, and your shell does not need to interpret its quotation marks.

{
  "model": "REPLACE_WITH_API_ID",
  "stream": false,
  "max_tokens": 200,
  "messages": [
    {
      "role": "user",
      "content": "Source: hand cart, item HC-14, spare wheels 7, hold yes. Return one JSON object with keys item, spares, and hold. Copy the item code into item. Put the whole-number spare-wheel count into spares. For hold, yes is true and no is false."
    }
  ],
  "response_format": {
    "type": "json_object",
    "schema": {
      "type": "object",
      "properties": {
        "item": {"type": "string"},
        "spares": {"type": "integer"},
        "hold": {"type": "boolean"}
      },
      "required": ["item", "spares", "hold"],
      "additionalProperties": false
    }
  }
}

Send the body as a JSON file and save the full response to another new file. This command shows the status on the terminal, including when the server sends an error body useful for diagnosis. Keep each attempt’s files under separate names if you plan to compare responses.

curl -sS -w 'HTTP %{http_code}\n' \
  -H 'Content-Type: application/json' \
  --data-binary @record-request.json \
  -o record-response.json \
  http://127.0.0.1:8080/v1/chat/completions

Start with the status. An error status belongs to the request or service path before any test of the extracted values. Open the response to read the error details in that case. A success status means an API response arrived. It is time to check what the model generated inside it.

Decode both layers and verify the result

The outer response includes familiar chat metadata and a list of choices. The first choice’s message has content that is itself a string, even when that string contains a valid JSON object. To inspect the result, decode the outer file and then decode that content string. This Python check raises a specific problem if the keys or types differ and shows a separate failure when the values disagree with the note.

import json

with open("record-response.json", encoding="utf-8") as file:
    envelope = json.load(file)

choice = envelope["choices"][0]
record = json.loads(choice["message"]["content"])
if type(record) is not dict or set(record) != {"item", "spares", "hold"}:
    raise ValueError("Expected exactly item, spares, and hold")
if type(record["item"]) is not str:
    raise ValueError("Item must be a string")
if type(record["spares"]) is not int:
    raise ValueError("Spares must be an integer")
if type(record["hold"]) is not bool:
    raise ValueError("Hold must be a Boolean")
expected = {"item": "HC-14", "spares": 7, "hold": True}
if record != expected:
    raise ValueError(f"Expected {expected}, received {record}")
print("Equipment record matches the source.")

Save the check as check-record.py in the same test directory and run it with Python 3. The expected message confirms several observations together. It shows that the outer response had a normal completion, the content decoded as one object, the three fields held the desired types, and the values matched the source. A different field order is fine because the check compares parsed mappings. An extra generated title or opening fence will fail parsing, which is appropriate for a consumer that expects directly usable JSON.

Use a second request with an intentional difference. Change the source to a folding table with item FT-06, spare wheels 0, and hold no. Update the check to expect that exact code, zero, and a false flag. Zero and false are meaningful values. A later consumer that treats them as missing will corrupt valid records even when the model did its part. Make a fresh generation and compare it with the second expectation. Keeping the value assertion separate from the type assertions makes both kinds of errors easier to locate.

Read failures at the right stage

When the outer body lacks choices, inspect the body and status. Using a path for a raw completion or sending an incorrect method can produce a valid response shape that belongs to another operation. If the actual error is that the model cannot be loaded, find the related entry in the server log before revising the schema. The key question at this stage is whether the server accepted the intended chat request at all.

If the outer response has a choice but the inner parser fails, inspect the returned message and its finish reason. A generation that runs into its token budget can end halfway through an object. A reasoning-oriented template can consume part of the budget before visible content arrives. Repeat the small example once with sufficient output budget or with a straightforward instruction checkpoint. Keep the prompt and schema stable while identifying why the content is incomplete.

If the object passes type checks and the values are wrong, keep the schema and look at the language of the extraction instruction. A field name like spares needs a clearly named source quantity. If the note contains both installed wheels and spare wheels, name the one to extract and include both values in the synthetic source. The decoder cannot infer which number an application owner wanted merely from the fact that the field is an integer.

Decide what an absent field should mean

Before using a similar request in a workflow, decide what the consumer should do when a required field is missing from an input note. This example requires integers and Booleans because both fixtures always provide them. A real note could say that the number of spares is pending. Forcing a numeric field in that case leaves room for the model to guess. One approach is to detect incomplete notes before extraction and put them in a manual review queue. Another is to design and test an explicit missing-value representation supported by your server’s grammar conversion.

Try an incomplete note separately if you intend to add that behavior. Write the desired outcome before running it, then record how the caller will see that outcome. A rejected input, a distinct status record, and an invented zero lead to different downstream actions. Keep the original note beside the generated object when reviewing unusual cases. The model’s structured response is an output to verify, and the original remains the reference when an item code or count determines what happens to the equipment.

Preserve a fixture for a later server update

Save one known response after the synthetic note passes, then replace a field in a copy of that response. For example, change the spare count from the numeric value seven to a quoted string containing the same digit. Run the checker on the altered copy and confirm that the type error appears. Restore the original and run the checker again. This rehearsal is independent of generation and demonstrates that the consumer catches a shape regression even when a person can read the string and infer its meaning.

Keep both request bodies and their expected mappings. If you update llama.cpp, start the new build with the same artifact and test the same two inputs. First check that the schema is accepted. Then compare the resulting parsed objects with the recorded values. JSON formatting can change across outputs, so use parsed values for acceptance and reserve the raw files for investigation. Differences in indentation and field order have little consequence when each receiver is a conforming parser. A switch from Boolean false to a missing field can affect the data contract even when a reader understands the original sentence.

Use the smallest fixture that reproduces an error before filing an issue or asking someone to inspect it. Include the first version in which you saw the behavior, the schema shape, and the applicable finish reason or error status. A two-sentence equipment note is easier for someone else to use than a document with company details or unrelated instructions. The synthetic fixture also lets you show exactly which failure your checker discovered and which portion of the result needs work.

Put field meanings in the prompt

llama.cpp’s grammar documentation explains that the server uses the response schema to restrict generated output. The model receives the chat messages you send. It needs enough information in those messages to understand which value belongs in each output field. In the equipment fixture, the instruction names the three JSON fields and the meaning of each. For example, the word hold represents the dispatch status, and its separate true or false output belongs to that field. llama.cpp grammar conversion and supported features.

Consider a note that says hand cart HC-14, seven spare wheels, four installed wheels, and hold yes. A prompt asking simply for the number of wheels leaves more than one defensible value. A schema requiring a whole number permits either seven or four. Change the prompt to name spare wheels explicitly, keep the schema the same, and check that the result remains seven. That proves something different from a change that simply narrows the allowed integer values without making the task clear.

Likewise, an item code can resemble a nearby carton label. Add a scratch note such as item HC-14, carton HC-41, spares seven, hold yes. Require the item field to come from the phrase item code, and compare the result with the source. If the result uses HC-41, the shape still passes. The caller should surface the wrong item during verification. Keeping a couple of these close variants gives you a better idea of what your actual extraction prompt handles than repeatedly sending the easiest note.

Add a check for business rules outside the grammar

Give the consumer three separate jobs. It should reject an unsuccessful or incomplete chat response, reject a structure that fails its data rules, and compare source values when reference data is available. Each job can fail while the others pass. A shipment workflow has consequences for where real equipment goes, so keep this exercise read-only until you have decided what a human reviewer will see on exceptions.

For example, a warehouse may allow spare counts from zero to twenty per item. This constraint is a business rule based on the equipment, and you can enforce it directly in the caller. Try a malformed source note with a negative quantity and decide whether the caller should present that record for review instead of using it. If a min or max appears in the response schema, use the server implementation’s supported subset as a guide and keep your direct check in place. A program accepting the schema document is only evidence that the document was readable; the supported grammar features determine what the decoder can constrain.

For a rejection-path rehearsal, make one offline success message with the expected item and count, a second with the correct shape and count 90, and a third that says 7 in quotation marks. The second is a domain failure. The third is a type failure. Use a read-only copy of the saved response as the starting point. There is no need to force a language model to generate these exact mistakes. Handcrafted fixtures repeat the same consumer checks every time.

Sometimes a source has an explicit hold condition involving another field. For example, a note could say that parts labeled for inspection must remain on hold. A conditional requirement can be represented in some general JSON Schema validators, but the llama.cpp project documents limitations on general conditionals during grammar conversion. Make the conditional rule a direct test in the application and give the model a short natural-language explanation where appropriate. Avoid treating the response format as the only place where this business decision lives.

Represent missing information deliberately

There is a useful design choice between rejecting a record with missing input and allowing a clear missing-value representation. For an input note that reads spare count pending, a zero would mean that someone counted and found none. Those are different operational situations. The example uses a required count because its two fixtures provide that information. To handle incomplete source notes later, first decide whether a human review or a machine status will represent the gap.

One safe path is an independent form rule that verifies whether the source has the fields required for this workflow. A desk operator can check the original and supply missing details before extraction. A program may already read an authoritative data field before assembling its prompt. In either case, keep incomplete notes out of the normal extraction contract and route them to review with a short reason.

If you choose a structured missing state instead, write an exact expectation for input with zero, input with a known count, and input with a count explicitly pending. Use a minimal shape whose features are supported by your installed server. The caller should still verify the intended relationship between the state and the count. For instance, a count of zero is valid when known and should not be used as the placeholder for a pending count. Record whether the application treats pending as a work item or simply holds it for a human to examine.

A field can also be unknown because a note has contradictory facts. Try a source that initially says seven, then says the latest count is eight. The prompt needs a revision rule so that the intended value is eight. A schema supplies the place for that count. It cannot choose which date or revision you want used. If the ordering itself is unclear, preserve the competing facts and ask for confirmation before changing any underlying inventory record.

Make a small acceptance set for the next version

Keep a set of four request files using one intended field schema. Start with the hand cart, then the folding table with zero and false, then a similar case with an item code and a different carton identifier. Use a fourth file to represent your selected missing-input behavior. For each fixture, record the source sentence, what type and values you expect, and which failure should lead to manual review. This set can be copied between developers without moving real equipment data.

After a runtime update, work through those requests in the same order. Check the server version and loaded artifact first. Save the HTTP status, finish reason, and extracted record as separate observations in the run notes. If the simplest input passes but the changed version fails, read both prompts and the raw completions before changing the schema. A failed case without the exact input and server route can be difficult to reproduce even on the same model.

A successful response with a length finish warrants a look at the program’s acceptance behavior. In some cases the visible content can already look complete when the generator reached its limit. Decide whether the completion reason is required for your workflow. A caller that will automatically write updates can require a normal completion before checking values. A person reviewing a candidate record can choose to read what is present and compare it to the note. Keep that decision explicit rather than inferring it from whether the output happened to parse.

When handing the example to another team, put the caller’s expected behavior next to the response format. Include ordinary records, false and zero, closely related codes, missing data, and a deliberately malformed saved result. Consumer fixtures should remain runnable after the server is stopped. The actual smoke test should still send a fresh request against the intended model and verify its output. This two-part acceptance gives you evidence about both the server contract and the way your application uses it.

Keep failed records out of a successful batch

When several notes are processed together, preserve the association between each request and its source document before adding any validated rows. A later completion can arrive before an earlier one if your consumer sends concurrent requests. A record can be valid JSON and still be attached to the wrong source through a bookkeeping error. Include the synthetic record ID in your local run note and compare it to the item expected for that particular request. If one record is rejected, preserve its raw response and reason separately. You can then review or rerun the exact source rather than repeating an entire batch and guessing which result should replace an earlier one.