Skip to content

Commit 08d13dc

Browse files
committed
feat: add structured output documentation and reference
1 parent edc4fdf commit 08d13dc

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

README.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,50 @@ The `function_map` optional parameter maps tool names to their Python implementa
151151

152152
> **Note**: The `function_map` parameter is not required when tools are provided. However, when omitted, only the tool call with the parameters used by the model will be included in the response.
153153
154+
## Structured JSON Output
155+
156+
The SDK supports structured JSON output through the `response_format` parameter. This allows you to enforce a specific JSON schema for the model's responses, making them more predictable and easier to parse.
157+
158+
Here's an example:
159+
160+
```python
161+
from xai_grok_sdk import XAI
162+
163+
llm = XAI(
164+
api_key=api_key,
165+
model="grok-2-1212",
166+
)
167+
168+
# Request with structured JSON output
169+
response = llm.invoke(
170+
messages=[
171+
{"role": "user", "content": "What is the weather in San Francisco?"},
172+
],
173+
tool_choice="none",
174+
response_format={
175+
"type": "json_schema",
176+
"json_schema": {
177+
"name": "weather_response",
178+
"schema": {
179+
"type": "object",
180+
"properties": {
181+
"location": {"type": "string"},
182+
"weather": {"type": "string"},
183+
},
184+
"required": ["location", "weather"],
185+
"additionalProperties": False,
186+
},
187+
"strict": True,
188+
},
189+
},
190+
)
191+
192+
response_message = response.choices[0].message
193+
print(response_message)
194+
```
195+
196+
The response will be a JSON object that strictly follows the defined schema. For more advanced schema options, including Pydantic types and formats, refer to the [xAI API documentation on structured outputs](https://docs.x.ai/docs/guides/structured-outputs).
197+
154198
## API Reference
155199

156200
### XAI Class

0 commit comments

Comments
 (0)