🎨 Data Designer Tutorial: Structured Outputs, Jinja Expressions, and Conditional Generation¶
📚 What you'll learn¶
In this notebook, we will continue our exploration of Data Designer, demonstrating more advanced data generation using structured outputs, Jinja expressions, and conditional generation with skip.when.
If this is your first time using Data Designer, we recommend starting with the first notebook in this tutorial series.
📦 Import Data Designer¶
data_designer.configprovides access to the configuration API.DataDesigneris the main interface for data generation.
import data_designer.config as dd
from data_designer.interface import DataDesigner
⚙️ Initialize the Data Designer interface¶
DataDesigneris the main object that is used to interface with the library.When initialized without arguments, the default model providers are used.
data_designer = DataDesigner()
🎛️ Define model configurations¶
Each
ModelConfigdefines a model that can be used during the generation process.The "model alias" is used to reference the model in the Data Designer config (as we will see below).
The "model provider" is the external service that hosts the model (see the model config docs for more details).
By default, we use build.nvidia.com as the model provider.
# This name is set in the model provider configuration.
MODEL_PROVIDER = "nvidia"
# The model ID is from build.nvidia.com.
MODEL_ID = "nvidia/nemotron-3-nano-30b-a3b"
# We choose this alias to be descriptive for our use case.
MODEL_ALIAS = "nemotron-nano-v3"
model_configs = [
dd.ModelConfig(
alias=MODEL_ALIAS,
model=MODEL_ID,
provider=MODEL_PROVIDER,
inference_parameters=dd.ChatCompletionInferenceParams(
temperature=1.0,
top_p=1.0,
max_tokens=2048,
extra_body={"chat_template_kwargs": {"enable_thinking": False}},
),
)
]
🏗️ Initialize the Data Designer Config Builder¶
The Data Designer config defines the dataset schema and generation process.
The config builder provides an intuitive interface for building this configuration.
The list of model configs is provided to the builder at initialization.
config_builder = dd.DataDesignerConfigBuilder(model_configs=model_configs)
🧑🎨 Designing our data¶
We will again create a product review dataset, but this time we will use structured outputs and Jinja expressions.
Structured outputs let you specify the exact schema of the data you want to generate.
Data Designer supports schemas specified using either json schema or Pydantic data models (recommended).
We'll define our structured outputs using Pydantic data models
💡 Why Pydantic?
Pydantic models provide better IDE support and type validation.
They are more Pythonic than raw JSON schemas.
They integrate seamlessly with Data Designer's structured output system.
from decimal import Decimal
from typing import Literal
from pydantic import BaseModel, Field
# We define a Product schema so that the name, description, and price are generated
# in one go, with the types and constraints specified.
class Product(BaseModel):
name: str = Field(description="The name of the product")
description: str = Field(description="A description of the product")
price: Decimal = Field(description="The price of the product", ge=10, le=1000, decimal_places=2)
class ProductReview(BaseModel):
rating: int = Field(description="The rating of the product", ge=1, le=5)
customer_mood: Literal["irritated", "mad", "happy", "neutral", "excited"] = Field(
description="The mood of the customer"
)
review: str = Field(description="A review of the product")
Next, let's design our product review dataset using a few more tricks compared to the previous notebook.
# Since we often only want a few attributes from Person objects, we can
# set drop=True in the column config to drop the column from the final dataset.
config_builder.add_column(
dd.SamplerColumnConfig(
name="customer",
sampler_type=dd.SamplerType.PERSON_FROM_FAKER,
params=dd.PersonFromFakerSamplerParams(),
drop=True,
)
)
config_builder.add_column(
dd.SamplerColumnConfig(
name="product_category",
sampler_type=dd.SamplerType.CATEGORY,
params=dd.CategorySamplerParams(
values=[
"Electronics",
"Clothing",
"Home & Kitchen",
"Books",
"Home Office",
],
),
)
)
config_builder.add_column(
dd.SamplerColumnConfig(
name="product_subcategory",
sampler_type=dd.SamplerType.SUBCATEGORY,
params=dd.SubcategorySamplerParams(
category="product_category",
values={
"Electronics": [
"Smartphones",
"Laptops",
"Headphones",
"Cameras",
"Accessories",
],
"Clothing": [
"Men's Clothing",
"Women's Clothing",
"Winter Coats",
"Activewear",
"Accessories",
],
"Home & Kitchen": [
"Appliances",
"Cookware",
"Furniture",
"Decor",
"Organization",
],
"Books": [
"Fiction",
"Non-Fiction",
"Self-Help",
"Textbooks",
"Classics",
],
"Home Office": [
"Desks",
"Chairs",
"Storage",
"Office Supplies",
"Lighting",
],
},
),
)
)
config_builder.add_column(
dd.SamplerColumnConfig(
name="target_age_range",
sampler_type=dd.SamplerType.CATEGORY,
params=dd.CategorySamplerParams(values=["18-25", "25-35", "35-50", "50-65", "65+"]),
)
)
# Sampler columns support conditional params, which are used if the condition is met.
# In this example, we set the review style to rambling if the target age range is 18-25.
# Note conditional parameters are only supported for Sampler column types.
config_builder.add_column(
dd.SamplerColumnConfig(
name="review_style",
sampler_type=dd.SamplerType.CATEGORY,
params=dd.CategorySamplerParams(
values=["rambling", "brief", "detailed", "structured with bullet points"],
weights=[1, 2, 2, 1],
),
conditional_params={
"target_age_range == '18-25'": dd.CategorySamplerParams(values=["rambling"]),
},
)
)
# Optionally validate that the columns are configured correctly.
data_designer.validate(config_builder)
Next, we will use more advanced Jinja expressions to create new columns.
Jinja expressions let you:
Access nested attributes:
{{ customer.first_name }}Combine values:
{{ customer.first_name }} {{ customer.last_name }}Use conditional logic:
{% if condition %}...{% endif %}
# We can create new columns using Jinja expressions that reference
# existing columns, including attributes of nested objects.
config_builder.add_column(
dd.ExpressionColumnConfig(name="customer_name", expr="{{ customer.first_name }} {{ customer.last_name }}")
)
config_builder.add_column(dd.ExpressionColumnConfig(name="customer_age", expr="{{ customer.age }}"))
config_builder.add_column(
dd.LLMStructuredColumnConfig(
name="product",
prompt=(
"Create a product in the '{{ product_category }}' category, focusing on products "
"related to '{{ product_subcategory }}'. The target age range of the ideal customer is "
"{{ target_age_range }} years old. The product should be priced between $10 and $1000."
),
output_format=Product,
model_alias=MODEL_ALIAS,
)
)
# We can even use if/else logic in our Jinja expressions to create more complex prompt patterns.
config_builder.add_column(
dd.LLMStructuredColumnConfig(
name="customer_review",
prompt=(
"Your task is to write a review for the following product:\n\n"
"Product Name: {{ product.name }}\n"
"Product Description: {{ product.description }}\n"
"Price: {{ product.price }}\n\n"
"Imagine your name is {{ customer_name }} and you are from {{ customer.city }}, {{ customer.state }}. "
"Write the review in a style that is '{{ review_style }}'."
"{% if target_age_range == '18-25' %}"
"Make sure the review is more informal and conversational.\n"
"{% else %}"
"Make sure the review is more formal and structured.\n"
"{% endif %}"
"The review field should contain only the review, no other text."
),
output_format=ProductReview,
model_alias=MODEL_ALIAS,
)
)
data_designer.validate(config_builder)
🚦 Conditional generation with skip.when¶
So far, every column is generated for every row. But sometimes an expensive LLM column only makes sense for a subset of rows — for example, a detailed complaint analysis is only useful when the review is negative.
Data Designer lets you skip column generation on a per-row basis using SkipConfig.
Skipped rows receive None by default, but you can provide a sentinel value with
skip=dd.SkipConfig(when="...", value="N/A") to write a specific value instead.
There are three patterns to know:
| Pattern | How | Effect |
|---|---|---|
| Expression gate | skip=dd.SkipConfig(when="...") |
Skip this column when the Jinja2 expression is truthy |
| Skip propagation (default) | Downstream column depends on a skipped column | Automatically skipped too (propagate_skip=True by default) |
| Propagation opt-out | propagate_skip=False on the downstream column |
Always generates, even if an upstream was skipped |
Pattern 1 — Expression gate. Only generate a detailed complaint analysis when the customer gave a low rating (1 or 2 stars).
Rows where the rating is 3 or higher will get None for this column.
config_builder.add_column(
dd.LLMTextColumnConfig(
name="complaint_analysis",
model_alias=MODEL_ALIAS,
prompt=(
"A customer reviewed '{{ product.name }}' ({{ product_category }} / {{ product_subcategory }}).\n\n"
"Review: {{ customer_review.review }}\n"
"Rating: {{ customer_review.rating }}/5\n"
"Mood: {{ customer_review.customer_mood }}\n\n"
"Write a short root-cause analysis of why this customer is unhappy "
"and suggest one concrete improvement the product team could make."
),
skip=dd.SkipConfig(when="{{ customer_review.rating > 2 }}"),
)
)
Pattern 2 — Skip propagation. action_items depends on complaint_analysis.
When complaint_analysis is skipped, action_items auto-skips too because
propagate_skip defaults to True.
config_builder.add_column(
dd.LLMTextColumnConfig(
name="action_items",
model_alias=MODEL_ALIAS,
prompt=(
"Based on this complaint analysis:\n"
"{{ complaint_analysis }}\n\n"
"List 2-3 concrete action items for the product team."
),
)
)
Pattern 3 — Propagation opt-out. review_summary also depends on complaint_analysis,
but sets propagate_skip=False so it always generates. The prompt uses a Jinja conditional
to handle the case where complaint_analysis is None.
config_builder.add_column(
dd.LLMTextColumnConfig(
name="review_summary",
model_alias=MODEL_ALIAS,
propagate_skip=False,
prompt=(
"Summarize this product review in one sentence:\n"
"Product: {{ product.name }}\n"
"Rating: {{ customer_review.rating }}/5\n"
"Review: {{ customer_review.review }}\n"
"{% if complaint_analysis %}"
"Complaint analysis: {{ complaint_analysis }}\n"
"{% endif %}"
),
)
)
data_designer.validate(config_builder)
🔁 Iteration is key – preview the dataset!¶
Use the
previewmethod to generate a sample of records quickly.Inspect the results for quality and format issues.
Adjust column configurations, prompts, or parameters as needed.
Re-run the preview until satisfied.
preview = data_designer.preview(config_builder, num_records=2)
# Run this cell multiple times to cycle through the 2 preview records.
# Look for rows where complaint_analysis and action_items are None (skipped)
# vs rows where they were generated (low-rated reviews).
preview.display_sample_record()
# The preview dataset is available as a pandas DataFrame.
# Notice that complaint_analysis, action_items, and review_summary columns
# reflect the skip behavior: None for skipped rows, generated text otherwise.
preview.dataset
📊 Analyze the generated data¶
Data Designer automatically generates a basic statistical analysis of the generated data.
This analysis is available via the
analysisproperty of generation result objects.
# Print the analysis as a table.
preview.analysis.to_report()
🆙 Scale up!¶
Happy with your preview data?
Use the
createmethod to submit larger Data Designer generation jobs.
results = data_designer.create(config_builder, num_records=10, dataset_name="tutorial-2")
# Load the generated dataset as a pandas DataFrame.
dataset = results.load_dataset()
dataset.head()
# Load the analysis results into memory.
analysis = results.load_analysis()
analysis.to_report()
⏭️ Next Steps¶
Check out the following notebook to learn more about: