OpenAI Completion Client with JSON Schema#

Refer to the trtllm-serve documentation for starting a server.

Source NVIDIA/TensorRT-LLM.

 1
 2# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
 3# SPDX-License-Identifier: Apache-2.0
 4#
 5# Licensed under the Apache License, Version 2.0 (the "License");
 6# you may not use this file except in compliance with the License.
 7# You may obtain a copy of the License at
 8#
 9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17# This example requires to specify `guided_decoding_backend` as
18# `xgrammar` or `llguidance` in the config.yaml file.
19import json
20
21from openai import OpenAI
22
23client = OpenAI(
24    base_url="http://localhost:8000/v1",
25    api_key="tensorrt_llm",
26)
27
28response = client.chat.completions.create(
29    model="TinyLlama-1.1B-Chat-v1.0",
30    messages=[{
31        "role": "system",
32        "content": "you are a helpful assistant"
33    }, {
34        "role":
35        "user",
36        "content":
37        f"Give me the information of the biggest city of China in the JSON format.",
38    }],
39    temperature=0,
40    response_format={
41        "type": "json",
42        "schema": {
43            "type": "object",
44            "properties": {
45                "name": {
46                    "type": "string"
47                },
48                "population": {
49                    "type": "integer"
50                },
51            },
52            "required": ["name", "population"],
53        }
54    },
55    # The OpenAI client has no chat_template_kwargs argument; send it in the
56    # request body so the chat template actually receives it.
57    extra_body={"chat_template_kwargs": {
58        "enable_thinking": False
59    }},
60)
61
62content = response.choices[0].message.content
63try:
64    response_json = json.loads(content)
65    assert "name" in response_json and "population" in response_json
66    print(content)
67except json.JSONDecodeError as e:
68    raise RuntimeError(f"Failed to decode JSON response: {content!r}") from e