All writing

Turn a support ticket into three JSON fields with Ollama

Extract an order ID, issue and replacement flag from a fictional ticket using a local Ollama model.

Last updated

Menus and supported features can change. Compare the source-check date below with your current app version.

App · APP
Official documentation · not hands-on tested Sources checked:

A customer writes that an item arrived broken. Before writing a reply, you need to know which order it was, what broke, and whether the customer actually asked for a replacement. In this exercise, Ollama reads a fictional ticket and saves those three pieces of information in a JSON file.

A fixed format is useful if another person or program needs to read the result. It does not guarantee the model understood the message. Keep a human check between this file and any action on an order. This exercise only writes a local practice file. It follows the official Ollama structured outputs documentation; I did not run the model or measure accuracy. The cover illustrates the three fields.

1. Get the local model and prepare a ticket

Install and open Ollama. In PowerShell or Terminal, run these commands:

ollama --version
ollama pull qwen2.5:1.5b

The second command downloads the model. Create a practice folder and save the following fictional line in ticket.txt as UTF-8 text. If your editor asks for a file type, choose a setting that does not append a second extension.

Order BW-1042 arrived with a cracked lid. Please send a replacement.

For this exercise, a replacement is requested only when the customer says so. Asking for available options does not count. That distinction gives you a simple second input to test later.

2. Describe the three fields

Save the script below as extract_ticket.py next to the ticket. It uses the Python standard library. localhost points at your own computer. The format setting describes the expected JSON fields and their types. This example uses local Ollama because the official documentation says Ollama Cloud does not currently support structured outputs.

import json
from pathlib import Path
from urllib.request import Request, urlopen

source = Path("ticket.txt").read_text(encoding="utf-8-sig")
keys = {"order_id", "issue", "replacement_requested"}
schema = {
    "type": "object",
    "properties": {
        "order_id": {"type": "string"},
        "issue": {"type": "string"},
        "replacement_requested": {"type": "boolean"}
    },
    "required": sorted(keys),
    "additionalProperties": False
}
payload = {
    "model": "qwen2.5:1.5b",
    "stream": False,
    "format": schema,
    "options": {"temperature": 0},
    "messages": [{
        "role": "user",
        "content": (
            "Extract only facts in the support ticket. Preserve the exact order ID. "
            "Write the issue as a short English phrase. "
            "The replacement field is true only if the customer explicitly requests it. "
            "Use empty strings for facts that are missing. Return JSON matching this schema:\n"
            + json.dumps(schema) + "\nTicket:\n" + source
        )
    }]
}
request = Request(
    "http://localhost:11434/api/chat",
    data=json.dumps(payload).encode("utf-8"),
    headers={"Content-Type": "application/json"}
)
with urlopen(request, timeout=180) as response:
    message = json.load(response)["message"]["content"]
result = json.loads(message)
if not isinstance(result, dict) or set(result) != keys:
    raise ValueError("Unexpected fields")
if not all(isinstance(result[k], str) for k in ("order_id", "issue")):
    raise ValueError("Expected strings")
if type(result["replacement_requested"]) is not bool:
    raise ValueError("Expected JSON true/false")
Path("ticket-result.json").write_text(
    json.dumps(result, ensure_ascii=False, indent=2) + "\n",
    encoding="utf-8"
)
print("Saved ticket-result.json; compare its facts to ticket.txt.")

Change to the practice folder in your terminal. On Windows with Python 3.12, run py -3.12 extract_ticket.py; on Mac or Linux, run python3 extract_ticket.py. Keep the app running while the script asks for a response.

3. Check shape and meaning separately

After the success message, reopen ticket-result.json. Compare the order ID with BW-1042 and check that the issue is a cracked lid. The model’s short wording can differ while keeping the same meaning. The replacement field should be true. Quoted "true" would be a string, while this exercise requires a JSON boolean. The script checks the field names and types before writing a file. It does not establish that a returned order ID or description is correct.

Next, replace Please send a replacement. in the input with Can you tell me my options? Save the input and run the script again. Now the expected replacement flag is false. To compare both attempts, copy the first output to a new name before running the second. Check the modified timestamp if you get an error: an old result can still be sitting in the folder.

If the script stops

A refused connection often means the local Ollama service is not running. Open Ollama and check again. If the model cannot be found, use ollama list and compare the exact name. If the run times out, check the terminal error before assuming the model is merely slow. When the output is well formed but its facts are wrong, return to the source message and review the missed wording. A tighter schema alone cannot correct a mistaken reading.

You are done when you can reopen the file and explain why the two versions have different flags. For a different local model exercise, see the game dialogue translation guide.

Sources & further reading