Generate text with guided decoding

Source https://github.com/NVIDIA/TensorRT-LLM/tree/main/examples/llm-api/llm_guided_decoding.py.

 1### Generate text with guided decoding
 2from tensorrt_llm import LLM, SamplingParams
 3from tensorrt_llm.llmapi import GuidedDecodingParams
 4
 5
 6def main():
 7
 8    # Specify the guided decoding backend; xgrammar is supported currently.
 9    llm = LLM(model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
10              guided_decoding_backend='xgrammar')
11
12    # An example from json-mode-eval
13    schema = '{"title": "WirelessAccessPoint", "type": "object", "properties": {"ssid": {"title": "SSID", "type": "string"}, "securityProtocol": {"title": "SecurityProtocol", "type": "string"}, "bandwidth": {"title": "Bandwidth", "type": "string"}}, "required": ["ssid", "securityProtocol", "bandwidth"]}'
14
15    prompt = [{
16        'role':
17        'system',
18        'content':
19        "You are a helpful assistant that answers in JSON. Here's the json schema you must adhere to:\n<schema>\n{'title': 'WirelessAccessPoint', 'type': 'object', 'properties': {'ssid': {'title': 'SSID', 'type': 'string'}, 'securityProtocol': {'title': 'SecurityProtocol', 'type': 'string'}, 'bandwidth': {'title': 'Bandwidth', 'type': 'string'}}, 'required': ['ssid', 'securityProtocol', 'bandwidth']}\n</schema>\n"
20    }, {
21        'role':
22        'user',
23        'content':
24        "I'm currently configuring a wireless access point for our office network and I need to generate a JSON object that accurately represents its settings. The access point's SSID should be 'OfficeNetSecure', it uses WPA2-Enterprise as its security protocol, and it's capable of a bandwidth of up to 1300 Mbps on the 5 GHz band. This JSON object will be used to document our network configurations and to automate the setup process for additional access points in the future. Please provide a JSON object that includes these details."
25    }]
26    prompt = llm.tokenizer.apply_chat_template(prompt, tokenize=False)
27    print(f"Prompt: {prompt!r}")
28
29    output = llm.generate(prompt, sampling_params=SamplingParams(max_tokens=50))
30    print(f"Generated text (unguided): {output.outputs[0].text!r}")
31
32    output = llm.generate(
33        prompt,
34        sampling_params=SamplingParams(
35            max_tokens=50, guided_decoding=GuidedDecodingParams(json=schema)))
36    print(f"Generated text (guided): {output.outputs[0].text!r}")
37
38    # Got output like
39    # Prompt: "<|system|>\nYou are a helpful assistant that answers in JSON. Here's the json schema you must adhere to:\n<schema>\n{'title': 'WirelessAccessPoint', 'type': 'object', 'properties': {'ssid': {'title': 'SSID', 'type': 'string'}, 'securityProtocol': {'title': 'SecurityProtocol', 'type': 'string'}, 'bandwidth': {'title': 'Bandwidth', 'type': 'string'}}, 'required': ['ssid', 'securityProtocol', 'bandwidth']}\n</schema>\n</s>\n<|user|>\nI'm currently configuring a wireless access point for our office network and I need to generate a JSON object that accurately represents its settings. The access point's SSID should be 'OfficeNetSecure', it uses WPA2-Enterprise as its security protocol, and it's capable of a bandwidth of up to 1300 Mbps on the 5 GHz band. This JSON object will be used to document our network configurations and to automate the setup process for additional access points in the future. Please provide a JSON object that includes these details.</s>\n"
40    # Generated text (unguided): '<|assistant|>\nHere\'s a JSON object that accurately represents the settings of a wireless access point for our office network:\n\n```json\n{\n  "title": "WirelessAccessPoint",\n  "'
41    # Generated text (guided): '{"ssid": "OfficeNetSecure", "securityProtocol": "WPA2-Enterprise", "bandwidth": "1300 Mbps"}'
42
43
44if __name__ == '__main__':
45    main()