Azure OpenAI for big data
The Azure OpenAI service can be used to solve a large number of natural language tasks through chat, responses, and embedding APIs. To make it easier to scale your prompting workflows from a few examples to large datasets of examples, we have integrated the Azure OpenAI service with the distributed machine learning library SynapseML. This integration makes it easy to use the Apache Spark distributed computing framework to process millions of prompts with the OpenAI service. This tutorial shows how to apply large language models at a distributed scale using Azure OpenAI.
Prerequisites
The key prerequisites for this quickstart include a working Azure OpenAI resource, and an Apache Spark cluster with SynapseML installed. We suggest creating a Synapse workspace, but an Azure Databricks, HDInsight, or Spark on Kubernetes, or even a python environment with the pyspark package will work.
- An Azure OpenAI resource – request access here before creating a resource
- Create a Synapse workspace
- Create a serverless Apache Spark pool
Import this guide as a notebook
The next step is to add this code into your Spark cluster. You can either create a notebook in your Spark platform and copy the code into this notebook to run the demo. Or download the notebook and import it into Synapse Analytics
- Download this demo as a notebook (select Raw, then save the file)
- Import the notebook.
- If you are using Synapse Analytics into the Synapse Workspace
- If your are using Databricks import into the Databricks Workspace.
- If you are using Fabric import into the Fabric Workspace
- Install SynapseML on your cluster. See the installation instructions for Synapse at the bottom of the SynapseML website.
- If you are using Fabric, please check Installation Guide. This requires pasting an extra cell at the top of the notebook you imported.
- Connect your notebook to a cluster and follow along, editing and running the cells.
Fill in service information
Next, edit the cell in the notebook to point to your service. In particular set the service_name, deployment_name, location, and key variables to match them to your OpenAI service:
from synapse.ml.core.platform import find_secret
# Fill in the following lines with your service information
# Learn more about selecting which embedding model to choose: https://openai.com/blog/new-and-improved-embedding-model
service_name = "synapseml-openai-3"
deployment_name = "gpt-6-luna"
deployment_name_embeddings = "text-embedding-ada-002"
key = find_secret(
secret_name="openai-api-key-3", keyvault="mmlspark-build-keys"
) # please replace this line with your key as a string
assert key is not None and service_name is not None
Create a dataset of prompts
Next, create a dataframe consisting of a series of rows, with one prompt per row.
You can also load data directly from ADLS or other databases. For more information on loading and preparing Spark dataframes, see the Apache Spark data loading guide.
# spark session is assumed to be created in the environment already such as in Fabric notebooks with Spark environment
df = spark.createDataFrame(
[
("Hello my name is",),
("The best code is code thats",),
("SynapseML is ",),
]
).toDF("prompt")
More Usage Examples
Generating Text Embeddings
In addition to completing text, we can also embed text for use in downstream algorithms or vector retrieval architectures. Creating embeddings allows you to search and retrieve documents from large collections and can be used when prompt engineering isn't sufficient for the task.
For more information on using OpenAIEmbedding see our embedding guide.
from synapse.ml.services.openai import OpenAIEmbedding
embedding = (
OpenAIEmbedding()
.setSubscriptionKey(key)
.setDeploymentName(deployment_name_embeddings)
.setCustomServiceName(service_name)
.setTextCol("prompt")
.setErrorCol("error")
.setOutputCol("embeddings")
)
display(embedding.transform(df).show(truncate=False))
Chat Completion
Chat models understand sequences of messages instead of a single prompt. The OpenAIChatCompletion transformer exposes this functionality at scale.
from synapse.ml.services.openai import OpenAIChatCompletion
from pyspark.sql import Row
from pyspark.sql.types import *
def make_message(role, content):
return Row(role=role, content=content, name=role)
chat_df = spark.createDataFrame(
[
(
[
make_message(
"system", "You are an AI chatbot with red as your favorite color"
),
make_message("user", "Whats your favorite color"),
],
),
(
[
make_message("system", "You are very excited"),
make_message("user", "How are you today"),
],
),
]
).toDF("messages")
chat_completion = (
OpenAIChatCompletion()
.setSubscriptionKey(key)
.setDeploymentName(deployment_name)
.setCustomServiceName(service_name)
.setMessagesCol("messages")
.setOutputCol("chat_completions")
.setErrorCol("chat_completions_error")
)
display(
chat_completion.transform(chat_df)
.select("messages", "chat_completions.choices.message.content")
.show(truncate=False)
)
Multimodal Chat Completions
Run this example with a vision-capable deployment. Each user message contains a text part and an image URL part. Define an explicit Spark schema so the nested image_url.url and optional detail fields are preserved when OpenAIChatCompletion builds the request.
from pyspark.sql import Row
from pyspark.sql.types import ArrayType, StringType, StructField, StructType
from synapse.ml.services.openai import OpenAIChatCompletion
image_url_schema = StructType(
[
StructField("url", StringType(), False),
StructField("detail", StringType(), True),
]
)
content_part_schema = StructType(
[
StructField("type", StringType(), False),
StructField("text", StringType(), True),
StructField("image_url", image_url_schema, True),
]
)
message_schema = StructType(
[
StructField("role", StringType(), False),
StructField("content", ArrayType(content_part_schema), False),
StructField("name", StringType(), True),
]
)
multimodal_schema = StructType(
[StructField("messages", ArrayType(message_schema), False)]
)
multimodal_chat_df = spark.createDataFrame(
[
Row(
messages=[
Row(
role="user",
content=[
Row(
type="text",
text="Describe this image in one sentence.",
image_url=None,
),
Row(
type="image_url",
text=None,
image_url=Row(
url="https://mmlspark.blob.core.windows.net/datasets/OCR/test2.png",
detail="low",
),
),
],
name=None,
)
]
)
],
schema=multimodal_schema,
)
multimodal_chat = (
OpenAIChatCompletion()
.setSubscriptionKey(key)
.setDeploymentName(deployment_name)
.setCustomServiceName(service_name)
.setMessagesCol("messages")
.setOutputCol("multimodal_chat_completions")
.setErrorCol("multimodal_chat_errors")
)
multimodal_chat.transform(multimodal_chat_df).select(
"messages",
"multimodal_chat_completions.choices.message.content",
"multimodal_chat_errors",
).show(truncate=False)
Chat Completion with Reasoning Models
OpenAIChatCompletion, OpenAIResponses, and OpenAIPrompt default to the deployment name gpt-6-luna when no deployment is configured. Explicit scalar deployments, deployment columns, and OpenAIDefaults.set_deployment_name(...) take precedence. OpenAIPrompt.setModel(...) remains an alternative on OpenAI v1 and Responses endpoints when no deployment is explicitly set. On legacy Chat endpoints, a model-only configuration raises an error; use setDeploymentName(...) to select the deployment. Your endpoint must offer the selected deployment; use its actual name if it differs. Embeddings, legacy completions, and Foundry model selection are unchanged. This fallback does not inspect input modality or select a different model for files; explicitly choose a compatible deployment for multimodal inputs.
When reasoning is enabled:
- Leave
temperature,top_p, andseedunset. - Use
reasoning_effortandverbositywhen supported by your deployment. SynapseML forwards the effort string without a client-side allowlist; values such asnone,minimal,low,medium,high,xhigh, ormaxare model-specific, not universally supported. Check the deployment's documentation before combining reasoning and sampling settings.
The deployment, credentials, and endpoint can still be set globally using OpenAIDefaults.
from synapse.ml.services.openai import OpenAIChatCompletion
from synapse.ml.services.openai.OpenAIDefaults import OpenAIDefaults
# Set global defaults without unsupported sampling parameters
defaults = OpenAIDefaults()
defaults.set_deployment_name(deployment_name)
defaults.set_subscription_key(key)
defaults.set_URL(f"https://{service_name}.openai.azure.com/")
chat_completion = (
OpenAIChatCompletion()
.setReasoningEffort("low")
.setVerbosity("low")
.setMessagesCol("messages")
.setOutputCol("chat_completions")
.setErrorCol("chat_completions_error")
)
display(
chat_completion.transform(chat_df)
.select("messages", "chat_completions.choices.message.content")
.show(truncate=False)
)
Retired Completions API
The OpenAICompletion transformer has been removed because the legacy Completions API is deprecated and retired. Use OpenAIChatCompletion, OpenAIPrompt with chat_completions or responses, or OpenAIResponses for text generation workloads.
Structured JSON output with json_schema
Use the new responseFormat option json_schema to force the model to return JSON strictly matching a provided JSON Schema. This improves reliability for downstream parsing and analytics.
Key points:
- Set
responseFormatto a dict containingtype="json_schema"and a nestedjson_schemaobject (JSON string form not supported). - Provide the schema as a Python dict / Scala Map plus a
nameand optionalstrictflag. - Bare
json_schemastring is rejected; supply the full dict form. - Allowed simple String values for
responseFormat:text,json_object. - For
json_schemaminimal validation only checks the presence of thejson_schemakey; the nested schema is passed through unchanged. - The model output will be constrained to the schema (no extra properties when
additionalProperties: false).
Summary table
| Type | How to set | Requires nested schema | Notes |
|---|---|---|---|
| text | String("text") | No | Raw string output |
| json_object | String("json_object") | No | Model attempts well‑formed JSON (not strictly validated) |
| json_schema | Dict/Map only | Yes | Strict; reject bare string or JSON string form |
Below we request a single field answer as structured JSON.
from synapse.ml.services.openai import OpenAIChatCompletion
from pyspark.sql import Row
# Define the JSON Schema we want the model to satisfy
schema = {
"type": "object",
"properties": {"answer": {"type": "string"}},
"required": ["answer"],
"additionalProperties": False,
}
# Single user message requesting structured output
messages_df = spark.createDataFrame(
[
(
[
Row(
role="user",
content="What is the capital of France?",
)
],
)
]
).toDF("messages")
chat_structured = (
OpenAIChatCompletion()
.setSubscriptionKey(key)
.setDeploymentName(deployment_name)
.setCustomServiceName(service_name)
.setMessagesCol("messages")
.setResponseFormat(
{
"type": "json_schema",
"json_schema": {
"name": "answer_schema",
"strict": True,
"schema": schema,
},
}
)
.setOutputCol("chat_structured")
.setErrorCol("chat_structured_error")
)
display(
chat_structured.transform(messages_df)
.select("chat_structured.choices.message.content")
.show(truncate=False)
)
# The returned content should be a JSON object: {\"answer\": \"Paris\"}
Schema-only structured output
In development builds with setResponseSchema, you can pass the inner JSON Schema directly instead of constructing the response-format envelope. The helper defaults to name="response_schema" and strict=True, and accepts an optional name and strict flag.
OpenAIChatCompletion, OpenAIResponses, and OpenAIPrompt all support this method. Each stage uses the correct envelope for its API. Existing setResponseFormat behavior is unchanged.
| Desired output | Configuration |
|---|---|
| Plain text | setResponseFormat("text") or setResponseFormat({"type": "text"}) |
| An arbitrary JSON object | setResponseFormat("json_object") or setResponseFormat({"type": "json_object"}) |
| A supplied inner JSON Schema | setResponseSchema(schema) |
| An already wrapped or named response format | setResponseFormat(response_format) |
The text and JSON-object selectors do not acquire a schema envelope. Named partial formats and full Chat/Responses envelopes retain their supplied name and strictness. The legacy setResponseFormat(inner_schema) form remains supported without implicitly enabling strict mode; use setResponseSchema when you want the strict-by-default convenience API. Do not pass an already wrapped format to setResponseSchema. Pydantic conversion remains the caller's responsibility.
An unchanged static response format is serialized lazily once per stage instance and its JSON is reused for later rows. The bounded cache is replaced when the format changes and is not persisted or transferred to Spark executors; each executor-side stage instance builds its own cache. Python dictionaries and lists are copied into immutable JVM collections; Scala formats containing mutable sequences remain uncached so later changes are reflected in requests. Column-driven response formats remain row-dependent, and Responses verbosity can still vary by row while its static format is cached. The format is still included in every HTTP request; caching does not cache model responses or reduce the number of requests.
The helper does not modify the JSON Schema or infer missing fields. For strict output, supply the model's supported schema, including required and additionalProperties: False for object definitions. Pass a Python dictionary or Scala Map[String, Any], not a JSON string or Spark StructType. Dictionary keys must be strings. Scala and Java BigDecimal values and Python decimal.Decimal values retain their exact numeric values. Scala BigInt values are not supported by the parameter serializer and are rejected before configuration changes. Continue to handle errors, refusals, and incomplete responses.
from synapse.ml.services.openai import OpenAIPrompt, OpenAIResponses
from pyspark.sql import functions as F
# Reuse the inner schema, credentials, and one-row messages_df above.
country_df = spark.createDataFrame([("France",)], ["country"])
schema_e2e_cases = []
def configure_schema_stage(stage, options):
return (
stage.setSubscriptionKey(key)
.setDeploymentName(deployment_name)
.setCustomServiceName(service_name)
.setResponseSchema(schema, **options)
.setOutputCol("schema_output")
.setErrorCol("schema_error")
)
def check_schema_result(case, result, parsed):
rows = result.select("schema_error", parsed.alias("parsed")).collect()
assert len(rows) == 1, f"{case}: expected one row, got {len(rows)}"
error = rows[0]["schema_error"]
assert error is None, f"{case}: service error: {error}"
parsed_answer = rows[0]["parsed"]
assert (
parsed_answer is not None
), f"{case}: expected parsed answer struct, got {parsed_answer!r}"
answer = parsed_answer["answer"]
assert (
isinstance(answer, str) and answer.strip()
), f"{case}: expected nonempty answer string, got {answer!r}"
schema_e2e_cases.append(case)
print(f"Schema-only E2E passed: {case}")
for option_name, options in (
("defaults", {}),
("custom_non_strict", {"name": "answer_schema", "strict": False}),
):
chat_schema = configure_schema_stage(OpenAIChatCompletion(), options)
chat_result = chat_schema.setMessagesCol("messages").transform(messages_df)
chat_text = F.expr("try_element_at(schema_output.choices, 1).message.content")
check_schema_result(
f"chat/{option_name}", chat_result, F.from_json(chat_text, "answer STRING")
)
responses_schema = configure_schema_stage(OpenAIResponses(), options)
responses_result = (
responses_schema.setMessagesCol("messages")
.setApiVersion("2025-04-01-preview")
.transform(messages_df)
)
responses_text = F.expr(
"try_element_at(filter(flatten(transform("
"filter(schema_output.output, x -> x.content IS NOT NULL), x -> x.content)), "
"x -> x.type = 'output_text'), 1).text"
)
check_schema_result(
f"responses/{option_name}",
responses_result,
F.from_json(responses_text, "answer STRING"),
)
for api_type in ("chat_completions", "responses"):
prompt_schema = configure_schema_stage(OpenAIPrompt(), options)
prompt_result = (
prompt_schema.setApiType(api_type)
.setApiVersion("2025-04-01-preview")
.setPromptTemplate("What is the capital of {country}?")
.setPostProcessing("json")
.setPostProcessingOptions({"jsonSchema": "answer STRING"})
.transform(country_df)
)
check_schema_result(
f"prompt_{api_type}/{option_name}", prompt_result, F.col("schema_output")
)
assert len(schema_e2e_cases) == 8
Scala uses the same schema-only API. Use scala.collection.immutable.ListMap for each object whose key order matters; an ordinary Map does not guarantee insertion order:
import com.microsoft.azure.synapse.ml.services.openai.OpenAIChatCompletion
import scala.collection.immutable.ListMap
val schema: Map[String, Any] = ListMap(
"type" -> "object",
"properties" -> ListMap("answer" -> Map("type" -> "string")),
"required" -> Seq("answer"),
"additionalProperties" -> false
)
val chat = new OpenAIChatCompletion().setResponseSchema(schema)
chat.setResponseSchema(schema, "answer_schema", strict = true)
OpenAIChatCompletion still returns the response envelope. Use Spark's built-in from_json on choices[0].message.content to create typed columns, or configure OpenAIPrompt with JSON post-processing. setResponseSchema does not change the output column's type.
ResponseFormat Options Quick Tests
Below we validate text, json_object, and json_schema across APIs in separate cells for clarity.
from synapse.ml.services.openai import OpenAIChatCompletion
from pyspark.sql import Row
messages_df = spark.createDataFrame(
[([Row(role="user", content="Say hello")],)], ["messages"]
)
chat_text = (
OpenAIChatCompletion()
.setSubscriptionKey(key)
.setDeploymentName(deployment_name)
.setCustomServiceName(service_name)
.setMessagesCol("messages")
.setResponseFormat("text")
.setOutputCol("chat_text")
)
display(
chat_text.transform(messages_df)
.select("chat_text.choices.message.content")
.show(truncate=False)
)
messages_df = spark.createDataFrame(
[([Row(role="user", content="Return a JSON object with key greeting")],)],
["messages"],
)
chat_json_obj = (
OpenAIChatCompletion()
.setSubscriptionKey(key)
.setDeploymentName(deployment_name)
.setCustomServiceName(service_name)
.setMessagesCol("messages")
.setResponseFormat("json_object")
.setOutputCol("chat_json_obj")
)
display(
chat_json_obj.transform(messages_df)
.select("chat_json_obj.choices.message.content")
.show(truncate=False)
)
Responses API Structured JSON with json_schema (flattened form)
For the Responses API, you can pass a flattened json_schema dict: top-level name, strict, and schema keys.
from synapse.ml.services.openai import OpenAIPrompt
schema = {
"type": "object",
"properties": {"answer": {"type": "string"}},
"required": ["answer"],
"additionalProperties": False,
}
df = spark.createDataFrame(
[("France", "capital"), ("Germany", "capital")], ["text", "category"]
)
prompt_flat = (
OpenAIPrompt()
.setSubscriptionKey(key)
.setDeploymentName(deployment_name)
.setCustomServiceName(service_name)
.setApiType("responses")
.setApiVersion("2025-04-01-preview")
.setPromptTemplate("What is the {category} of {text}.")
.setResponseFormat(
{
"type": "json_schema",
"name": "answer_schema",
"strict": True,
"schema": schema,
}
)
.setOutputCol("out_flat")
)
display(prompt_flat.transform(df).select("out_flat").show(truncate=False))
Invalid: Bare json_schema String
Attempting to set responseFormat to the bare string json_schema should raise an error.
try:
OpenAIPrompt().setResponseFormat("json_schema")
except Exception as e:
print("Expected error:", e)
Additional inference controls and compatibility
Breaking compatibility change for Chat pipelines: OpenAIChatCompletion and OpenAIPrompt in Chat mode now reject explicitly set echo, bestOf, and cacheLevel during request construction instead of forwarding them. This fails the Spark task rather than returning a per-row provider error, including for previously saved stages and custom endpoints that accepted or ignored these fields. Clear these settings before using those pipelines. Legacy Completions behavior is unchanged; cacheLevel is not the new prompt-cache protocol.
Behavior change for Responses sampling: Explicit and global temperature / top_p settings are now forwarded even when the deployment name contains gpt-5; previously, they were silently dropped. The provider validates whether the model and reasoning mode support them, so an existing pipeline can now receive per-row provider errors for settings it previously ignored. Clear incompatible stage or global settings before running those pipelines. This also applies to OpenAIPrompt in Responses mode.
The following controls are available on the low-level stages and are forwarded by OpenAIPrompt to its selected API. Each has a set...Col(...) alternative; a column binding replaces the scalar binding, and null row values omit that option. Python setParams(...), copy, and save/load preserve these settings.
| Control | API and wire behavior |
|---|---|
setServiceTier("priority"), setSafetyIdentifier("opaque-id"), setMetadata({"job": "example"}) | Chat and Responses: service_tier, safety_identifier, metadata |
setReasoning({"effort": "max", "context": "all_turns", "mode": "standard", "summary": "auto"}) | Responses reasoning object. setReasoningEffort(...) remains supported, but conflicting effort values raise an error, including an effort configured globally through OpenAIDefaults. Clear a conflicting global with OpenAIDefaults().reset_reasoning_effort() or configure a matching per-stage effort. Chat uses setReasoningEffort(...), not this object. |
setInclude(["reasoning.encrypted_content"]), setTruncation("disabled") | Responses include and truncation |
setLogProbsEnabled(True), setTopLogProbs(3) | Chat: boolean logprobs plus top_logprobs. Responses: include gains message.output_text.logprobs, preserving other entries, plus top_logprobs. Setting a count enables log probabilities. |
Existing setLogProbs(3) | Retains the integer-count API; now translates to the correct Chat/Responses fields. Do not combine with setTopLogProbs(...). Legacy Completions behavior is unchanged. |
setLogitBias({"42": -10}), setStopSequences(["END", "STOP"]) | Chat logit_bias and array-valued stop. Use either setStop(string) or setStopSequences(...), not both. |
setStore(True) / setStoreCol("persist") | Chat and Responses storage; Prompt exposes the ID in responseIdCol for stored rows. Responses sends store=false for an unset setting or a null storage-column value; only explicit true values opt in. Direct Chat sends an explicitly configured scalar false, while Prompt Chat omits the no-op scalar false. Prompt also omits no-op scalar false on Foundry. SynapseML locally rejects any resolved store value for Foundry model inference, including scalar false on a direct AIFoundryChatCompletion stage, during request construction. This fails the Spark task rather than returning a per-row provider error. |
Low-level raw outputs retain token log probabilities, effective service tier and metadata. Responses also retains reasoning summaries and encrypted content when returned. OpenAIPrompt intentionally returns text plus its configured usage/ID columns; use a low-level stage when these other raw fields are needed.
Responses rejects inherited Chat/legacy-only settings (seed, n, stop, penalties, logitBias, echo, bestOf, cacheLevel) instead of dropping or misrouting them. This includes a global seed set with Python OpenAIDefaults().set_seed(...): import OpenAIDefaults with from synapse.ml.services.openai.OpenAIDefaults import OpenAIDefaults, then call OpenAIDefaults().reset_seed() before using Responses in the same session. Use per-stage seeds for Chat when mixing APIs. Chat rejects legacy-only echo, bestOf, and cacheLevel. Neither API treats cacheLevel as the new prompt-cache protocol.
Streaming, tool orchestration, background polling, arbitrary conversation items, audio output and prediction are not implemented by these synchronous text transformers. A forwarded setting does not establish that a particular Azure/OpenAI deployment supports it.
Working with Usage Statistics
The following examples show how to enable usage tracking by setting the usageCol parameter. When set, usage statistics are returned in a separate column alongside the model output.
Chat Completions with usageCol
Set the usageCol parameter to get usage statistics in a separate column.
from synapse.ml.services.openai import OpenAIPrompt
chat_usage_prompt = (
OpenAIPrompt()
.setSubscriptionKey(key)
.setDeploymentName(deployment_name)
.setCustomServiceName(service_name)
.setApiType("chat_completions")
.setUsageCol("usage") # Enable usage tracking with separate column
.setPromptTemplate("Provide a fun fact about {topic}.")
.setOutputCol("chat_output")
)
chat_usage_df = spark.createDataFrame([("Azure AI",)], ["topic"])
chat_usage_result = chat_usage_prompt.transform(chat_usage_df)
# Response is in chat_output, usage statistics are in the separate 'usage' column
display(chat_usage_result.select("chat_output", "usage").show(truncate=False))
Responses API with usageCol
responses_usage_prompt = (
OpenAIPrompt()
.setSubscriptionKey(key)
.setDeploymentName(deployment_name)
.setCustomServiceName(service_name)
.setApiType("responses")
.setUsageCol("usage") # Enable usage tracking
.setPromptTemplate("List two key capabilities of {topic}.")
.setOutputCol("responses_output")
)
responses_usage_df = spark.createDataFrame([("Azure OpenAI",)], ["topic"])
responses_usage_result = responses_usage_prompt.transform(responses_usage_df)
# Response is in responses_output, usage is in separate 'usage' column
display(responses_usage_result.select("responses_output", "usage").show(truncate=False))
Embeddings with usageCol
from synapse.ml.services.openai import OpenAIEmbedding
embedding_usage = (
OpenAIEmbedding()
.setSubscriptionKey(key)
.setCustomServiceName(service_name)
.setDeploymentName(deployment_name_embeddings)
.setUsageCol("usage") # Enable usage tracking with separate column
.setTextCol("text")
.setOutputCol("embeddings")
)
embedding_usage_df = spark.createDataFrame(
[("Usage statistics help monitor token consumption.",)], ["text"]
)
embedding_usage_result = embedding_usage.transform(embedding_usage_df)
# Embeddings are in 'embeddings' column, usage is in separate 'usage' column
display(embedding_usage_result.select("embeddings", "usage").show(truncate=False))
Responses API with store and Response Chaining
The Responses API supports storing generated model responses for later retrieval via API using the store parameter. When store=True, the response ID is returned in a separate column (auto-generated or custom via setResponseIdCol). You can chain responses together using previousResponseId (scalar) or previousResponseIdCol (per-row from column) to maintain conversation context across requests.
from synapse.ml.services.openai import OpenAIResponses
from pyspark.sql.functions import col, lit, array, struct, expr
from pyspark.sql import Row
# Create messages DataFrame
messages_df = spark.createDataFrame(
[
([Row(role="user", content="What is Python?")],),
([Row(role="user", content="What is Spark?")],),
],
["messages"],
)
# First request with store=True to save response for later use
responses = (
OpenAIResponses()
.setSubscriptionKey(key)
.setDeploymentName(deployment_name)
.setCustomServiceName(service_name)
.setApiVersion("2025-04-01-preview")
.setStore(True)
.setMessagesCol("messages")
.setOutputCol("response")
)
first_result = responses.transform(messages_df).cache()
first_result.count() # Materialize to avoid re-execution
# Show response IDs (can be used for later retrieval)
display(
first_result.select(
col("response.id").alias("response_id"),
expr(
"element_at(filter(element_at(response.output, -1).content, x -> x.text is not null), 1).text"
).alias("text"),
).show(truncate=80)
)
# Chain responses using previousResponseIdCol
with_ids = first_result.withColumn("prev_id", col("response.id"))
follow_up_df = with_ids.select(
col("prev_id"),
array(
struct(lit("user").alias("role"), lit("Give me an example").alias("content"))
).alias("messages"),
)
chained = (
OpenAIResponses()
.setSubscriptionKey(key)
.setDeploymentName(deployment_name)
.setCustomServiceName(service_name)
.setApiVersion("2025-04-01-preview")
.setPreviousResponseIdCol("prev_id")
.setMessagesCol("messages")
.setOutputCol("chained_response")
)
chained_result = chained.transform(follow_up_df).cache()
display(
chained_result.select(
col("prev_id").alias("previous_response_id"),
expr(
"element_at(filter(element_at(chained_response.output, -1).content, x -> x.text is not null), 1).text"
).alias("chained_text"),
).show(truncate=80)
)
OpenAIPrompt with store and Response Chaining
You can also use store with OpenAIPrompt for a simpler API. When store=True, the response ID is returned in a separate column (auto-generated by default or custom via setResponseIdCol). The main output column contains only the response text.
from synapse.ml.services.openai import OpenAIPrompt
from pyspark.sql.functions import col
# Sample DataFrame
prompt_df = spark.createDataFrame([("Python",), ("Spark",)], ["topic"])
# First request with store=True - response ID in separate auto-generated column
prompt_store = (
OpenAIPrompt()
.setSubscriptionKey(key)
.setDeploymentName(deployment_name)
.setCustomServiceName(service_name)
.setApiType("responses")
.setStore(True)
.setPromptTemplate("Briefly explain {topic}")
.setOutputCol("output")
)
first_prompt_result = prompt_store.transform(prompt_df).cache()
first_prompt_result.count()
# Get the auto-generated responseIdCol name
response_id_col_name = prompt_store.getResponseIdCol()
# Response text is in 'output', response ID is in auto-generated column
display(
first_prompt_result.select(
col("topic"),
col("output").alias("response"), # Just the text
col(response_id_col_name).alias("response_id"), # ID in separate column
).show(truncate=80)
)
# Chain using previousResponseIdCol
chained_prompt = (
OpenAIPrompt()
.setSubscriptionKey(key)
.setDeploymentName(deployment_name)
.setCustomServiceName(service_name)
.setApiType("responses")
.setPreviousResponseIdCol(response_id_col_name)
.setPromptTemplate("Give me a code example")
.setOutputCol("chained_output")
)
chained_prompt_result = chained_prompt.transform(first_prompt_result).cache()
display(
chained_prompt_result.select(
col("topic"),
col(response_id_col_name).alias("previous_id"),
col("chained_output").alias("follow_up_response"),
).show(truncate=80)
)
Prompt caching: request options and input breakpoints
When many rows share instructions or reference material, put that reusable prefix before the changing question. The service can reuse eligible cached input; cache hits, latency improvements, and savings are not guaranteed. This is service-side prompt caching, not Spark DataFrame caching.
There are two different pieces of the request:
prompt_cache_optionsis a top-level request option. SynapseML accepts it throughsetPromptCacheOptions(...)orsetPromptCacheOptionsCol(...). Null fields inside an options struct remain explicit JSON nulls; a null value for the whole options column omits the option.prompt_cache_breakpointbelongs inside an input content block. In explicit mode, mark the end of the stable prefix. A DataFrame options column is not an input breakpoint.
Breakpoint objects, including nested arrays and maps, must contain JSON-compatible values. Null array elements are retained as JSON null, including in arrays of structs, arrays, or maps; null struct fields and map entries are omitted on both APIs. Dates, timestamps, and binary values are unsupported; numbers must be finite. NaN and positive or negative infinity are rejected locally rather than silently becoming JSON null. In OpenAIChatCompletion.transform and OpenAIResponses.transform, invalid breakpoints produce per-row validation errors in errorCol and null output values; no HTTP request is sent for those rows. These are local input errors, not provider errors or Spark task failures.
Local option validation is different: Unsupported API controls, conflicting option settings, and non-finite numbers in promptCacheOptions or reasoning columns raise request-construction exceptions that fail the Spark task rather than produce errorCol results. Earlier valid rows in that task may already have sent requests, and Spark retries can resend them, including creating duplicate stored responses when store=true. Validate or filter per-row options before transforming. Non-finite scalar cache options and reasoning values are rejected when the setter is called.
Explicit mode without input breakpoints performs no cache reads or writes. Top-level Responses instructions cannot contain a breakpoint, so the following example puts reusable instructions in a developer message's input_text content. Unset options preserve the service's implicit-caching defaults.
Saving and loading stages: Newly saved OpenAI and Foundry stages recreate their built-in HTTP handler from the constructor rather than Java-deserializing a saved function. An unset OpenAI text-deployment fallback is also recreated by the loading version; use setDeploymentName(...) to pin that choice. Explicit settings and defaults already recorded in older artifacts retain their saved behavior. Cache options and column bindings are preserved. Save stages before attaching credentials, and provide credentials after loading. Explicitly configured custom handlers and older artifacts containing serialized UDFs remain subject to the existing deserialization protection; recreate those stages from trusted configuration rather than disabling the protection.
See the official prompt-caching guide, Responses request reference, and Chat Completions reference. The guide currently describes a minimum of 1,024 visible input tokens for supported newer models. The reference below is deliberately substantial, but eligibility is decided by the service, not a local token-count check.
# Reuse the credentials and caller-selected deployment from the setup cell.
cache_base_url = f"https://{service_name}.openai.azure.com/openai/v1/"
cache_options = {"mode": "explicit", "ttl": "30m"}
catalog = "\n".join(
f"Product {number}: warranty lasts {1 + number % 3} years; returns are accepted "
"within 30 days with a receipt. Repairs require the product serial number. "
"Shipping damage must be reported within seven days. Replacement parts are "
"ordered through customer support, and expedited shipping is optional."
for number in range(1, 81)
)
stable_prefix = (
"Answer customer questions using only this product catalog. "
"Identify the product and give a concise answer.\n\n" + catalog
)
cache_questions = [
"How long is the warranty for Product 17?",
"How do I return Product 23?",
]
def cache_input(question):
return [
{
"role": "developer",
"content": [
{
"type": "input_text",
"text": stable_prefix,
"prompt_cache_breakpoint": {"mode": "explicit"},
}
],
},
{"role": "user", "content": [{"type": "input_text", "text": question}]},
]
The same request with the OpenAI Python SDK
This comparison requires an installed OpenAI Python SDK with client.responses.create and its extra_body argument. Upgrade the SDK in your notebook environment if the capability check below fails. It uses the same Azure OpenAI v1 endpoint, deployment, prefix, and options as the Spark example below. Passing extra_body={"prompt_cache_options": cache_options} adds a top-level JSON field without requiring an SDK release that declares a typed prompt_cache_options argument.
The SDK raises a provider API error for unsupported options. SynapseML preserves the provider error in its configured error column instead of maintaining a local model or cache-value whitelist.
import inspect
from openai import OpenAI
with OpenAI(api_key=key, base_url=cache_base_url) as native_client:
create_response = getattr(getattr(native_client, "responses", None), "create", None)
if (
not callable(create_response)
or "extra_body" not in inspect.signature(create_response).parameters
):
raise RuntimeError(
"Upgrade the openai SDK: this example requires responses.create(extra_body=...)."
)
native_response = native_client.responses.create(
model=deployment_name,
input=cache_input(cache_questions[0]),
reasoning={"effort": "low"},
text={"verbosity": "low"},
store=False,
extra_body={"prompt_cache_options": cache_options},
)
assert native_response.status == "completed", native_response.status
assert native_response.output_text
assert native_response.usage.input_tokens >= 1024
print(native_response.output_text)
print("cached_tokens:", native_response.usage.input_tokens_details.cached_tokens)
SynapseML: explicit request options and marked input content
Use a nested Spark schema so the breakpoint remains a JSON object rather than becoming a string. Chat content represented as an array of legacy maps cannot carry breakpoints; those rows receive a per-row validation error in errorCol, with null output and no HTTP request. The error message directs you to a nested struct content schema. Each row carries the same developer prefix and a different user question. The cache_options column below is separate request configuration; it is not included in the messages sent to the model.
from pyspark.sql import functions as F
from pyspark.sql.types import ArrayType, MapType, StringType, StructField, StructType
from synapse.ml.services.openai import OpenAIResponses
cache_part_schema = StructType(
[
StructField("type", StringType(), False),
StructField("text", StringType(), True),
StructField(
"prompt_cache_breakpoint", MapType(StringType(), StringType()), True
),
]
)
cache_message_schema = StructType(
[
StructField("role", StringType(), False),
StructField("content", ArrayType(cache_part_schema), False),
]
)
cache_schema = StructType(
[
StructField("question", StringType(), False),
StructField("messages", ArrayType(cache_message_schema), False),
StructField("cache_options", MapType(StringType(), StringType()), True),
]
)
cache_df = spark.createDataFrame(
[
(cache_questions[0], cache_input(cache_questions[0]), cache_options),
(cache_questions[1], cache_input(cache_questions[1]), {"mode": "explicit"}),
],
cache_schema,
)
cached_responses = (
OpenAIResponses()
.setUrl(cache_base_url)
.setSubscriptionKey(key)
.setDeploymentName(deployment_name)
.setMessagesCol("messages")
.setPromptCacheOptions(cache_options)
.setReasoningEffort("low")
.setVerbosity("low")
.setOutputCol("cache_response")
.setErrorCol("cache_error")
)
scalar_cache_rows = (
cached_responses.transform(cache_df)
.select(
"question",
"cache_response.output",
F.col("cache_response.usage.input_tokens_details.cached_tokens").alias(
"cached_tokens"
),
"cache_error",
)
.collect()
)
assert len(scalar_cache_rows) == len(cache_questions)
for row in scalar_cache_rows:
assert row.cache_error is None, row.cache_error
assert row.output
assert row.cached_tokens is not None and row.cached_tokens > 0, row
print(row.asDict())
Row-bound options are an additional configuration choice
setPromptCacheOptionsCol replaces the scalar binding. The second row omits ttl and lets the service choose its default lifetime; it still has an explicit input breakpoint. A null options-column value omits the entire options field. If neither setter is called, the field is also omitted—SynapseML does not disable provider-default caching.
The example uses a string-valued map because mode and ttl are strings. For mixed types, such as a string ttl and Boolean prewarm, use a Spark struct so booleans remain JSON booleans rather than becoming strings. Within a non-null options object, null struct members and map entries are forwarded as JSON null, not omitted. To omit an option as in the second row, leave its key out of the map; do not assume that null selects a service default. SynapseML forwards these serializable values and leaves their support to the service.
row_cached_responses = cached_responses.copy({}).setPromptCacheOptionsCol(
"cache_options"
)
column_cache_rows = (
row_cached_responses.transform(cache_df)
.select(
"question",
"cache_options",
F.col("cache_response.usage.input_tokens_details.cached_tokens").alias(
"cached_tokens"
),
"cache_error",
)
.collect()
)
assert len(column_cache_rows) == len(cache_questions)
for row in column_cache_rows:
assert row.cache_error is None, row.cache_error
assert row.cached_tokens is not None and row.cached_tokens > 0, row
print(row.asDict())
OpenAIPrompt with service-selected implicit caching
The high-level prompter can forward the same request options. Its ordinary templates do not insert explicit content breakpoints, so use implicit mode here; use the structured-message example above when you need to choose an explicit breakpoint.
OpenAIPrompt normalizes usage across APIs: its input_token_details map differs from the raw Responses input_tokens_details struct. Its system-message prefix differs from the explicit developer-message prefix above, so first warm this exact Prompt request, then check an immediate repeat. No cache-lifetime or eviction wait is needed.
from synapse.ml.services.openai import OpenAIPrompt
implicit_cache_prompt = (
OpenAIPrompt()
.setUrl(cache_base_url)
.setSubscriptionKey(key)
.setDeploymentName(deployment_name)
.setApiType("responses")
.setSystemPrompt(stable_prefix)
.setPromptTemplate("{question}")
.setPromptCacheOptions({"mode": "implicit", "ttl": "30m"})
.setReasoningEffort("low")
.setVerbosity("low")
.setOutputCol("cache_answer")
.setUsageCol("cache_usage")
.setErrorCol("cache_error")
)
implicit_cache_input = cache_df.select("question")
implicit_warmup_rows = (
implicit_cache_prompt.transform(implicit_cache_input)
.select("cache_answer", "cache_error")
.collect()
)
assert len(implicit_warmup_rows) == len(cache_questions)
for row in implicit_warmup_rows:
assert row.cache_error is None, row.cache_error
assert row.cache_answer
implicit_cache_rows = (
implicit_cache_prompt.transform(implicit_cache_input)
.select(
"question",
"cache_answer",
F.col("cache_usage.input_token_details")["cached_tokens"].alias(
"cached_tokens"
),
"cache_error",
)
.collect()
)
assert len(implicit_cache_rows) == len(cache_questions)
for row in implicit_cache_rows:
assert row.cache_error is None, row.cache_error
assert row.cache_answer
assert row.cached_tokens is not None and row.cached_tokens > 0, row
print(row.asDict())
Field mapping and limits
| OpenAI request/output | SynapseML |
|---|---|
model | Caller-selected setDeploymentName(...) on the v1 endpoint |
prompt_cache_options | setPromptCacheOptions(dict) or setPromptCacheOptionsCol(column) |
prompt_cache_key | setPromptCacheKey(key) or setPromptCacheKeyCol(column) |
Legacy prompt_cache_retention | setPromptCacheRetention(policy); independent of the options object's ttl |
Responses input | OpenAIResponses.setMessagesCol(...) |
Responses input[].content[].prompt_cache_breakpoint | The same nested field in the DataFrame's input_text, input_image, or input_file content |
Chat messages[].content[].prompt_cache_breakpoint | The same nested field in OpenAIChatCompletion content; text parts use type="text", not input_text |
Responses usage.input_tokens_details.cached_tokens | cache_response.usage.input_tokens_details.cached_tokens in the raw Responses output |
Chat usage.prompt_tokens_details.cached_tokens | The corresponding field under the raw Chat output |
Either API's cached tokens with OpenAIPrompt.setUsageCol("cache_usage") | F.col("cache_usage.input_token_details")["cached_tokens"] in the normalized usage map |
| Either API's cache-write tokens | Raw usage.*_tokens_details.cache_write_tokens, or normalized input_token_details["cache_write_tokens"] |
| Responses cache-write TTL breakdown | Raw usage.input_tokens_details.cache_write_tokens_details.ttl_30m_tokens / ttl_12h_tokens; normalized keys cache_write_tokens_details.ttl_30m_tokens / cache_write_tokens_details.ttl_12h_tokens |
| Responses applied options and diagnostics | Raw prompt_cache_options and prompt_cache_diagnostics; request a comparison with setPromptCacheOptions({"comparison_response_id": response_id}) |
Keep the reusable prefix and its ordering stable; place varying row content after it. Cache reads (cached_tokens) and cache writes (cache_write_tokens) are distinct counters, not interchangeable savings measures. Missing counters remain null, not zero. These examples assert error-free responses and positive cache reads immediately after warming the matching request prefix: the native request warms the explicit Responses example, and a separate Prompt request warms the implicit example. These short checks also run when CI executes the notebook; they do not wait for or qualify cache lifetime or eviction. A failed assertion means this run did not qualify cache reuse; it does not by itself identify a client defect, because provider/model support and routing also affect cache hits.
The examples use the common 30m lifetime and mode-only breakpoint object. Responses also supports 12h, and each breakpoint may override the request's lifetime. SynapseML preserves multiple breakpoint objects and their ordering; the provider validates model support and breakpoint limits. prompt_cache_options.ttl is a minimum cache lifetime, not the older prompt_cache_retention maximum-retention policy; SynapseML does not translate between them.
On providers that support Responses prewarming, set setPromptCacheOptions({"prewarm": True, "ttl": "12h"}), then omit prewarm on the generation request. Support is endpoint-specific: an Azure OpenAI v1 deployment tested with gpt-6-luna rejected prewarm as an unknown parameter, including when it was False. Do not infer prewarming support from accepted mode and ttl options. A successful prewarm can return status="completed" with an empty output array: OpenAIPrompt then returns null text, preserves usage and the stored response ID, and does not invent a content-filter error. Actual incomplete/content-filter responses still produce errors. Use the low-level OpenAIResponses output to inspect cache diagnostics; ordinary Prompt templates still do not insert explicit content breakpoints.
For separate opt-in assertion-backed qualification of Chat, Responses, Foundry model inference, prewarming and persistence, see cognitive/src/test/python/synapsemltest/services/test_OpenAICacheLive.py. Set SYNAPSEML_LIVE_CACHE_TESTS=1 and the endpoint, credential and model variables documented there. Foundry requires both an OpenAI and a third-party deployment on its own endpoint; it does not reuse the Azure OpenAI deployment name. Missing configuration produces an explicit skip, not provider qualification. Missing provider counters and unsupported options fail qualification rather than being counted as cache hits. All cache-hit checks run immediately after warm-up; accepting ttl="12h" and reporting a 12-hour write counter does not prove 12 hours of retention.