Skip to content

Commit d2d34de

Browse files
authored
Merge pull request #2964 from ismael-dm/cms/ismael-dm/hpe-dev-portal/blog/using-structured-outputs-in-vllm
Create Blog “using-structured-outputs-in-vllm”
2 parents 2567d80 + b091df4 commit d2d34de

File tree

2 files changed

+181
-0
lines changed

2 files changed

+181
-0
lines changed
Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
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+
thumbnailimage: ""
7+
disable: false
8+
tags:
9+
- AI
10+
- GenAI
11+
- opensource
12+
- LLM
13+
---
14+
<style> li { font-size: 27px; line-height: 33px; max-width: none; } </style>
15+
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 formal grammars. vLLM, an open source inference and serving engine for LLMs, has supported structured outputs for a while. However, there is little documentation on how to use it. This is why I decided to contribute and write the [Structured Outputs documentation page](https://docs.vllm.ai/en/latest/usage/structured_outputs.html).
16+
17+
In this blog post, I'll explain how structured outputs work in vLLM and walk you through how to use them effectively.
18+
19+
## Why structured outputs?
20+
21+
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:
22+
23+
1. **Reliability:** Outputs are predictable and machine-readable.
24+
2. **Compatibility:** Seamless integration with APIs, databases, or other systems.
25+
3. **Efficiency:** No need for extensive post-processing to validate or fix outputs.
26+
27+
Imagine there is an external system which receives a JSON object with the all the details to trigger an alert, and you want your LLM-based system to be able to use it. Of course you could try to explain the LLM what should be the output format and that it must be a valid JSON object, but LLMs are not deterministic and thus you 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.
28+
29+
How do these tools work? The idea behind them is to filter a list of possible next tokens to force a valid token to be generated that produces the desired output format, for example, a valid JSON object.
30+
31+
![Structured outputs in vLLM](/img/structured_outputs_thumbnail.png "Structured outputs in vLLM")
32+
33+
## What is vLLM?
34+
35+
vLLM is a state-of-the-art, open-source inference and serving engine for LLMs. It’s built for performance and simplicity, offering:
36+
37+
* **PagedAttention:** An innovative memory management mechanism for efficient attention key-value handling.
38+
* **Continuous batching:** Supports concurrent requests dynamically.
39+
* **Advanced optimizations:** Includes features like quantization, speculative decoding, and CUDA graphs.
40+
41+
These optimizations make vLLM one of the fastest and most versatile engines for production environments.
42+
43+
## Structured outputs on vLLM
44+
45+
vLLM extends the OpenAI API with additional parameters to enable structured outputs. These include:
46+
47+
* **guided_choice:** Restricts output to a set of predefined choices.
48+
* **guided_regex:** Ensures outputs match a given regex pattern.
49+
* **guided_json:** Validates outputs against a JSON schema.
50+
* **guided_grammar:** Enforces structure using context-free grammars.
51+
52+
Here’s how each works, along with example outputs:
53+
54+
### **1. Guided choice**
55+
56+
Guided choice is the simplest form of structured output. It ensures the response is one from of a set of predefined options.
57+
58+
```python
59+
from openai import OpenAI
60+
61+
client = OpenAI(base_url="http://localhost:8000/v1", api_key="-")
62+
63+
completion = client.chat.completions.create(
64+
model="Qwen/Qwen2.5-3B-Instruct",
65+
messages=[
66+
{"role": "user", "content": "Classify this sentiment: vLLM is wonderful!"}
67+
],
68+
extra_body={"guided_choice": ["positive", "negative"]},
69+
)
70+
print(completion.choices[0].message.content)
71+
```
72+
73+
**Example output:**
74+
75+
```
76+
positive
77+
```
78+
79+
### **2. Guided Regex**
80+
81+
A guided regex constrains the output to match a regex pattern, which is useful for formats like email addresses.
82+
83+
```python
84+
completion = client.chat.completions.create(
85+
model="Qwen/Qwen2.5-3B-Instruct",
86+
messages=[
87+
{
88+
"role": "user",
89+
"content": "Generate an example email address for Alan Turing at Enigma. End in .com.",
90+
}
91+
],
92+
extra_body={"guided_regex": r"\w+@\w+\.com\n", "stop": ["\n"]},
93+
)
94+
print(completion.choices[0].message.content)
95+
```
96+
97+
**Example output:**
98+
99+
```
100+
101+
```
102+
103+
### **3. Guided JSON**
104+
105+
Guided JSON enforces a valid JSON format based on a schema, simplifying integration with other systems.
106+
107+
```python
108+
from pydantic import BaseModel
109+
from enum import Enum
110+
111+
class CarType(str, Enum):
112+
sedan = "sedan"
113+
suv = "SUV"
114+
truck = "Truck"
115+
coupe = "Coupe"
116+
117+
class CarDescription(BaseModel):
118+
brand: str
119+
model: str
120+
car_type: CarType
121+
122+
json_schema = CarDescription.model_json_schema()
123+
124+
completion = client.chat.completions.create(
125+
model="Qwen/Qwen2.5-3B-Instruct",
126+
messages=[
127+
{"role": "user", "content": "Generate a JSON for the most iconic car from the 90s."}
128+
],
129+
extra_body={"guided_json": json_schema},
130+
)
131+
print(completion.choices[0].message.content)
132+
```
133+
134+
**Example output:**
135+
136+
```json
137+
{
138+
"brand": "Toyota",
139+
"model": "Supra",
140+
"car_type": "coupe"
141+
}
142+
```
143+
144+
### **4. Guided grammar**
145+
146+
Guided grammar uses an Extended Backus-Naur Form (EBNF) grammar syntax to define complex output structures, such as SQL queries.
147+
148+
```python
149+
completion = client.chat.completions.create(
150+
model="Qwen/Qwen2.5-3B-Instruct",
151+
messages=[
152+
{"role": "user", "content": "Generate a SQL query to find all users older than 30."}
153+
],
154+
extra_body={
155+
"guided_grammar": """
156+
query ::= "SELECT" fields "FROM users WHERE" condition;
157+
fields ::= "name, age" | "*";
158+
condition ::= "age >" number;
159+
number ::= [0-9]+;
160+
"""
161+
},
162+
)
163+
print(completion.choices[0].message.content)
164+
```
165+
166+
**Example output:**
167+
168+
```sql
169+
SELECT * FROM users WHERE age > 30;
170+
```
171+
172+
## **Next steps**
173+
174+
To start integrating structured outputs into your projects:
175+
176+
1. **Explore the documentation:** Check out the [official documentation](https://docs.vllm.ai/en/latest/) for more examples and detailed explanations.
177+
2. **Install vLLM locally:** Set up the inference server on your local machine using the [vLLM GitHub repository](https://github.com/vllm-project/vllm).
178+
3. **Experiment with structured outputs:** Try out different formats (choice, regex, JSON, grammar) and observe how they can simplify your workflow.
179+
4. **Deploy in production:** Once comfortable, deploy vLLM to your production environment and integrate it with your applications.
180+
181+
Structured outputs make LLMs not only powerful but also practical for real-world applications. Dive in and see what you can build!
37.2 KB
Loading

0 commit comments

Comments
 (0)