Generate text with guided decoding#

Source NVIDIA/TensorRT-LLM.

 1### Generate text with guided decoding
 2from tensorrt_llm import SamplingParams
 3from tensorrt_llm._tensorrt_engine import LLM
 4from tensorrt_llm.llmapi import GuidedDecodingParams
 5
 6
 7def main():
 8
 9    # Specify the guided decoding backend; xgrammar is supported currently.
10    llm = LLM(model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",
11              guided_decoding_backend='xgrammar')
12
13    # An example from json-mode-eval
14    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"]}'
15
16    prompt = [{
17        'role':
18        'system',
19        'content':
20        "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"
21    }, {
22        'role':
23        'user',
24        'content':
25        "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."
26    }]
27    prompt = llm.tokenizer.apply_chat_template(prompt, tokenize=False)
28    print(f"Prompt: {prompt!r}")
29
30    output = llm.generate(prompt, sampling_params=SamplingParams(max_tokens=50))
31    print(f"Generated text (unguided): {output.outputs[0].text!r}")
32
33    output = llm.generate(
34        prompt,
35        sampling_params=SamplingParams(
36            max_tokens=50, guided_decoding=GuidedDecodingParams(json=schema)))
37    print(f"Generated text (guided): {output.outputs[0].text!r}")
38
39    # Got output like
40    # 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"
41    # 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  "'
42    # Generated text (guided): '{"ssid": "OfficeNetSecure", "securityProtocol": "WPA2-Enterprise", "bandwidth": "1300 Mbps"}'
43
44
45if __name__ == '__main__':
46    main()