You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Jul 4, 2025. It is now read-only.
Structured outputs, or response formats, are a feature designed to generate responses in a defined JSON schema, enabling more predictable and machine-readable outputs. This is essential for applications where data consistency and format adherence are crucial, such as automated data processing, structured data generation, and integrations with other systems.
7
7
8
-
In recent developments, systems like OpenAI's models have excelled at producing these structured outputs. However, while open-source models like Llama 3.1 and Mistral Nemo offer powerful capabilities, they currently struggle to produce reliably structured JSON outputs required for advanced use cases. This often stems from the models not being specifically trained on tasks demanding strict schema adherence.
8
+
In recent developments, systems like OpenAI's models have excelled at producing these structured outputs. However, while open-source models like Llama 3.1 and Mistral Nemo offer powerful capabilities, they currently struggle to produce reliably structured JSON outputs required for advanced use cases.
9
9
10
10
This guide explores the concept of structured outputs using these models, highlights the challenges faced in achieving consistent output formatting, and provides strategies for improving output accuracy, particularly when using models that don't inherently support this feature as robustly as GPT models.
11
11
12
12
By understanding these nuances, users can make informed decisions when choosing models for tasks requiring structured outputs, ensuring that the tools they select align with their project's formatting requirements and expected accuracy.
13
13
14
-
The Structured Outputs/Response Format feature in [OpenAI](https://platform.openai.com/docs/guides/structured-outputs) is fundamentally a prompt engineering challenge. While its goal is to use system prompts to generate JSON output matching a specific schema, popular open-source models like Llama 3.1 and Mistral Nemo struggle to consistently generate exact JSON output that matches the requirements. An easy way to directly guild the model to reponse in json format in system message:
14
+
The Structured Outputs/Response Format feature in [OpenAI](https://platform.openai.com/docs/guides/structured-outputs) is fundamentally a prompt engineering challenge. While its goal is to use system prompts to generate JSON output matching a specific schema, popular open-source models like Llama 3.1 and Mistral Nemo struggle to consistently generate exact JSON output that matches the requirements. An easy way to directly guild the model to reponse in json format in system message, you just need to pass the pydantic model to `response_format`:
15
15
16
16
```
17
+
from pydantic import BaseModel
18
+
from openai import OpenAI
19
+
import json
20
+
ENDPOINT = "http://localhost:39281/v1"
21
+
MODEL = "llama3.1:8b-gguf-q4-km"
22
+
23
+
client = OpenAI(
24
+
base_url=ENDPOINT,
25
+
api_key="not-needed"
26
+
)
27
+
28
+
29
+
class CalendarEvent(BaseModel):
30
+
name: str
31
+
date: str
32
+
participants: list[str]
33
+
34
+
35
+
completion = client.beta.chat.completions.parse(
36
+
model=MODEL,
37
+
messages=[
38
+
{"role": "system", "content": "Extract the event information."},
39
+
{"role": "user", "content": "Alice and Bob are going to a science fair on Friday."},
40
+
],
41
+
response_format=CalendarEvent,
42
+
stop=["<|eot_id|>"]
43
+
)
44
+
45
+
event = completion.choices[0].message.parsed
46
+
47
+
print(json.dumps(event.dict(), indent=4))
48
+
```
49
+
50
+
The output of the model like this
51
+
52
+
```
53
+
{
54
+
"name": "science fair",
55
+
"date": "Friday",
56
+
"participants": [
57
+
"Alice",
58
+
"Bob"
59
+
]
60
+
}
61
+
```
62
+
63
+
With more complex json format, llama3.1 still struggle to response correct answer:
"explanation": "First, we need to isolate the variable x. To do this, subtract 7 from both sides of the equation.",
123
+
"explanation": "To isolate the variable x, we need to get rid of the constant term on the left-hand side. We can do this by subtracting 7 from both sides of the equation.",
70
124
"output": "8x + 7 - 7 = -23 - 7"
71
125
},
72
126
{
73
-
"explanation": "This simplifies to 8x = -30",
127
+
"explanation": "Simplifying the left-hand side, we get:",
74
128
"output": "8x = -30"
75
129
},
76
130
{
77
-
"explanation": "Next, divide both sides of the equation by 8 to solve for x.",
78
-
"output": "(8x) / 8 = -30 / 8"
131
+
"explanation": "Now, to solve for x, we need to isolate it by dividing both sides of the equation by 8.",
132
+
"output": "8x / 8 = -30 / 8"
79
133
},
80
134
{
81
-
"explanation": "This simplifies to x = -3.75",
135
+
"explanation": "Simplifying the right-hand side, we get:",
82
136
"output": "x = -3.75"
83
137
}
84
138
],
85
-
"final_output": "-3.75"
86
-
}''',
87
-
refusal=None,
88
-
role='assistant',
89
-
audio=None,
90
-
function_call=None,
91
-
tool_calls=None
92
-
)
93
-
)
94
-
],
95
-
created=1730645716,
96
-
model='_',
97
-
object='chat.completion',
98
-
service_tier=None,
99
-
system_fingerprint='_',
100
-
usage=CompletionUsage(
101
-
completion_tokens=190,
102
-
prompt_tokens=78,
103
-
total_tokens=268,
104
-
completion_tokens_details=None,
105
-
prompt_tokens_details=None
106
-
)
107
-
)
139
+
"final_answer": "There is no final answer yet, let's break it down step by step."
140
+
}
108
141
```
109
142
110
-
From the output, you can easily parse the response to get correct json format as you guild the model in the system prompt.
143
+
Even if the model can generate correct format but the information doesn't 100% accurate, the `final_answer` should be `-3.75` instead of `There is no final answer yet, let's break it down step by step.`.
111
144
112
-
Howerver, open source model like llama3.1 or mistral nemo still truggling on mimic newest OpenAI API on response format. For example, consider this request created using the OpenAI library with very simple request like [OpenAI](https://platform.openai.com/docs/guides/structured-outputs#chain-of-thought):
145
+
Another usecase for structured output with json response, you can provide the `response_format={"type" : "json_object"}`, the model will be force to generate json output.
113
146
114
147
```
115
-
from openai import OpenAI
116
-
ENDPOINT = "http://localhost:39281/v1"
117
-
MODEL = "llama3.1:8b-gguf-q4-km"
118
-
client = OpenAI(
119
-
base_url=ENDPOINT,
120
-
api_key="not-needed"
121
-
)
122
-
123
-
class Step(BaseModel):
124
-
explanation: str
125
-
output: str
126
-
127
-
128
-
class MathReasoning(BaseModel):
129
-
steps: List[Step]
130
-
final_answer: str
131
-
132
-
133
-
completion_payload = {
134
-
"messages": [
135
-
{"role": "system", "content": f"You are a helpful math tutor. Guide the user through the solution step by step.\n"},
136
-
{"role": "user", "content": "how can I solve 8x + 7 = -23"}
137
-
]
138
-
}
139
-
140
-
response = client.beta.chat.completions.parse(
141
-
top_p=0.9,
142
-
temperature=0.6,
148
+
json_format = {"song_name":"release date"}
149
+
completion = client.chat.completions.create(
143
150
model=MODEL,
144
-
messages= completion_payload["messages"],
145
-
response_format=MathReasoning
151
+
messages=[
152
+
{"role": "system", "content": f"You are a helpful assistant, you must reponse with this format: '{json_format}'"},
153
+
{"role": "user", "content": "List 10 songs for me"}
154
+
],
155
+
response_format={"type": "json_object"},
156
+
stop=["<|eot_id|>"]
146
157
)
147
-
```
148
-
149
-
The response format parsed by OpenAI before sending to the server is quite complex for the `MathReasoning` schema. Unlike GPT models, Llama 3.1 and Mistral Nemo cannot reliably generate responses that can be parsed as shown in the [OpenAI tutorial](https://platform.openai.com/docs/guides/structured-outputs/example-response). This may be due to these models not being trained on similar structured output tasks.
The response for this request by `mistral-nemo` and `llama3.1` can not be used to parse result like in the [original tutorial by openAI](https://platform.openai.com/docs/guides/structured-outputs/example-response). Maybe `llama3.1` and `mistral-nemo` didn't train with this kind of data, so it fails to handle this case.
162
+
The output will looks like this:
219
163
220
164
```
221
-
Response: {
222
-
"choices" :
223
-
[
224
-
{
225
-
"finish_reason" : null,
226
-
"index" : 0,
227
-
"message" :
228
-
{
229
-
"content" : "Here's a step-by-step guide to solving the equation 8x + 7 = -23:\n\n```json\n{\n \"name\": \"MathReasoning\",\n \"schema\": {\n \"$defs\": {\n \"Step\": {\n \"additionalProperties\": false,\n \"properties\": {\n \"explanation\": {\"title\": \"Explanation\", \"type\": \"string\"},\n \"output\": {\"title\": \"Output\", \"type\": \"string\"}\n },\n \"required\": [\"explanation\", \"output\"],\n \"title\": \"Step\",\n \"type\": \"object\"\n }\n },\n \"additionalProperties\": false,\n \"properties\": {\n \"final_answer\": {\"title\": \"Final Answer\", \"type\": \"string\"},\n \"steps\": {\n \"items\": {\"$ref\": \"#/$defs/Step\"},\n \"title\": \"Steps\",\n \"type\": \"array\"\n }\n },\n \"required\": [\"steps\", \"final_answer\"],\n \"title\": \"MathReasoning\",\n \"type\": \"object\"\n },\n \"strict\": true\n}\n```\n\n1. **Subtract 7 from both sides** to isolate the term with x:\n\n - Explanation: To get rid of the +7 on the left side, we add -7 to both sides of the equation.\n - Output: `8x + 7 - 7 = -23 - 7`\n\n This simplifies to:\n ```\n 8x = -30\n ```\n\n2. **Divide both sides by 8** to solve for x:\n\n - Explanation: To get rid of the 8 on the left side, we multiply both sides of the equation by the reciprocal of 8, which is 1/8.\n - Output: `8x / 8 = -30 / 8`\n\n This simplifies to:\n ```\n x = -3.75\n ```\n\nSo, the final answer is:\n\n- Final Answer: `x = -3.75`",
230
-
"role" : "assistant"
231
-
}
232
-
}
233
-
],
165
+
{
166
+
"Happy": "2013",
167
+
"Uptown Funk": "2014",
168
+
"Shut Up and Dance": "2014",
169
+
"Can't Stop the Feeling!": "2016",
170
+
"We Found Love": "2011",
171
+
"All About That Bass": "2014",
172
+
"Radioactive": "2012",
173
+
"SexyBack": "2006",
174
+
"Crazy": "2007",
175
+
"Viva la Vida": "2008"
176
+
}
234
177
```
235
178
236
-
237
-
238
-
239
179
## Limitations of Open-Source Models for Structured Outputs
240
180
241
181
While the concept of structured outputs is compelling, particularly for applications requiring machine-readable data, it's important to understand that not all models support this capability equally. Open-source models such as Llama 3.1 and Mistral Nemo face notable challenges in generating outputs that adhere strictly to defined JSON schemas. Here are the key limitations:
0 commit comments