Skip to main content
New tool CRON Expression Builder — preview next run times before you schedule Apex. Open the builder →
Diagram of a Data 360 code extension generative model pipeline cleaning text before LLM calls
Integration

Data 360 Code Extension Generative Model Calls: Clean First

Data 360 code extensions can call your org's generative models through the LLM gateway, and every row you send is a billable, rate-limited call. Scripts should clean, mask and dedupe rows in PySpark before calling and retry only the rows that fail, while functions can use the model to find chunk boundaries in documents.

The short answer

Run deterministic PySpark first (strip HTML, mask PII, drop near-empty rows, dedupe on a hash) and call llm_gateway_generate_text_col once per unique text, then join results back. Persist the struct's status and error fields so failed rows feed a retry pass, and use a function with runtime.llm_gateway only for search index chunking.

Key takeaways Strip HTML, mask emails and phone numbers, and filter near-empty text in PySpark before any row reaches llm_gateway_generate_text_col. Skip visits that already have an insight or a pending retry, so a recurring run pays only for new notes. Dedupe on a hash of the cleaned text, call the model once per unique text, and join the result back to every source row. Write failed rows to a separate retry DLO, then retry with a left_anti join against the results and a cap on attempts. In a chunking function, let the model place boundaries and keep merging, size caps and continuous seq_no in plain Python.

Data 360 code extensions gained LLM gateway callouts on December 3, so a PySpark script or a search index chunking function can now call any generative model configured in your org. Each row or document you send is a separate billable call that counts against rate limits, and the platform does not batch these calls yet. So the transform should do all the cheap, deterministic work before the model call and give every failed row a way back in. Below are both forms, built around a technician-notes enrichment script and a maintenance-manual chunking function.

Script or function: decide by what triggers the work

A script is a batch transform that you deploy and run. It reads DLOs or DMOs, transforms them with Spark and writes to another DLO or DMO. A function is your own logic that the platform calls from inside one of its features. Right now search index chunking is the only such feature.

Script Function
Triggered by Your deployed batch run A search index build, per document
Input DataFrame from client.read_dlo() or client.read_dmo() Document elements in request.input
Model call llm_gateway_generate_text_col() per row, or client.llm_gateway_generate_text() once runtime.llm_gateway.generate_text(...)
Output Rows via client.write_to_dlo() or client.write_to_dmo() SearchIndexChunkingV1Response(output=chunks)
On failure Error recorded in a per-row struct, job continues You check the response and raise a controlled error

If you want summaries, labels or extracted values stored as data, write a script. If you want a search index to split content at meaningful boundaries, write a function. A script reads and writes on one side only: DLO to DLO or DMO to DMO.

Both forms have the same prerequisites. The developer needs the Data Cloud Architect permission set and the Salesforce CLI with the Data Code Extension plugin. The org has to be on Developer, Enterprise, Performance or Unlimited edition, with at least one generative AI model configured. The LLM calls authenticate through an external client app. From the Agent API getting-started guide, complete only the "Create a Salesforce App" and "Obtain Credentials" sections. Get the package initialized and validating locally before you write any model code:

sf data-code-extension script init -p tech_notes_enrichment
sf data-code-extension script scan -e ./payload/entrypoint.py
sf data-code-extension script run -e ./payload/entrypoint.py -o fsl-sandbox

For local runs, log in to a sandbox with the external client app credentials (My Domain URL and consumer key) and run the script there.

Script pattern: one model call per unique, cleaned note

Field service technicians write visit notes in a rich-text field. The DLO holds HTML from the mobile editor, customer emails and phone numbers pasted into notes, plenty of entries like "done" and "n/a", and the same boilerplate copied across many visits. For each note we want a failure category from a fixed list and a one-sentence summary.

Anything a regex or a filter can handle runs before the model. That reduces the number of calls and keeps raw contact details out of the prompt. Salesforce manages the gateway, but I still mask PII. The model doesn't need a customer's phone number to classify a seized bearing, and masking is also what lets the duplicate check match notes that differ only in contact details.

from pyspark import StorageLevel
from pyspark.sql.functions import (
    col, lit, lower, length, regexp_extract, regexp_replace,
    sha2, substring, trim, when,
)
from datacustomcode.client import Client, llm_gateway_generate_text_col
# copy the WriteMode import line from the entrypoint.py that `script init` generated

MODEL_ID = "sfdc_ai__DefaultGPT4Omni"  # use a model configured in your org
CATEGORIES = ["ELECTRICAL", "MECHANICAL", "FIRMWARE", "INSTALLATION", "MISUSE", "UNKNOWN"]

PROMPT = (
    "Classify this field service visit note.\n"
    "Note: {note}\n"
    "Answer in exactly two lines.\n"
    "CATEGORY=<one of ELECTRICAL, MECHANICAL, FIRMWARE, INSTALLATION, MISUSE, UNKNOWN>\n"
    "SUMMARY=<one sentence, at most 30 words, no names or contact details>"
)

client = Client()


def clean(df):
    text = col("note_body__c")
    text = regexp_replace(text, r"<[^>]+>", " ")          # HTML tags
    text = regexp_replace(text, r"&[a-z]+;", " ")          # HTML entities
    text = regexp_replace(text, r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", "[EMAIL]")
    text = regexp_replace(text, r"\+?[0-9][0-9 ().-]{7,}[0-9]", "[PHONE]")
    text = trim(regexp_replace(text, r"\s+", " "))
    return (
        df.withColumn("clean_note__c", substring(text, 1, 4000))
        .filter(length(col("clean_note__c")) >= 40)    # drops "done", "n/a", nulls
        .withColumn("note_hash__c", sha2(lower(col("clean_note__c")), 256))
    )


def classify(unique_df):
    gw = col("gw")
    raw_cat = regexp_extract(gw["response"], r"CATEGORY=([A-Z_]+)", 1)
    return (
        unique_df.repartition(16)
        .withColumn("gw", llm_gateway_generate_text_col(
            PROMPT, {"note": col("clean_note__c")}, model_id=MODEL_ID))
        # success test until the real status value is confirmed in a sample run
        .withColumn("gw_ok", gw["response"].isNotNull() & gw["error_code"].isNull())
        .withColumn("category__c",
                    when(raw_cat.isin(CATEGORIES), raw_cat).otherwise(lit("UNKNOWN")))
        .withColumn("summary__c", regexp_extract(gw["response"], r"SUMMARY=(.+)", 1))
        .withColumn("gw_status__c", gw["status"].cast("string"))
        .withColumn("gw_error__c", gw["error_message"])
        .drop("gw", "clean_note__c")
    )


cleaned = clean(client.read_dlo("Tech_Visit_Note__dll"))

# skip visits that already have an insight or a pending retry
seen = (
    client.read_dlo("Tech_Note_Insights__dll").select("visit_id__c")
    .union(client.read_dlo("Tech_Note_Retry__dll").select("visit_id__c"))
    .distinct()
)
cleaned = cleaned.join(seen, on="visit_id__c", how="left_anti")

unique_notes = cleaned.select("note_hash__c", "clean_note__c").dropDuplicates(["note_hash__c"])

classified = classify(unique_notes).persist(StorageLevel.MEMORY_AND_DISK)
classified.count()  # materialize once so the two writes below reuse these results

result = cleaned.join(classified, on="note_hash__c", how="left")

good = result.filter(col("gw_ok")).select(
    "visit_id__c", "note_hash__c", "category__c", "summary__c", "gw_status__c")
bad = result.filter(~col("gw_ok")).withColumn("attempt__c", lit(1)).select(
    "visit_id__c", "note_hash__c", "clean_note__c", "attempt__c", "gw_status__c", "gw_error__c")

client.write_to_dlo("Tech_Note_Insights__dll", good, write_mode=WriteMode.APPEND)
client.write_to_dlo("Tech_Note_Retry__dll", bad, write_mode=WriteMode.APPEND)

On recurring runs, only visits with no insight and no pending retry reach dedupe and the model, so a nightly job pays only for new notes, and the retry job owns the failed rows.

The hash is computed on lowercased, masked text, so two notes that differ only in a customer email become one call. For a failure category that is what you want. If the masked detail matters to the task, for example extracting which contact approved the work, dedupe on the raw text or skip dedupe.

The prompt restricts the category to a closed list, and isin checks the answer afterwards. Models occasionally answer off-list, and an unvalidated label can end up in a segment filter, so off-list answers are stored as UNKNOWN.

Only unique_notes reaches the model, and the join copies each result back to every source row. Forty visits with the same pasted boilerplate cost one call. Spark is lazy and result feeds two writes, so without persistence each write recomputes the plan and calls the model twice for every note.

If you need a single generation per run, use client.llm_gateway_generate_text(prompt, model_id). It takes one prompt and doesn't iterate the DataFrame. Generating a short description of the category taxonomy once from a lookup table is a good fit.

Reading the result struct and retrying only what failed

llm_gateway_generate_text_col() returns a struct with four fields: status, response, error_code and error_message. You read them with bracket notation, as in col("gw")["response"]. When the model returns an error for a row, the error goes into that row's struct and the job carries on. That makes failures easy to lose. If you select only the response, failed rows become nulls that look the same as notes the model had nothing to say about.

I haven't yet confirmed what string status holds on success. Until you have, gw_ok treats a row as successful when response is present and error_code is null. Run a sample, look at the status values that come back, and tighten the check to match.

Successful rows go to the insights DLO. Failed rows go to a separate retry DLO with the masked text, the hash and the error. The retry job reads that DLO, drops any hash that a later pass has already fixed, and stops after a fixed number of attempts:

from pyspark import StorageLevel
from pyspark.sql.functions import col, lit, max as spark_max
from datacustomcode.client import Client, llm_gateway_generate_text_col
# copy the WriteMode import line from the entrypoint.py that `script init` generated
# PROMPT, CATEGORIES, MODEL_ID and classify(): same as the main script

MAX_ATTEMPTS = 3
client = Client()

done = client.read_dlo("Tech_Note_Insights__dll").select("note_hash__c").distinct()

pending = (
    client.read_dlo("Tech_Note_Retry__dll")
    .join(done, on="note_hash__c", how="left_anti")         # fixed by an earlier pass
    .groupBy("visit_id__c", "note_hash__c", "clean_note__c")
    .agg(spark_max("attempt__c").alias("attempt__c"))        # retry DLO is append-only
    .filter(col("attempt__c") < MAX_ATTEMPTS)
)

unique_pending = pending.select("note_hash__c", "clean_note__c").dropDuplicates(["note_hash__c"])
classified = classify(unique_pending).persist(StorageLevel.MEMORY_AND_DISK)
classified.count()

result = pending.join(classified, on="note_hash__c", how="left")

good = result.filter(col("gw_ok")).select(
    "visit_id__c", "note_hash__c", "category__c", "summary__c", "gw_status__c")
still_bad = result.filter(~col("gw_ok")).withColumn("attempt__c", col("attempt__c") + 1).select(
    "visit_id__c", "note_hash__c", "clean_note__c", "attempt__c", "gw_status__c", "gw_error__c")

client.write_to_dlo("Tech_Note_Insights__dll", good, write_mode=WriteMode.APPEND)
client.write_to_dlo("Tech_Note_Retry__dll", still_bad, write_mode=WriteMode.APPEND)

Because of the anti-join, reprocessing old retry rows does no harm. The attempt cap keeps one malformed note from consuming calls every night. Schedule the retry well after the main run so a rate-limit window has time to reset. Rows that reach the cap stay in the retry DLO with no insight attached, so put a report on that DLO and someone will look at them.

Function pattern: the model finds procedure boundaries, Python shapes the chunks

The scenario here is a search index over equipment maintenance manuals. Fixed-size chunking can cut a lockout procedure off partway through step 4, and retrieval then returns half a safety procedure. With a chunking function, the model marks where each procedure begins and ends, and ordinary code does everything else.

The entry point is function(request, runtime) in payload/entrypoint.py. Model calls go through the runtime object the platform passes in: you build a request with GenerateTextRequestBuilder and send it with runtime.llm_gateway.generate_text(...). Running sf data-code-extension function init gives you a package containing a reference at example/chunking_with_llm/entrypoint.py. In the code below, the platform-specific calls sit in four small stubs; copy their bodies from that reference file. The builder methods, the attribute that holds the response text and the shape of request.input elements should come from the reference, so I have left them out instead of guessing.

# payload/entrypoint.py  (search index chunking function)
import logging

logger = logging.getLogger(__name__)

MODEL_ID = "sfdc_ai__DefaultGPT4Omni"
DELIM = "---CHUNK---"
MIN_CHARS = 200    # fold smaller fragments into the previous chunk
MAX_CHARS = 2500   # split anything larger at a line break

PROMPT = (
    "You are preparing an equipment maintenance manual for search.\n"
    "Insert the line " + DELIM + " between procedures. Keep each procedure's\n"
    "warnings, tools list and numbered steps together. Do not rewrite,\n"
    "summarise or drop any text.\n\n"
    "Section:\n{section}"
)


# ---- Platform stubs: copy exact calls from example/chunking_with_llm/entrypoint.py ----
def element_texts(request):
    """Return the text of each document element in request.input, in order."""
    raise NotImplementedError("copy element access from the reference example")


def call_model(runtime, prompt):
    """Build the request with GenerateTextRequestBuilder using MODEL_ID, call
    runtime.llm_gateway.generate_text(...), return (ok, text)."""
    raise NotImplementedError("copy builder and response handling from the reference example")


def make_chunk(text, seq_no):
    """Return a chunk with text, seq_no and chunk_type as the reference example builds it."""
    raise NotImplementedError("copy chunk construction from the reference example")


def build_response(chunks):
    """Return SearchIndexChunkingV1Response(output=chunks), imported as the reference does."""
    raise NotImplementedError("copy the response import from the reference example")
# ---------------------------------------------------------------------------------------


def shape(raw):
    pieces = [p.strip() for p in raw.split(DELIM) if p.strip()]
    merged = []
    for piece in pieces:
        if merged and len(piece) < MIN_CHARS:
            merged[-1] = merged[-1] + "\n" + piece
        else:
            merged.append(piece)
    capped = []
    for piece in merged:
        while len(piece) > MAX_CHARS:
            cut = piece.rfind("\n", 0, MAX_CHARS)
            if cut < MIN_CHARS:
                cut = MAX_CHARS
            capped.append(piece[:cut].strip())
            piece = piece[cut:].strip()
        if piece:
            capped.append(piece)
    return capped


def function(request, runtime):
    chunks = []
    for idx, text in enumerate(element_texts(request)):
        if not text or len(text.strip()) < 20:
            continue
        ok, raw = call_model(runtime, PROMPT.format(section=text))
        if not ok:
            # log position and size only, never the manual text
            logger.error("chunking call failed: element=%d chars=%d", idx, len(text))
            raise RuntimeError(f"LLM chunking failed on element {idx}")
        for piece in shape(raw):
            # one counter for the whole document; match the reference for the start value
            chunks.append(make_chunk(piece, len(chunks)))
    return build_response(chunks)

The model only inserts ---CHUNK--- markers. Python drops empty pieces, merges fragments shorter than 200 characters into the chunk before them, and splits anything longer than 2,500 characters at a line break. seq_no comes from a single counter across all elements, so it doesn't restart at each section. The merge rule has a cost: a short procedure that really is complete on its own, such as a two-line torque spec, gets attached to the procedure before it. For manuals I accept that. If every short clause in your documents must stand alone, lower MIN_CHARS.

When a call fails, the function logs the element index and length and then raises. The docs ask for failed gateway responses to be handled explicitly with controlled errors, and they say to keep sensitive content out of prompts and logs, which is why the log line contains no text. You could fall back to splitting on numbered headings instead. I would still raise, because a document indexed with a different chunking that nobody noticed is harder to track down later than a build that failed with an error. Test locally with a payload built from a real document, using the input shape the reference example reads:

sf data-code-extension function run -e payload/entrypoint.py -t tests/test.json

Sizing the run before the first full pass

Every unique note and every document element is a model call, and each one counts against the Salesforce Large Language Model Limits. Batched calls and better scaling are on the roadmap but not available yet, so work out the numbers before the first full run:

cleaned = clean(client.read_dlo("Tech_Visit_Note__dll"))

# same incremental filter as the main script
seen = (
    client.read_dlo("Tech_Note_Insights__dll").select("visit_id__c")
    .union(client.read_dlo("Tech_Note_Retry__dll").select("visit_id__c"))
    .distinct()
)
cleaned = cleaned.join(seen, on="visit_id__c", how="left_anti")

unique_notes = cleaned.select("note_hash__c", "clean_note__c").dropDuplicates(["note_hash__c"])
print(f"rows after cleaning: {cleaned.count()}, unique notes: {unique_notes.count()}")

trial = classify(unique_notes.sample(fraction=0.01, seed=42).limit(200))
trial.groupBy("gw_status__c", "category__c").count().show()

Run this on a sandbox first. Comparing the two counts shows how many calls dedupe saved, and where notes share copied boilerplate the saving can be large. The trial grouping shows the real status values, how often the model answers outside the list, and whether the category spread looks believable. Read twenty of the summaries yourself before you trust the rest.

Throughput depends on partitions. A heavy filter can leave a large DLO read in a handful of partitions, and the job then spends most of its window on one or two executors, sending gateway requests almost one at a time. That is why classify calls repartition(16) before the UDF. More partitions only help when there are CPUs to run them. You set compute size at deploy time with --cpu-size (CPU_L, CPU_XL, CPU_2XL or CPU_4XL; the default is CPU_2XL), so move up to CPU_4XL when you add partitions:

sf data-code-extension script deploy -p ./payload --name tech_notes_enrichment --cpu-size CPU_4XL --package-version 1 -o myorg

CPU_L is the smallest size, so keep it for small trial runs. Increase partitions and compute together and watch the error rate. Once you pass the rate limit, more parallelism only produces more rows in the retry DLO.

What to watch for

  • Anything that makes otherwise identical notes differ defeats dedupe. Timestamps, visit numbers and signatures in the note body all count, so mask or strip them in clean() if they don't affect the answer.
  • The phone regex also catches long serial and part numbers. If technicians write serials in the notes, give those their own pattern and run it before the phone mask.
  • substring(text, 1, 4000) cuts off long notes, so the summary only covers the opening part. Set the cap after checking your note length distribution.
  • The exact success value of status is not yet confirmed. Until it is, use the response/error_code check.
  • Each write recomputes any part of the plan that isn't persisted, and that includes the model calls. Persist the classified DataFrame and materialize it once.
  • MODEL_ID has to match a model configured in your org. Pick it on purpose instead of keeping whatever default appears in examples.

Originally reported by developer.salesforce.com

Frequently asked questions

How do I call a generative model from a Data 360 code extension script?

Use the built-in llm_gateway_generate_text_col UDF inside withColumn. You pass a prompt template with {placeholders}, a dict that maps each placeholder to a DataFrame column, and a model_id such as sfdc_ai__DefaultGPT4Omni. Each row comes back as a struct with status, response, error_code and error_message.

How do I retry failed LLM calls in a Data 360 code extension script?

A failure on one row is recorded in that row's struct and the job keeps going, so nothing retries automatically. Write the status and error fields out, send failed rows to a retry DLO, and run a second job that anti-joins against finished results and caps the number of attempts.

Why is my Data 360 LLM enrichment script so slow?

If the DataFrame sits in only a few partitions, gateway requests run close to one at a time on a few executors. Repartition before the call and deploy with a larger --cpu-size such as CPU_4XL (the default is CPU_2XL) so there are CPUs to run the partitions, and keep an eye on the Large Language Model Limits.

Is every row a separate LLM call in a Data 360 code extension?

Yes. Every row or document you send is its own model call, and batched calls are on the roadmap but not available yet. Deduplicate before the call and run a small sample before the full dataset.

Can a Data 360 code extension function call an LLM for anything besides chunking?

Not today. Functions plug into platform features, and search index chunking is the only one available. For enrichment that writes summaries or labels to records, use a script.

Watch the video explainer

Newsletter

One email every Tuesday

New guides, tool updates, and the release-note changes that break things.

No spam. Unsubscribe in one click.

Comments

Loading comments...

Leave a Comment