DeepSeek V4.1 Flash JSON output: Extract and validate support ticket fields in Python

DeepSeek

Learn how to call DeepSeek V4.1 Flash from Python in JSON mode to extract support ticket fields, design a strict ticket schema, validate the returned JSON, and distinguish the guarantees provided by JSON mode from the checks you must enforce yourself.

Published
On this page

Set up the DeepSeek JSON call for a single support ticket

To go from one plain-text support ticket to a validated JSON object, you will send the ticket text to DeepSeek V4.1 Flash in JSON mode, parse the model’s reply, and then enforce a few schema checks before using it. The DeepSeek JSON Output guide documents that you enable JSON-only replies by setting response_format={"type": "json_object"} on chat.completions.create, so the returned message.content is a valid JSON string you can parse directly [1].

For the sample ticket:

  • Subject: Cannot export reports
  • Customer: Casey Chen
  • Priority: high
  • Product: AcmeCRM
  • Description: CSV export is disabled after yesterday's update
  • No account ID provided

a valid extracted object (all keys present, missing facts as null) would look like:

json
{
  "subject": "Cannot export reports",
  "customer_name": "Casey Chen",
  "priority": "high",
  "product": "AcmeCRM",
  "description": "CSV export is disabled after yesterday's update",
  "account_id": null
}

Input: the raw support ticket text. Request: a chat.completions.create call to api.deepseek.com with model="deepseek-flash" and response_format={"type": "json_object"} so the reply is machine-parseable JSON [1]. Validation: Python code that rejects truncated, blank, malformed, or schema-violating JSON before it reaches downstream systems.

Install the OpenAI Python SDK with:

bash
python -m pip install openai

Then use an environment variable for your key (for example DEEPSEEK_API_KEY) and configure the client with base_url="https://api.deepseek.com" before you make any JSON-mode calls [1].

python
import os
import json
from typing import Any, Dict

from openai import OpenAI


def get_env_api_key() -> str:
    api_key = os.getenv("DEEPSEEK_API_KEY")
    if not api_key:
        raise RuntimeError("DEEPSEEK_API_KEY environment variable is not set")
    return api_key


def extract_and_validate_ticket() -> Dict[str, Any]:
    client = OpenAI(
        api_key=get_env_api_key(),
        base_url="https://api.deepseek.com",
    )

    # All extraction instructions live in the system message; the user message is only the ticket.
    system_message = """You are a JSON API that extracts support ticket fields.

Return ONLY a single JSON object, no extra text.

The JSON object MUST have exactly these keys:
- "subject"
- "customer_name"
- "priority"
- "product"
- "description"
- "account_id"

Rules:
- All six keys MUST be present in the JSON object.
- Every value MUST be either a string or null.
- Use null if the ticket does not provide a value.
- "priority" MUST be one of: "low", "medium", "high", "urgent", or null.
- Do NOT invent an account_id if it is not explicitly provided; use null instead.

Example JSON (for illustration only):
{
  "subject": "Example subject",
  "customer_name": "Example Name",
  "priority": "high",
  "product": "ExampleProduct",
  "description": "Example description text.",
  "account_id": null
}

Output ONLY JSON, no explanation, markdown, or comments."""

    # Synthetic plain-text support ticket (user message contains only the ticket text).
    user_message = (
        "Subject: Cannot export reports\n"
        "Customer: Casey Chen\n"
        "Priority: high\n"
        "Product: AcmeCRM\n"
        "Description: CSV export is disabled after yesterday's update.\n"
        "No account ID was provided."
    )

    response = client.chat.completions.create(
        model="deepseek-flash",
        messages=[
            {"role": "system", "content": system_message},
            {"role": "user", "content": user_message},
        ],
        # JSON mode: DeepSeek will return a valid JSON string in message.content [1].
        response_format={"type": "json_object"},
        max_tokens=300,
    )

    # Basic structural checks on the completion.
    if not response.choices:
        raise RuntimeError("No choices returned from DeepSeek completion")

    choice = response.choices[0]

    # Treat truncation as an error; JSON may be incomplete.
    if getattr(choice, "finish_reason", None) == "length":
        raise RuntimeError("Completion was truncated (finish_reason=length)")

    content = choice.message.content
    if content is None or content.strip() == "":
        # In JSON Output mode, non-JSON content can be replaced with spaces,
        # so an apparently empty string must be treated as an error [1].
        raise RuntimeError("Model returned blank or whitespace-only content in JSON mode")

    # Parse JSON output into a Python dict.
    try:
        obj = json.loads(content)
    except json.JSONDecodeError as e:
        raise RuntimeError(f"Model output is not valid JSON: {e}") from e

    if not isinstance(obj, dict):
        raise RuntimeError("Top-level JSON value must be an object")

    # Schema and type validation.
    required_keys = {
        "subject",
        "customer_name",
        "priority",
        "product",
        "description",
        "account_id",
    }

    actual_keys = set(obj.keys())
    if actual_keys != required_keys:
        missing = required_keys - actual_keys
        extra = actual_keys - required_keys
        problems = []
        if missing:
            problems.append(f"missing keys: {sorted(missing)}")
        if extra:
            problems.append(f"unexpected keys: {sorted(extra)}")
        raise RuntimeError("Schema validation failed (" + ", ".join(problems) + ")")

    # Value type checks and allowed priority values.
    allowed_priorities = {"low", "medium", "high", "urgent"}

    for key, value in obj.items():
        if value is not None and not isinstance(value, str):
            raise RuntimeError(
                f"Value for '{key}' must be a string or null; got {type(value).__name__}"
            )

        if key == "priority" and value is not None and value not in allowed_priorities:
            raise RuntimeError(
                "Invalid priority value: "
                f"{value!r} (allowed: null, 'low', 'medium', 'high', 'urgent')"
            )

    return obj


if __name__ == "__main__":
    ticket = extract_and_validate_ticket()
    # Print only the final validated JSON object.
    print(json.dumps(ticket, indent=2, sort_keys=True))
Set up the DeepSeek JSON call for a single support ticket
  1. Input: the raw support ticket text.

    To go from one plain-text support ticket to a validated JSON object, you will send the ticket text to DeepSeek V4.1 Flash in JSON mode, parse the model’s reply, and then enforce a few schema checks before using it.

  2. Request: a chat.completions.create call to api.deepseek.com

    enable JSON-only replies by setting response_format={"type": "json_object"} on chat.completions.create, so the returned message.content is a valid JSON string you can parse directly

  3. Validation: Python code

    Validation: Python code that rejects truncated, blank, malformed, or schema-violating JSON before it reaches downstream systems.

Design the JSON schema and prompts for support ticket fields

field_nametyperequiredallows_nullnotes
subjectstringtruetrueShort summary of the issue. Must always be present; use null only if the ticket genuinely lacks a subject line.
customer_namestringtruetruePerson or organization submitting the ticket. Key must exist; set to null if no name is given.
prioritystringtruetrueTicket urgency. Key must exist and value must be null or one of: low, medium, high, urgent.
productstringtruetrueProduct or service the ticket refers to. Always include the key; use null if the ticket does not specify a product.
descriptionstringtruetrueFree-text description of the problem. Key is required; use null only if no description is provided.
account_idstringtruetrueCustomer account identifier if explicitly mentioned. Never invent it; include the key and set to null when the ticket does not contain an account ID.

To keep DeepSeek’s output aligned with this schema, the system message should declare the model’s role as a JSON-only extractor, list the exact keys, and spell out the rules for values and nulls.

A concise pattern is:

You are a JSON API that extracts support ticket fields.

Return ONLY a single JSON object, no extra text.

The JSON object MUST have exactly these keys:

  • "subject"
  • "customer_name"
  • "priority"
  • "product"
  • "description"
  • "account_id"

Rules:

  • All six keys MUST be present in the JSON object.
  • Every value MUST be either a string or null.
  • Use null if the ticket does not provide a value.
  • "priority" MUST be one of: "low", "medium", "high", "urgent", or null.
  • Do NOT invent an account_id if it is not explicitly provided; use null instead.

Example JSON (for illustration only): { "subject": "Example subject", "customer_name": "Example Name", "priority": "high", "product": "ExampleProduct", "description": "Example description text.", "account_id": null }

Output ONLY JSON, no explanation, markdown, or comments.

In your validator, treat any deviation from a single JSON object with exactly these keys, strict JSON syntax, or the string/null value rules as an error. That includes extra keys, missing keys, non-string scalar values, or a priority value outside the allowed set.

The user message should contain only the raw ticket text so it naturally maps onto the schema without repeating JSON or extraction rules.

For the synthetic sample, a plain-text ticket can look like:

Subject: Cannot export reports Customer: Casey Chen Priority: high Product: AcmeCRM Description: CSV export is disabled after yesterday's update. No account ID was provided.

This keeps the system message solely responsible for defining the JSON shape and null behavior, while the user message supplies the facts to extract. Avoid mixing JSON instructions or schema details into the user message, so the roles stay clear: the system message constrains output to the six keys and null handling, and the user message is just the ticket content DeepSeek should transform into that object.

Validate the JSON ticket object before using it

Validation starts the moment you get message.content back from DeepSeek. Treat the raw string as untrusted until it passes a few simple checks. First, inspect the chosen completion: if there are no choices, or the first choice has finish_reason == "length", fail fast instead of trying to parse possibly truncated JSON. Then check that choice.message.content is not None and not just whitespace; in JSON mode, a usable reply must be a non-empty JSON string, and a blank or whitespace-only body should be treated as an error rather than an empty ticket.

Once you have nonblank content, parse it with json.loads. If parsing raises a JSON decode error, surface that as a hard failure; you do not want to guess what the model meant. After parsing, assert that the top-level value is a dictionary, since downstream code expects a single JSON object representing the ticket.

With a dict in hand, validate the schema by comparing the object’s keys to the exact set you expect: {"subject", "customer_name", "priority", "product", "description", "account_id"}. If any required key is missing or any extra key appears, treat that as a schema error instead of trying to fix it. This ensures that every ticket your code accepts has all six fields, and no unexpected fields that might confuse downstream consumers.

Finally, enforce value-level constraints: iterate over each key/value pair and reject any value that is neither a string nor null (i.e., None in Python). Then apply the simple business rule for priority: if it is not null, it must be exactly one of "low", "medium", "high", or "urgent". A value like "critical" or a numeric priority should cause validation to fail. When all of these checks pass, you have a clean Python dict that matches the schema for fields like the sample ticket:

  • "subject": "Cannot export reports"
  • "customer_name": "Casey Chen"
  • "priority": "high"
  • "product": "AcmeCRM"
  • "description": "CSV export is disabled after yesterday's update"
  • "account_id": null

At that point it is safe to treat the dict as a validated ticket object and pass it on to your own application logic.

When any of the validation steps fails, the script should raise a clear exception (for example, a RuntimeError with a concise message) or return an explicit error object to the caller, rather than silently fixing or dropping fields. Do not coerce bad priorities into valid ones, invent missing values, or ignore extra keys; those policies hide problems and make downstream behavior unpredictable.

The practical rule is simple: only tickets that pass all structural and value checks should reach downstream systems such as databases, queues, or routing logic. Everything else should trigger error handling—logging for operators, metrics, or a retry/fallback path—without leaking raw ticket content into logs where that is a concern.

To enforce this consistently, make validation a required step in your control flow. Call DeepSeek, take the first completion, and immediately run it through your validator. If validation succeeds, print or return the validated JSON dict and continue processing. If it fails, handle the exception or error object in one place (for example, by surfacing an error to the caller or sending the ticket for manual review). This keeps the deepseek-flash extraction and your JSON schema in sync and ensures that no unvalidated model output is ever used by the rest of your system.

Know what DeepSeek JSON mode guarantees and what you must still verify

JSON mode gives you a strong syntactic contract, but it does not make any promises about whether the extracted ticket fields are complete, accurate, or aligned with your business rules.

When you call chat.completions.create with response_format={"type": "json_object"}, the DeepSeek JSON Output guide explains that the model is instructed to return a valid JSON string in message.content instead of free-form text. In practice, this means that whenever you get a nonblank completion, you can treat it as parseable JSON: json.loads should succeed without you having to strip prose, bullets, or code fences first. Blank or whitespace-only content and truncated completions still need to be detected separately, which is why the script checks for an empty choices list, a finish_reason of "length", and whitespace-only choice.message.content before attempting to parse.

The chat.completions API itself also has a well-defined structure: the response has a choices array, and each choice contains a message with a role and content. Your script takes the first choice (choices[0]) and reads message.content as the model’s reply. JSON mode changes what that content looks like (a JSON string instead of arbitrary text), but not how you access it or how many choices you receive. You are still responsible for choosing which choice to use and for handling cases where no usable choice is present.

Everything beyond that—your six ticket fields, null handling, and specific value constraints—is an application-level convention layered on top of those guarantees. The API does not know that your object must have exactly subject, customer_name, priority, product, description, and account_id; those keys exist because you listed them in the system message and enforce them in your validator. Likewise, the decision to represent missing facts as null rather than an empty string or omitted key is your own schema choice, not something JSON mode enforces. The allowed set of priorities (low, medium, high, urgent, or null) is also a business rule you impose; the model could otherwise emit values like "critical" or "p1" and still satisfy the API’s JSON requirements.

The practical takeaway is that JSON mode and the SDK guarantee a parseable container and a consistent response structure, but they do not guarantee that the contents match your support workflow. That is why the script goes beyond syntax: it insists on the exact key set, string-or-null types, and a restricted priority vocabulary before treating the object as valid. You should treat those rules as a starting point. If your tickets sometimes carry additional identifiers, different priority scales, or locale-specific fields, extend the schema and tighten the checks to match your own SLAs and downstream systems—while keeping the same pattern of: trust the API for JSON format and message shape, and trust your own validation for everything related to meaning and correctness.

Sources

  1. DeepSeek JSON Output
Contact support