|
| 1 | +--- |
| 2 | +title: Using structured outputs in vLLM |
| 3 | +date: 2025-03-16T19:28:00.657Z |
| 4 | +author: Ismael Delgado Muñoz |
| 5 | +authorimage: /img/Avatar6.svg |
| 6 | +disable: false |
| 7 | +tags: |
| 8 | + - AI |
| 9 | + - GenAI |
| 10 | + - opensource |
| 11 | + - LLM |
| 12 | +--- |
| 13 | +Generating predictable and reliable outputs from large language models (LLMs) can be challenging, especially when those outputs need to integrate seamlessly with downstream systems. Structured outputs solve this problem by enforcing specific formats, such as JSON, regex patterns, or even grammars. vLLM supported this since some time ago, but there were no documentation on how to use it, and that´s why I decided to do a contribution and write the Structured Outputs documentation page (https://docs.vllm.ai/en/latest/usage/structured_outputs.html). |
| 14 | + |
| 15 | +# Why Structured Outputs? |
| 16 | + |
| 17 | +LLMs are incredibly powerful, but their outputs can be inconsistent when a specific format is required. Structured outputs address this issue by restricting the model’s generated text to adhere to predefined rules or formats, ensuring: |
| 18 | + |
| 19 | +1. **Reliability:** Outputs are predictable and machine-readable. |
| 20 | +2. **Compatibility:** Seamless integration with APIs, databases, or other systems. |
| 21 | +3. **Efficiency:** No need for extensive post-processing to validate or fix outputs. |
| 22 | + |
| 23 | +Imagine we have an external system which receives a JSON with the all the details to trigger an alert, and we want our LLM-based system to be able to use it. Of course we can try to explain the LLM what should be the output format and that it must be a valid JSON, but LLMs are not deterministic and thus we may end up with an invalid JSON. Probably, if you have tried to do something like this before, you would have found yourself in this situation. |
| 24 | + |
| 25 | +How these tools work? The idea is that we´ll be able to filter the list of possible next tokens to force that we are always generating a token that is valid for the desired output format. |
| 26 | + |
| 27 | +# What is vLLM? |
| 28 | + |
| 29 | +vLLM is a state-of-the-art, open-source inference and serving engine for LLMs. It’s built for performance and simplicity, offering: |
| 30 | + |
| 31 | +- **PagedAttention:** An innovative memory management mechanism for efficient attention key-value handling. |
| 32 | +- **Continuous Batching:** Supports concurrent requests dynamically. |
| 33 | +- **Advanced Optimizations:** Includes features like quantization, speculative decoding, and CUDA graphs. |
| 34 | + |
| 35 | +These optimizations make vLLM one of the fastest and most versatile engines for production environments. |
| 36 | + |
| 37 | +# Structured outputs on vLLM |
| 38 | + |
| 39 | +vLLM extends the OpenAI API with additional parameters to enable structured outputs. These include: |
| 40 | + |
| 41 | +- **`guided_choice`:** Restricts output to a set of predefined choices. |
| 42 | +- **`guided_regex`:** Ensures outputs match a given regex pattern. |
| 43 | +- **`guided_json`:** Validates outputs against a JSON schema. |
| 44 | +- **`guided_grammar`:** Enforces structure using context-free grammars. |
| 45 | + |
| 46 | +Here’s how each works, along with example outputs: |
| 47 | + |
| 48 | +### **1. Guided Choice** |
| 49 | + |
| 50 | +Simplest form of structured output, ensuring the response is one of a set of predefined options. |
| 51 | + |
| 52 | +```python |
| 53 | +from openai import OpenAI |
| 54 | + |
| 55 | +client = OpenAI(base_url="http://localhost:8000/v1", api_key="-") |
| 56 | + |
| 57 | +completion = client.chat.completions.create( |
| 58 | + model="Qwen/Qwen2.5-3B-Instruct", |
| 59 | + messages=[ |
| 60 | + {"role": "user", "content": "Classify this sentiment: vLLM is wonderful!"} |
| 61 | + ], |
| 62 | + extra_body={"guided_choice": ["positive", "negative"]}, |
| 63 | +) |
| 64 | +print(completion.choices[0].message.content) |
| 65 | +``` |
| 66 | + |
| 67 | +**Example Output:** |
| 68 | + |
| 69 | +``` |
| 70 | +positive |
| 71 | +``` |
| 72 | + |
| 73 | +### **2. Guided Regex** |
| 74 | + |
| 75 | +Constrains output to match a regex pattern, useful for formats like email addresses. |
| 76 | + |
| 77 | +```python |
| 78 | +completion = client.chat.completions.create( |
| 79 | + model="Qwen/Qwen2.5-3B-Instruct", |
| 80 | + messages=[ |
| 81 | + { |
| 82 | + "role": "user", |
| 83 | + "content": "Generate an example email address for Alan Turing at Enigma. End in .com.", |
| 84 | + } |
| 85 | + ], |
| 86 | + extra_body={"guided_regex": r"\w+@\w+\.com\n", "stop": ["\n"]}, |
| 87 | +) |
| 88 | +print(completion.choices[0].message.content) |
| 89 | +``` |
| 90 | + |
| 91 | +**Example Output:** |
| 92 | + |
| 93 | +``` |
| 94 | + |
| 95 | +``` |
| 96 | + |
| 97 | +### **3. Guided JSON** |
| 98 | + |
| 99 | +Enforces a valid JSON format based on a schema, simplifying integration with other systems. |
| 100 | + |
| 101 | +```python |
| 102 | +from pydantic import BaseModel |
| 103 | +from enum import Enum |
| 104 | + |
| 105 | +class CarType(str, Enum): |
| 106 | + sedan = "sedan" |
| 107 | + suv = "SUV" |
| 108 | + truck = "Truck" |
| 109 | + coupe = "Coupe" |
| 110 | + |
| 111 | +class CarDescription(BaseModel): |
| 112 | + brand: str |
| 113 | + model: str |
| 114 | + car_type: CarType |
| 115 | + |
| 116 | +json_schema = CarDescription.model_json_schema() |
| 117 | + |
| 118 | +completion = client.chat.completions.create( |
| 119 | + model="Qwen/Qwen2.5-3B-Instruct", |
| 120 | + messages=[ |
| 121 | + {"role": "user", "content": "Generate a JSON for the most iconic car from the 90s."} |
| 122 | + ], |
| 123 | + extra_body={"guided_json": json_schema}, |
| 124 | +) |
| 125 | +print(completion.choices[0].message.content) |
| 126 | +``` |
| 127 | + |
| 128 | +**Example Output:** |
| 129 | + |
| 130 | +```json |
| 131 | +{ |
| 132 | + "brand": "Toyota", |
| 133 | + "model": "Supra", |
| 134 | + "car_type": "coupe" |
| 135 | +} |
| 136 | +``` |
| 137 | + |
| 138 | +### **4. Guided Grammar** |
| 139 | + |
| 140 | +Uses an EBNF grammar to define complex output structures, such as SQL queries. |
| 141 | + |
| 142 | +```python |
| 143 | +completion = client.chat.completions.create( |
| 144 | + model="Qwen/Qwen2.5-3B-Instruct", |
| 145 | + messages=[ |
| 146 | + {"role": "user", "content": "Generate a SQL query to find all users older than 30."} |
| 147 | + ], |
| 148 | + extra_body={ |
| 149 | + "guided_grammar": """ |
| 150 | + query ::= "SELECT" fields "FROM users WHERE" condition; |
| 151 | + fields ::= "name, age" | "*"; |
| 152 | + condition ::= "age >" number; |
| 153 | + number ::= [0-9]+; |
| 154 | + """ |
| 155 | + }, |
| 156 | +) |
| 157 | +print(completion.choices[0].message.content) |
| 158 | +``` |
| 159 | + |
| 160 | +**Example Output:** |
| 161 | + |
| 162 | +```sql |
| 163 | +SELECT * FROM users WHERE age > 30; |
| 164 | +``` |
| 165 | + |
| 166 | +# **Next Steps** |
| 167 | + |
| 168 | +To start integrating structured outputs into your projects: |
| 169 | + |
| 170 | +1. **Explore the Documentation:** Check out the official documentation for more examples and detailed explanations. |
| 171 | +2. **Install vLLM Locally:** Set up the inference server on your local machine using the vLLM GitHub repository. |
| 172 | +3. **Experiment with Structured Outputs:** Try out different formats (choice, regex, JSON, grammar) and observe how they can simplify your workflow. |
| 173 | +4. **Deploy in Production:** Once comfortable, deploy vLLM to your production environment and integrate it with your applications. |
| 174 | + |
| 175 | +Structured outputs make LLMs not only powerful but also practical for real-world applications. Dive in and see what you can build! |
0 commit comments