Structured Outputs and Code Execution
On this page
Updated November 2, 2026. Based on xAI documentation: with the
xai-sdk, structured outputs combine with tools by creating the conversation (client.chat.create(..., tools=[code_execution()])), then callingchat.parse(Schema), which returns the response and the typed object; the previous example calledclient.chat.parse(...)with Chat Completions arguments, a method that doesn’t exist in any SDK. Sources: Structured Outputs · Code Execution.
Execute Code and Structure Results
Combining structured outputs with code execution lets the model calculate results and return them in a structured format. The model writes code, executes it in a sandboxed environment, and formats the output according to your schema.
Grok 4 and Later Feature
Like web search, this combination is reserved for Grok 4 and later models—meaning the entire current lineup (Grok 4.5, Grok 4.3, grok-4.20 variants). Earlier models didn’t support combining tools with structured outputs.
Typical Use Case: Precise Calculations
The main advantage of code execution with structured outputs is calculation precision. LLMs regularly make arithmetic errors. By executing code, results are mathematically exact.
from pydantic import BaseModel
from xai_sdk import Client
from xai_sdk.chat import user
from xai_sdk.tools import code_execution
client = Client() # key read from XAI_API_KEY
class FinancialAnalysis(BaseModel):
total_revenue: float
total_cost: float
gross_margin: float
margin_percentage: float
most_profitable_product: str
least_profitable_product: str
chat = client.chat.create(
model="grok-4.20-0309-reasoning",
tools=[code_execution()],
)
chat.append(user("""Here are the quarterly sales:
- Product A: 150 units at €45, unit cost €28
- Product B: 320 units at €22, unit cost €15
- Product C: 85 units at €120, unit cost €78
Calculate the complete financial analysis."""))
response, parsed = chat.parse(FinancialAnalysis)
print(f"Gross margin: €{parsed.gross_margin}")
print(f"Margin: {parsed.margin_percentage}%")
print(f"Best product: {parsed.most_profitable_product}")
The model will write a Python script to perform the calculations, execute it, and then format the results into the FinancialAnalysis schema.
Example: Statistical Analysis
class DescriptiveStatistics(BaseModel):
mean: float
median: float
std_dev: float
minimum: float
maximum: float
quartile_1: float
quartile_3: float
value_count: int
chat = client.chat.create(
model="grok-4.20-0309-reasoning",
tools=[code_execution()],
)
chat.append(user("""Calculate the descriptive statistics for this data:
[23, 45, 12, 67, 34, 89, 56, 78, 41, 33, 61, 25,
72, 48, 55, 39, 64, 71, 28, 50]"""))
response, parsed = chat.parse(DescriptiveStatistics)
print(f"Mean: {parsed.mean}")
print(f"Std dev: {parsed.std_dev}")
Combine Web Search and Code Execution
You can enable both tools simultaneously:
class MarketAnalysis(BaseModel):
company: str
current_price: float
change_30d: float
avg_volume: float
trend: str
recommendation: str
from xai_sdk.tools import web_search
chat = client.chat.create(
model="grok-4.20-0309-reasoning",
tools=[web_search(), code_execution()],
)
chat.append(user("Analyze Apple stock over the last 30 days"))
response, parsed = chat.parse(MarketAnalysis)
The model will fetch recent data from the web, then use code execution to calculate changes and averages.
Code Execution Limits
- The execution environment is isolated and ephemeral
- Common Python packages come preinstalled (NumPy, Pandas, Matplotlib, SciPy)
- Execution time and memory are bounded
- No network access from executed code
- Files created don’t persist between calls
Key Takeaways
- Code execution + structured outputs requires Grok 4 minimum—the entire current lineup is compatible
- The model writes and executes code for precise calculations
- Enable the tool with
code_execution()in the xAI SDK, or{"type": "code_interpreter"}in the Responses API, then get the typed object withchat.parse(Schema) - Combinable with
web_searchto search then calculate - Ideal for financial, statistical, and mathematical analysis
- Calculated results are exact, unlike LLM estimates