Send work that can wait to the generative AI hub as one batch job, record live calls with inference observability, and know what your own code still owns.
Most AI features answer a person who is waiting. Some work has no one waiting: re-coding three years of maintenance history, classifying last month's supplier invoices, summarizing every open service order before Monday. Sending those one call at a time, as fast as possible, is the expensive way to do it.
As of November 2026, SAP's generative AI hub (part of SAP AI Core) offers two features for this side of production:
Batch consumption. You put many model requests into one file, hand it over as a single job, and collect the answers later, within hours. SAP describes it as cheaper than calling the model one request at a time, and it handles retries and rate limits for you.
Inference observability. When you ask for it, SAP AI Core keeps a record of each live model call: model, tokens, latency, and, if you choose, the full request and response. You can attach labels and user feedback to each record and read them back later.
Batch is about cost and volume for work that can wait. Observability is about knowing what your live AI did. Neither replaces your own evaluation or monitoring. Both change what you have to build yourself.
Take Calder Pumpworks, the course's fictional pump maker. At its Rockford plant, about one closed maintenance notification in six has no usable damage code. Reliability engineers can't spot repeat failures in a history that says "other". Coding 240 old notifications is a job nobody is waiting for. It can run overnight.
Cost. A job that can wait shouldn't pay for speed it doesn't use. SAP says batch costs less than synchronous calls. Microsoft, the provider behind it, prices its own global batch at half its standard rate. SAP's own documentation gives no batch discount; it points to SAP Note 3437766 for token conversion rates. Check your metering and ask before you build a business case on it.
Reliability. A script that fires 10,000 calls hits rate limits, needs retry logic and can stall live users who share the same quota. A batch job takes the whole file and works through it in the background.
Evidence. When a planner says "the AI coded this wrong", someone must find that call: which model, which prompt version, what it was shown. With observability switched on, the record exists. Without it, you only have the user's word.
Risk. Recorded prompts can contain personal data. SAP stores them without masking, and says consent is the customer's responsibility. Turning on full recording is a data protection decision, not a technical toggle.
Both features sit in the generative AI hub of SAP AI Core, which needs the extended service plan. Status as read on SAP pages on 19 November 2026:
Feature
What SAP offers
Status and limits
Batch consumption
Upload a JSON Lines file to your object store, create a job, read the results file when it finishes
Generally available since 8 May 2026 per the What's New list of the service guide). Azure OpenAI models only, native model calls only (no orchestration), EU and US regions except prod-euonly and sovereign cloud (SAP documentation). SAP's JavaScript SDK still marks its batch package beta and its API experimental
Inference observability
Record calls to foundation models or orchestration; add labels and feedback; retrieve and delete records
Generally available since 27 April 2026 per the service guide. Full recording needs an S3 object store; metadata-only needs none (SAP documentation). Storage is charged by data volume (SAP Note 3720903)
SAP's Q2 2026 release highlights announced both (SAP News). In the SAP pages we read, both are used through APIs; reports and alerts on top of them are yours to build.
"Batch is just a cheaper switch on the same calls." Batch takes plain model calls only. Orchestration features such as grounding, masking and content filters don't run in a batch job.
"A completed batch job means every request worked." SAP says COMPLETED means the job as a whole was processed. Individual requests can still fail and must be checked one by one.
"Inference observability is a monitoring dashboard." SAP documents it as a store of call records with APIs. Alerts, service level objectives and quality reports are still yours to build.
"Recording everything is the safe choice." Full recording stores prompts and answers unmasked. Record only what you have a reason and a right to keep, and delete on a schedule.
"Deleting a record removes the data." SAP's delete removes metadata and labels. The request, response and feedback in your object store stay until you remove them.
Pick one answer for each question. The explanation appears after you choose.
1Calder wants to fill missing damage codes on 240 old maintenance notifications. Nobody is waiting for the result. Which approach fits best?
Answer: D. The work can wait and is many requests of the same kind, which is what batch consumption is for. Observability records live calls; it doesn't make bulk work cheaper. Grounding runs in orchestration, which batch doesn't support.
2A project lead says: "The batch job finished with status COMPLETED, so we can load all the codes." What should you ask first?
Answer: D. SAP says COMPLETED means the job as a whole was processed, while single requests can still fail. And a successful call can still give a wrong code, so a person checks a sample before anything is written back.
3Your team plans to batch requests that use grounding on SAP documents and data masking. What is the problem?
Answer: A. SAP's documentation says batch consumption supports native model calls only; orchestration requests aren't supported. Grounding and masking are orchestration modules, so the design must change or stay online.
4Which statement about inference observability is accurate as of November 2026?
Answer: B. Calls are recorded only when the request headers ask for it. SAP stores payloads without masking, and deleting record data removes metadata and labels while the payloads in your object store stay.
5Legal asks whether recording the order assistant's prompts in full is safe. What is the right first answer?
Answer: C. SAP stores requests, responses and feedback without masking and puts consent for personal data on the customer. Metadata mode keeps model, tokens and latency without the content.
6Why should every observed call carry labels such as the use case and prompt version?
Answer: A. Labels exist for filtering and analysis. When a prompt changes, records labeled by version let you compare speed, errors and feedback before and after.
The express lane is an online call. One request, one answer, now. You pay for speed, you share rate limits with everyone else, and your code handles every failure.
The freight lane is a batch job. You load a whole file of requests, hand it over, and come back later. The service queues it, retries what fails for transient reasons, and leaves a results file in your object store. You give up speed and orchestration; you gain throughput and a lower price.
The flight recorder is inference observability. It sits on the express lane and, when you switch it on for a call, keeps what happened: model, tokens, latency and, in full mode, the request and answer. You can later attach labels and feedback.
Everything else follows from one rule each. In the freight lane, the custom_id is the only thread between a request and its answer: lose it and you have answers you can't use. With the flight recorder, you decide per call what is kept: the header is the switch, and anything you record unmasked is now data you must govern.
This topic builds on Observability for AI systems, where you recorded traces with OpenTelemetry, and Token economics, where you priced calls. Here you see what SAP now does for you, and what still sits in your code.
sequenceDiagram
participant A as Your script
participant S as Object store (S3, Blob, GCS...)
participant B as Batch service (SAP AI Core)
participant P as Azure OpenAI
A->>S: upload input.jsonl (one request per line)
A->>B: POST /llm-batch-service/v1/batches
B-->>A: id, status PENDING
B->>S: read input file
B->>P: submit requests, retry transient failures
loop every 30 to 60 minutes
A->>B: GET .../batches/{id}/status
end
B->>S: write {id}/output.jsonl and error.jsonl
A->>S: download, match lines on custom_id
As of 19 November 2026, SAP's documentation describes it like this:
The input file. JSON Lines, one request per line. Each line has custom_id, method (POST only), url (/v1/chat/completions only) and body, which holds a chat completion request with model and messages. Every line in one file must use the same model (SAP: prepare the input file).
The object store. The file lives in your own storage. SAP AI Core reaches it through an object store secret, written as ai://<secret-name>/<path>. Batch supports Amazon S3, Azure Blob Storage, Google Cloud Storage, Alibaba Cloud OSS and SAP HANA Cloud data lake.
The job.POST $AI_API/llm-batch-service/v1/batches with type: "llm-native", input.uri, output.uri (ending in /) and spec with provider: "azure-openai" and the same model as the file (SAP: create a batch job). The AI-Resource-Group header picks the resource group.
Status.GET .../batches/{id}/status returns current_status, target_status, updated_at and message. SAP lists PENDING, PREPARING_INPUT, INPUT_PREPARED, IN_PROGRESS, PREPARING_OUTPUT, COMPLETED, FAILED, CANCELLING and CANCELLED. SAP's JavaScript SDK docs say a job can run up to 24 hours and suggest polling every 30 to 60 minutes for large batches.
Results. The service writes output.jsonl into a folder named after the batch ID, and error.jsonl beside it when requests failed (SAP: retrieve results). Each output line carries the custom_id and a response with status_code and body. The order isn't guaranteed.
SAP's batch tutorial lists the limits: 200 MB per input file, 100,000 requests per file, and 500 input files without an expiry set or 10,000 with one (tutorial source). These match Microsoft's limits for Azure OpenAI batch (Microsoft Learn), which SAP's page names as the detailed input specification.
flowchart LR
APP[Your app] -->|completion call + headers| ORC[Orchestration or model deployment]
ORC -->|answer + ai-inference-id| APP
ORC -->|metadata| MD[(Record store in SAP AI Core)]
ORC -->|request, response, feedback in full mode| S3[(Your S3 bucket)]
APP -->|labels, feedback| API[/observability/inferences API/]
API --> MD
API --> S3
full (request, response and metadata) or metadata (metadata only)
ai-object-store-secret-name
The S3 object store secret; needed for full only
ai-inference-observability-labels
Optional, comma-separated key=value pairs: at most 16, keys start with ext.ai.sap.com, keys and values up to 64 characters, ASCII letters, digits, -, . and / only
The response carries an ai-inference-id header. With it you use the observability API under your AI API URL:
Call
What it does
GET /observability/inferences/{id}
One record: source, modelName, modelVersion, responseHttpCode, inputTokens, outputTokens, latency, createdAt, and in full mode request and response
GET /observability/inferences?labelSelector=ext.ai.sap.com/prompt=v4
Records by label key or key and value
POST /observability/inferences/{id}/labels
Adds new labels; a key that already exists is rejected
POST /observability/inferences/{id}/feedback
Adds feedback (any JSON object, such as {"stars": 5}); full mode only; never overwrites
POST /observability/inferencesDeleteRequests
Deletes metadata and labels by time range and labels; with no criteria it deletes all record data in the resource group (SAP: delete)
The paths and bodies above are from SAP's documentation and SAP's sample request collection for the developer tutorial. SAP says the API is documented on the SAP Business Accelerator Hub; we didn't read that reference in this run.
#Build it yourself: back-code the maintenance history overnight
You will build batch_lab.py, a small tool that does both halves of this topic on your own computer. First it writes a batch input file for 240 Calder notifications that have no damage code, checks it against SAP's rules, runs it through a local stand-in for the batch service, and matches the answers back. Then it records a day of live calls the way inference observability does and reports on them.
flowchart LR
P[prepare<br/>input.jsonl] --> C[check<br/>SAP's rules]
C --> S[submit<br/>local batch service]
S --> O[output.jsonl<br/>error.jsonl]
O --> L[collect<br/>match on custom_id]
L --> R[codes_proposed.csv<br/>retry.jsonl]
OB[observe<br/>records, labels, feedback] --> REP[report per prompt version]
In VS Code's Explorer, right-click the unit10 folder, choose New File and name it batch_lab.py.
Paste this code and save (Ctrl+S on Windows, Cmd+S on macOS):
"""Batch and observability lab for Calder Pumpworks (fictional), built-in modules only.
Back-codes closed maintenance notifications that have no damage code, the way the
generative AI hub's batch consumption works: one JSONL file in, one job, results
matched back by custom_id. Then records an online day the way inference
observability does: records, labels, feedback, storage estimate.
Everything runs locally on synthetic data (seed 42). No account, no charge.
python unit10/batch_lab.py prepare write the batch input file
python unit10/batch_lab.py prepare --broken write a file with three mistakes in it
python unit10/batch_lab.py check FILE validate a batch input file
python unit10/batch_lab.py submit run the local stand-in batch service
python unit10/batch_lab.py collect match results, score, write retries
python unit10/batch_lab.py collect --batch ID read a real job's downloaded output
python unit10/batch_lab.py observe record an online day and report on it
python unit10/batch_lab.py observe --mode metadata
"""
import argparse
import csv
import json
import random
import re
import statistics
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent / "batch"
SEED = 42
MODEL = "gpt-4.1"
CODES = ["LEAK", "OVERHEAT", "ELEC", "VIBR", "WORN", "BLOCK", "OTHER"]
# SAP's documented batch limits (help portal / developer tutorial, read 2026-11-19)
MAX_LINES = 100_000
MAX_BYTES = 200 * 1024 * 1024
# Course prices, not SAP's or any vendor's: USD per million tokens
PRICE_IN, PRICE_OUT = 2.00, 8.00
BATCH_SHARE = 0.50 # course assumption: batch costs half; check your own metering
# SAP's worked example for inference observability storage (SAP AI Core service guide)
MB_PER_RECORD_DAY = 0.002048
DVU_PER_MB_DAY = 0.00089
EQUIPMENT = {
"10000101": "Test bench TB-1", "10000103": "Overhead crane 10 t",
"10000104": "Air compressor C-2", "10000105": "Assembly conveyor CV-1",
"10000106": "Torque station TS-2", "10000107": "Forklift FL-3",
"10000108": "Paint booth exhaust fan PB-1",
}
PHRASES = {
"LEAK": ["oil dripping under {p}", "water leaking at {p} flange", "leak on pressure side near {p}",
"puddle under {p}, seal weeping"],
"OVERHEAT": ["{p} running hot", "{p} too hot to touch, smell of burning", "temp alarm on {p}",
"overheating after 20 min at {p}"],
"ELEC": ["{p} trips breaker", "no power to {p}", "{p} display flickers, loose wire?",
"contactor chattering at {p}"],
"VIBR": ["{p} shaking at speed", "heavy vibration on {p}", "{p} noisy and vibrating, brg?",
"rattle from {p} when loaded"],
"WORN": ["{p} worn, needs replacing", "belt on {p} frayed", "{p} pads worn thin",
"{p} slack, worn out"],
"BLOCK": ["{p} jammed", "{p} stuck, will not move", "something blocking {p}", "{p} clogged"],
"OTHER": ["{p} not right, pls check", "operator reports issue with {p}", "check {p}",
"{p} odd since monday"],
}
PARTS = ["motor", "bearing", "seal", "valve", "belt", "brake", "sensor"]
SYSTEM = ("You code SAP maintenance notifications for Calder Pumpworks. Choose one damage code from "
+ ", ".join(CODES) + ". Use OTHER when the text names no symptom. Answer only JSON: "
'{"damage": "<code>", "reason": "<five words or fewer>"}')
def say(msg=""):
print(msg)
def make_notifications(count):
rng = random.Random(SEED)
rows = []
for i in range(count):
code = rng.choices(CODES, weights=[18, 12, 16, 16, 14, 10, 14])[0]
text = rng.choice(PHRASES[code]).format(p=rng.choice(PARTS))
rows.append({"MaintenanceNotification": str(10007001 + i),
"TechnicalObject": rng.choice(list(EQUIPMENT)),
"NotificationText": text, "_true": code})
return rows
def batch_line(n):
user = f"Equipment {n['TechnicalObject']} ({EQUIPMENT[n['TechnicalObject']]}): {n['NotificationText']}"
return {"custom_id": n["MaintenanceNotification"], "method": "POST", "url": "/v1/chat/completions",
"body": {"model": MODEL, "max_tokens": 40, "response_format": {"type": "json_object"},
"messages": [{"role": "system", "content": SYSTEM},
{"role": "user", "content": user}]}}
def tokens(text):
return max(1, round(len(text) / 4)) # rough rule: about 4 characters per token
def check_file(path):
"""Return a list of problems; empty means the file passes."""
problems, seen, models = [], set(), set()
raw = path.read_bytes()
if len(raw) > MAX_BYTES:
problems.append(f"file is {len(raw)} bytes; the limit is 200 MB")
if raw and not raw.endswith(b"\n"):
problems.append("the file must end with a newline after the last line")
lines = raw.decode("utf-8").splitlines()
if len(lines) > MAX_LINES:
problems.append(f"too_many_tasks: {len(lines)} requests; the limit is {MAX_LINES}")
for no, text in enumerate(lines, start=1):
try:
item = json.loads(text)
except json.JSONDecodeError:
problems.append(f"line {no}: invalid_json_line")
continue
cid = item.get("custom_id")
if not cid:
problems.append(f"line {no}: custom_id missing")
elif cid in seen:
problems.append(f"line {no}: custom_id {cid} used twice")
seen.add(cid)
if item.get("method") != "POST":
problems.append(f"line {no}: method must be POST")
if item.get("url") != "/v1/chat/completions":
problems.append(f"line {no}: url must be /v1/chat/completions")
body = item.get("body") or {}
if "messages" not in body:
problems.append(f"line {no}: body.messages missing")
models.add(body.get("model"))
if len(models) > 1:
problems.append(f"one model per job; this file mixes {sorted(m or 'none' for m in models)}")
return problems, len(lines)
def cmd_prepare(args):
HERE.mkdir(parents=True, exist_ok=True)
rows = make_notifications(args.count)
with open(HERE / "notifications.csv", "w", newline="", encoding="utf-8") as f:
w = csv.DictWriter(f, fieldnames=["MaintenanceNotification", "TechnicalObject", "NotificationText"])
w.writeheader()
for r in rows:
w.writerow({k: r[k] for k in w.fieldnames})
with open(HERE / "truth.csv", "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["MaintenanceNotification", "DamageCode"])
for r in rows:
w.writerow([r["MaintenanceNotification"], r["_true"]])
lines = [batch_line(r) for r in rows]
name = "input.jsonl"
if args.broken:
name = "input_broken.jsonl"
lines[7]["body"]["model"] = "gpt-4.1-mini" # a second model in one job
lines[12]["custom_id"] = lines[11]["custom_id"] # an ID used twice
text = "\n".join(json.dumps(x, separators=(",", ":")) for x in lines)
if not args.broken:
text += "\n" # broken file: no newline at the end
(HERE / name).write_bytes(text.encode("utf-8"))
problems, count = check_file(HERE / name)
size = (HERE / name).stat().st_size
est_in = sum(tokens(SYSTEM) + tokens(r["NotificationText"]) + 12 for r in rows)
say(f"Wrote {count} requests to unit10/batch/{name} ({size:,} bytes, model {MODEL})")
say(f"Estimated input tokens: {est_in:,}")
say("Check: " + ("OK" if not problems else f"{len(problems)} problem(s)"))
say("Next: python unit10/batch_lab.py " + (f"check unit10/batch/{name}" if args.broken else "submit"))
def cmd_check(args):
path = Path(args.file)
if not path.exists():
sys.exit(f"{path} not found. Run: python unit10/batch_lab.py prepare")
problems, count = check_file(path)
if problems:
say(f"{path.name}: {count} lines, {len(problems)} problem(s)")
for p in problems[:10]:
say(" " + p)
sys.exit(1)
say(f"{path.name}: {count} lines, OK")
def fake_model(text):
"""A deterministic stand-in for the model: keyword rules, deliberately imperfect."""
t = text.lower()
rules = [("LEAK", ["leak", "drip", "puddle", "weep"]), ("OVERHEAT", ["hot", "temp", "burn"]),
("ELEC", ["power", "trip", "wire", "contactor", "flicker"]),
("BLOCK", ["jam", "stuck", "block", "clog"]),
("VIBR", ["vibrat", "shak", "rattle"]), ("WORN", ["worn", "fray", "slack"])]
for code, words in rules:
if any(w in t for w in words):
return code
return "OTHER"
def cmd_submit(args):
src = HERE / "input.jsonl"
if not src.exists():
sys.exit("unit10/batch/input.jsonl not found. Run: python unit10/batch_lab.py prepare")
problems, count = check_file(src)
if problems:
say("FAILED the service refused the input file:")
for p in problems[:5]:
say(" " + p)
sys.exit(1)
batch_id = "local-0001"
for status, note in [("PENDING", "job accepted"), ("PREPARING_INPUT", "reading input from the object store"),
("IN_PROGRESS", f"{count} requests at the provider"),
("PREPARING_OUTPUT", "writing results"), ("COMPLETED", "done")]:
say(f"{status:<17} {note}")
rng = random.Random(SEED + 1)
out, err = [], []
for text in src.read_text(encoding="utf-8").splitlines():
item = json.loads(text)
cid, body = item["custom_id"], item["body"]
user = body["messages"][-1]["content"]
roll = rng.random()
if roll < 0.01: # the provider refused this one request
err.append({"custom_id": cid, "response": None,
"error": {"code": "content_filter", "message": "request blocked by provider filter"}})
continue
code = fake_model(user)
content = json.dumps({"damage": code, "reason": "keyword in text"})
if roll > 0.985: # valid HTTP 200, but not the JSON we asked for
content = f"The damage code is probably {code}."
usage = {"prompt_tokens": tokens(SYSTEM) + tokens(user) + 12, "completion_tokens": tokens(content)}
usage["total_tokens"] = usage["prompt_tokens"] + usage["completion_tokens"]
out.append({"custom_id": cid, "response": {"status_code": 200, "body": {
"object": "chat.completion", "model": MODEL,
"choices": [{"index": 0, "message": {"role": "assistant", "content": content},
"finish_reason": "stop"}], "usage": usage}}, "error": None})
rng.shuffle(out) # output order is not guaranteed; match on custom_id
folder = HERE / "output" / batch_id
folder.mkdir(parents=True, exist_ok=True)
for name, rows in [("output.jsonl", out), ("error.jsonl", err)]:
with open(folder / name, "w", encoding="utf-8", newline="\n") as f:
for r in rows:
f.write(json.dumps(r) + "\n")
say(f"Batch {batch_id}: {len(out)} lines in output.jsonl, {len(err)} in error.jsonl")
say("Next: python unit10/batch_lab.py collect")
def cmd_collect(args):
folder = HERE / "output" / args.batch
if not (folder / "output.jsonl").exists():
sys.exit("No batch output yet. Run: python unit10/batch_lab.py submit")
inputs = {json.loads(t)["custom_id"]: t for t in (HERE / "input.jsonl").read_text("utf-8").splitlines()}
truth = {r["MaintenanceNotification"]: r["DamageCode"]
for r in csv.DictReader(open(HERE / "truth.csv", encoding="utf-8"))}
proposed, retry, bad_json, failed, tok_in, tok_out = {}, [], [], [], 0, 0
for t in (folder / "output.jsonl").read_text("utf-8").splitlines():
line = json.loads(t)
cid, resp = line["custom_id"], line.get("response") or {}
if resp.get("status_code") != 200:
failed.append(cid)
continue
usage = resp["body"].get("usage", {})
tok_in += usage.get("prompt_tokens", 0)
tok_out += usage.get("completion_tokens", 0)
try:
code = json.loads(resp["body"]["choices"][0]["message"]["content"])["damage"]
if code not in CODES:
raise ValueError(code)
proposed[cid] = code
except (ValueError, KeyError, TypeError):
bad_json.append(cid)
for name in ("error.jsonl", "errors.jsonl"): # SAP's pages use both names
if (folder / name).exists():
for t in (folder / name).read_text("utf-8").splitlines():
failed.append(json.loads(t)["custom_id"])
missing = sorted(set(inputs) - set(proposed) - set(bad_json) - set(failed))
retry = sorted(set(bad_json + failed + missing))
right = sum(1 for cid, c in proposed.items() if truth[cid] == c)
wrong = [(cid, truth[cid], c) for cid, c in sorted(proposed.items()) if truth[cid] != c]
with open(HERE / "codes_proposed.csv", "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["MaintenanceNotification", "ProposedDamageCode", "Status"])
for cid in sorted(proposed):
w.writerow([cid, proposed[cid], "PROPOSED"])
with open(HERE / "retry.jsonl", "w", encoding="utf-8", newline="\n") as f:
for cid in retry:
f.write(inputs[cid] + "\n")
say(f"Requests sent: {len(inputs)}")
say(f"Usable answers: {len(proposed)}")
say(f"Not JSON / no code: {len(bad_json)}")
say(f"Failed requests: {len(failed)}")
say(f"Missing lines: {len(missing)}")
say(f"Agree with sample: {right} of {len(proposed)} ({right / max(1, len(proposed)):.1%})")
for cid, true, got in wrong[:3]:
say(f" {cid}: proposed {got}, sample says {true}")
online = tok_in / 1e6 * PRICE_IN + tok_out / 1e6 * PRICE_OUT
say(f"Tokens: {tok_in:,} in, {tok_out:,} out")
say(f"Course cost: online {online:.4f} USD, batch {online * BATCH_SHARE:.4f} USD")
say(f"Wrote unit10/batch/codes_proposed.csv and unit10/batch/retry.jsonl ({len(retry)} lines)")
def check_labels(labels):
if len(labels) > 16:
return "at most 16 labels per inference"
for k, v in labels.items():
if not k.startswith("ext.ai.sap.com/"):
return f"label key {k} must start with ext.ai.sap.com/"
if len(k) > 64 or len(v) > 64:
return f"label {k} is longer than 64 characters"
if not re.fullmatch(r"[A-Za-z0-9./-]+", k) or not re.fullmatch(r"[A-Za-z0-9./-]+", v):
return f"label {k}={v}: only ASCII letters, digits, '-', '.' and '/' are allowed"
return None
def cmd_observe(args):
HERE.mkdir(parents=True, exist_ok=True)
rng = random.Random(SEED + 2)
labels = {"ext.ai.sap.com/use-case": "notif-coding", "ext.ai.sap.com/prompt": "v3"}
problem = check_labels(labels)
if problem:
sys.exit(problem)
say("Header: ai-inference-observability-persistence-mode: " + args.mode)
say("Header: ai-inference-observability-labels: " + ",".join(f"{k}={v}" for k, v in labels.items()))
say("(calls 31 to 60 send ext.ai.sap.com/prompt=v4 after a prompt change at midday)")
records = []
for i, n in enumerate(make_notifications(300)[200:260]):
prompt_v = "v3" if i < 30 else "v4" # a prompt change at midday
user = f"{n['TechnicalObject']}: {n['NotificationText']}"
code = fake_model(user)
if prompt_v == "v4" and code in ("VIBR", "WORN"):
code = "OTHER" # v4 added examples but dropped two code descriptions
good = code == n["_true"]
latency = round(rng.lognormvariate(0.2, 0.35) + (0.6 if prompt_v == "v4" else 0), 3)
rec = {"id": f"inf-{i + 1:04d}", "source": "orchestration", "resourceGroup": "calder-dev",
"modelName": MODEL, "modelVersion": "latest", "responseHttpCode": 200 if rng.random() > 0.03 else 429,
"inputTokens": tokens(SYSTEM) + tokens(user) + (40 if prompt_v == "v4" else 0),
"outputTokens": 14, "latency": latency,
"labels": dict(labels, **{"ext.ai.sap.com/prompt": prompt_v})}
if args.mode == "full":
rec["request"] = {"messages": [{"role": "user", "content": user}]}
rec["response"] = {"damage": code}
rec["feedback"] = [{"content": {"stars": 5 if good else 2}}] if i % 3 == 0 else []
else:
rec["feedback"] = None # feedback needs persistence mode full
records.append(rec)
with open(HERE / "inference_records.jsonl", "w", encoding="utf-8", newline="\n") as f:
for r in records:
f.write(json.dumps(r) + "\n")
say(f"Recorded {len(records)} inferences in mode '{args.mode}' -> unit10/batch/inference_records.jsonl")
for version in ["v3", "v4"]:
rows = [r for r in records if r["labels"]["ext.ai.sap.com/prompt"] == version]
lat = sorted(r["latency"] for r in rows)
p95 = lat[int(0.95 * (len(lat) - 1))]
errors = sum(r["responseHttpCode"] != 200 for r in rows)
stars = [fb["content"]["stars"] for r in rows for fb in (r["feedback"] or [])]
star_text = f"{statistics.mean(stars):.1f} stars ({len(stars)} ratings)" if stars else "no feedback (mode metadata)"
say(f" prompt {version}: {len(rows)} calls, p50 {statistics.median(lat):.2f} s, p95 {p95:.2f} s, "
f"errors {errors}, input tokens {sum(r['inputTokens'] for r in rows):,}, {star_text}")
per_day = args.records_per_day
kept = per_day * args.retention_days
mb = kept * MB_PER_RECORD_DAY
cu = mb * DVU_PER_MB_DAY * 30
say(f"Storage estimate: {per_day:,} records/day kept {args.retention_days} days = {kept:,} records, "
f"{mb:,.1f} MB, about {cu:.2f} capacity units a month (SAP's example factors)")
def main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = p.add_subparsers(dest="cmd", required=True)
s = sub.add_parser("prepare")
s.add_argument("--count", type=int, default=240)
s.add_argument("--broken", action="store_true")
s.set_defaults(func=cmd_prepare)
s = sub.add_parser("check")
s.add_argument("file")
s.set_defaults(func=cmd_check)
sub.add_parser("submit").set_defaults(func=cmd_submit)
s = sub.add_parser("collect")
s.add_argument("--batch", default="local-0001", help="the batch ID whose output folder to read")
s.set_defaults(func=cmd_collect)
s = sub.add_parser("observe")
s.add_argument("--mode", choices=["full", "metadata"], default="full")
s.add_argument("--records-per-day", type=int, default=800)
s.add_argument("--retention-days", type=int, default=30)
s.set_defaults(func=cmd_observe)
args = p.parse_args()
args.func(args)
if __name__ == "__main__":
main()
Wrote 240 requests to unit10/batch/input.jsonl (133,319 bytes, model gpt-4.1)
Estimated input tokens: 19,545
Check: OK
Next: python unit10/batch_lab.py submit
Open unit10/batch/input.jsonl in VS Code. Each line is one request. Look at the first one: custom_id is the notification number 10007001, url is /v1/chat/completions, and body holds the model, a short system instruction and the notification text. That number is how you will find this notification's answer later.
Open unit10/batch/notifications.csv. These are the 240 made-up notifications: number, equipment, text. truth.csv holds the code a reliability engineer would give each one; it plays the role of a hand-checked sample.
input_broken.jsonl: 240 lines, 3 problem(s)
the file must end with a newline after the last line
line 13: custom_id 10007012 used twice
one model per job; this file mixes ['gpt-4.1', 'gpt-4.1-mini']
Each is a rule from SAP's pages: a newline after the last line, unique IDs to match answers, and one model per job. A duplicate ID is the worst of the three: two answers would claim the same notification.
PENDING job accepted
PREPARING_INPUT reading input from the object store
IN_PROGRESS 240 requests at the provider
PREPARING_OUTPUT writing results
COMPLETED done
Batch local-0001: 238 lines in output.jsonl, 2 in error.jsonl
Next: python unit10/batch_lab.py collect
Open unit10/batch/output/local-0001/output.jsonl. The first line is not 10007001: the stand-in shuffles the output, as the real service may. Each line has custom_id, response.status_code, response.body with the answer in choices[0].message.content, and usage with token counts.
The real service takes minutes to hours and you poll it; the stand-in prints its statuses at once. Everything else (the file shapes, the folder named after the batch ID, the separate error file) follows SAP's documentation.
Requests sent: 240
Usable answers: 234
Not JSON / no code: 4
Failed requests: 2
Missing lines: 0
Agree with sample: 225 of 234 (96.2%)
10007020: proposed OTHER, sample says OVERHEAT
10007053: proposed OTHER, sample says OVERHEAT
10007060: proposed OTHER, sample says OVERHEAT
Tokens: 21,916 in, 2,859 out
Course cost: online 0.0667 USD, batch 0.0334 USD
Wrote unit10/batch/codes_proposed.csv and unit10/batch/retry.jsonl (6 lines)
Read the result as a job owner would:
Four answers came back with HTTP 200 but no usable code. The model wrote a sentence instead of JSON. A 200 status means the call worked, not that the answer is usable.
Two requests failed and are listed in error.jsonl. The job still says COMPLETED.
Missing lines counts notifications with no line in either file. It is zero here; a real job deserves the check anyway.
Three wrong codes all say OTHER for "overheating": the keyword rule knows "hot" but not "overheating". A real model makes different mistakes, which is why a sample check comes before any write-back.
retry.jsonl holds the six requests to send again, in the same format. Check it with python unit10/batch_lab.py check unit10/batch/retry.jsonl before you submit it as a second job.
codes_proposed.csv marks every code PROPOSED. Nothing here writes to SAP. A planner confirms codes, as in the maintenance triage project.
Now the express lane. A planner uses the same coding prompt live, one notification at a time, and someone changes the prompt from v3 to v4 at midday.
Run:
python unit10/batch_lab.py observe
You should see:
Header: ai-inference-observability-persistence-mode: full
Header: ai-inference-observability-labels: ext.ai.sap.com/use-case=notif-coding,ext.ai.sap.com/prompt=v3
(calls 31 to 60 send ext.ai.sap.com/prompt=v4 after a prompt change at midday)
Recorded 60 inferences in mode 'full' -> unit10/batch/inference_records.jsonl
prompt v3: 30 calls, p50 1.36 s, p95 2.13 s, errors 2, input tokens 2,156, 5.0 stars (10 ratings)
prompt v4: 30 calls, p50 1.78 s, p95 2.66 s, errors 4, input tokens 3,364, 2.9 stars (10 ratings)
Storage estimate: 800 records/day kept 30 days = 24,000 records, 49.2 MB, about 1.31 capacity units a month (SAP's example factors)
Open unit10/batch/inference_records.jsonl. Each line has the fields SAP's record shows (id, source, modelName, modelVersion, responseHttpCode, inputTokens, outputTokens, latency), plus labels and feedback.
The v4 prompt is slower, uses more tokens and gets worse ratings. Without the prompt label you would see one blended day and no cause. With it, the comparison is one filter.
The two prompt lines now end with no feedback (mode metadata), and the records have no request or response. Speed, errors and tokens still compare by version. Quality, the stars, is gone: SAP accepts feedback only in full mode.
That is the trade-off in one line. Metadata mode is cheaper to govern and needs no object store. Full mode lets you collect feedback and read what the model was shown, and makes you responsible for unmasked content.
Try a larger estate: python unit10/batch_lab.py observe --records-per-day 2000 --retention-days 90. The last line shows 180,000 records, 368.6 MB and about 9.84 capacity units a month. Retention, not traffic alone, drives the bill.
To run the same file on SAP AI Core you need the extended plan, a region where batch is offered (EU or US, not prod-euonly or sovereign cloud), an object store secret, and a supported model. SAP lists models, token conversion rates and rate limits in SAP Note 3437766, which needs a login. As of 19 November 2026, SAP's JavaScript SDK types batch models as gpt-4.1, gpt-4.1-mini, gpt-4.1-nano, gpt-5, gpt-5.4 and gpt-5.4-mini, with provider azure-openai.
The Python SDK (sap-ai-sdk-gen, 7.4.1 as read on PyPI) has BatchService with create, list, get, get_status, cancel and delete. The JavaScript package @sap-ai-sdk/llm-batch (2.18.0) is marked beta in its README and its API experimental: it may change without notice.
"""SKETCH: submit unit10/batch/input.jsonl to the generative AI hub's batch service.
Needs an SAP AI Core instance with the extended plan, in a region where batch
consumption is offered, an object store secret registered in your resource group,
and the AICORE_* values in .env. It is not part of the free lab.
"""
import os
import sys
import time
from pathlib import Path
import httpx
from dotenv import load_dotenv
from gen_ai_hub.batch_service import BatchService
from gen_ai_hub.proxy import get_proxy_client
load_dotenv()
SECRET = os.environ.get("AICORE_OBJECT_STORE_SECRET") # the secret's name, e.g. calder-batch
if not SECRET:
sys.exit("Set AICORE_OBJECT_STORE_SECRET in .env to your object store secret's name")
FOLDER = "notif-coding"
proxy = get_proxy_client(proxy_version="gen-ai-hub")
base = proxy.ai_core_client.base_url.rstrip("/") # your AI API URL, ending in /v2
# 1. Upload the input file through AI Core's file API (it writes to your object store)
data = Path("unit10/batch/input.jsonl").read_bytes()
headers = dict(proxy.request_header)
headers["Content-Type"] = "*/*" # what SAP's JavaScript SDK sends for file uploads
r = httpx.put(f"{base}/lm/dataset/files/{SECRET}/{FOLDER}/input.jsonl",
params={"overwrite": "true"}, headers=headers, content=data, timeout=120)
r.raise_for_status()
# 2. Create the job: one model, one provider, input file in, output folder out
service = BatchService(proxy_client=proxy)
job = service.create(type="llm-native",
input_uri=f"ai://{SECRET}/{FOLDER}/input.jsonl",
output_uri=f"ai://{SECRET}/{FOLDER}/output/", # must end with /
provider="azure-openai", model="gpt-4.1")
print("Batch", job.id, job.status)
# 3. Poll slowly; treat any status you don't know as "still running"
TERMINAL = {"COMPLETED", "FAILED", "CANCELLED"}
while True:
st = service.get_status(job.id)
print(time.strftime("%H:%M"), st.current_status, st.message or "")
if st.current_status in TERMINAL:
break
time.sleep(600)
# 4. Download the results next to the local lab's files, then run collect on them
out = Path("unit10/batch/output") / job.id
out.mkdir(parents=True, exist_ok=True)
for name in ("output.jsonl", "error.jsonl", "errors.jsonl"): # SAP pages use both names
r = httpx.get(f"{base}/lm/dataset/files/{SECRET}/{FOLDER}/output/{job.id}/{name}",
headers=proxy.request_header, timeout=120)
if r.status_code == 200:
(out / name).write_bytes(r.content)
print("Saved", out / name)
Then python unit10/batch_lab.py collect --batch <the job ID> scores the real answers with the same code. We checked that the sketch's imports and calls match sap-ai-sdk-gen 7.4.1, but didn't run it against a tenant. The upload uses AI Core's file endpoint (/lm/dataset/files/{path}), which the AI API reference shipped in SAP's JavaScript SDK caps at 100 MB per file, below the batch service's 200 MB. For larger files, upload with your object store's own tools.
The switch is a set of request headers, so recording fits the HTTP calls you already make. Check whether your SDK version lets you pass extra headers; SAP's JavaScript orchestration client documents requestConfig.headers for this. A sketch with plain HTTP:
# SKETCH: one recorded orchestration call; needs an orchestration deployment URL and a token
headers = {
"Authorization": f"Bearer {token}",
"AI-Resource-Group": "default",
"ai-inference-observability-persistence-mode": "metadata", # or "full" with a secret
"ai-inference-observability-labels": "ext.ai.sap.com/use-case=notif-coding,ext.ai.sap.com/prompt=v3",
}
r = httpx.post(f"{deployment_url}/v2/completion", headers=headers, json=body, timeout=30)
inference_id = r.headers.get("ai-inference-id") # keep it with your own log line
Store the ai-inference-id next to your own trace ID from Observability for AI systems. Then a planner's complaint about notification 10007020 leads to your trace, and your trace leads to SAP's record.
Two details in SAP's documentation deserve a second look before you switch on full mode. SAP's sample record for a foundation model call stores the request as the upstream call, with its URL and headers. And the latency field shows 637.341 in one SAP example and 8.058... in the tutorial's, without a unit. Read a few of your own records before you build a report on either field.
Where it sits. Both features live in the SAP AI Core tenant on SAP BTP. The batch job reads and writes your object store; the notifications come from S/4HANA CP10 through a released API, and confirmed codes go back only through the planner's app. Observability sits on the online path between your app and the orchestration deployment.
flowchart LR
S4[S/4HANA CP10<br/>notifications API] --> EX[Extract job on BTP]
EX --> OS[(Object store)]
OS --> BJ[Batch service<br/>SAP AI Core]
BJ --> OS
OS --> RV[Review app<br/>planner confirms]
RV --> S4
APP[Planner app] --> ORC[Orchestration] --> AOAI[Azure OpenAI]
ORC -.records.-> OBS[(Inference records + S3)]
Non-functional requirements that decide the design
Requirement
Typical target
What breaks if missed
Turnaround
Results by 06:00 for a 22:00 start
Jobs can run up to 24 hours; a morning review starts on stale data
Data protection
No personal data in full recordings without consent
Unmasked prompts in S3 become a data protection finding
Retention
Records kept 30 to 90 days, then deleted with their payloads
Storage cost grows each month; deletion leaves S3 payloads behind
Volume
Under 100,000 requests and 200 MB per file
The file is refused (too_many_tasks); split by plant or month
Cost
Batch price per 1,000 notifications agreed in the business case
The saving is assumed, not measured
Integration and identity. The batch job runs under SAP AI Core's technical client and resource group, not a user. So the extract decides what data enters the file, and a person's identity enters only at the review step, where the planner confirms codes with their own SAP authorizations. Online calls should carry the user in your own trace; don't put user IDs in labels unless your data protection rules allow it.
Context: 240 uncoded notifications now, and a few thousand a year after go-live; a live coding assistant for planners.
Options: A, online calls in a throttled loop; B, generative AI hub batch consumption; C, a vendor's batch API outside SAP AI Core.
Decision: B for the back-log and the monthly re-run, with the file checked before upload and a sample review before write-back. Online calls record metadata by default, and full mode only on the test resource group.
Consequences: no orchestration in the batch path, so the extract strips names before the file is written; the poller tolerates unknown statuses; a deletion job removes S3 payloads after 30 days.
What a design review will ask
What enters the batch file, and who approved it for a model provider?
How do answers reach SAP, and who confirms them?
What happens to a job that fails at 03:00, and who is told?
Which calls are recorded in full, why, and when are the payloads deleted?
What does batch cost per 1,000 requests in our contract, and how was that measured?
Security and SAP authorizations. The object store secret gives SAP AI Core read and write access to a bucket. Use a bucket per use case, least-privilege keys, and rotation, which SAP leaves to the customer. Batch results are proposals; writing codes to S/4HANA uses the reviewer's authorizations through a released API, never the batch job's technical user.
Data protection. SAP stores observed requests and responses without masking or sanitizing, and says guarding against injection in stored feedback is the customer's job. Mask before the call, or record metadata only.
Evaluation. Check a random sample of every batch before write-back, and keep the sample's agreement rate per job. Use observability labels to compare prompt versions in production, then feed the findings into your evaluation gate.
Cost. Measure the real price of a batch job from your metering after the first run; don't rely on the vendor's discount. Price observability storage by records kept, using SAP Note 3720903.
Operations. Poll slowly. Alert on FAILED, on jobs past their deadline and on a rising share of unusable answers. Keep the batch ID with the business run that started it.
Clean core. Nothing here changes S/4HANA. The extract and the write-back use released APIs; the AI runs on BTP.
Save and run python unit10/batch_lab.py observe. You should see label key plant must start with ext.ai.sap.com/ and nothing is recorded.
Fix the key to "ext.ai.sap.com/plant": "CP11", save and run observe again. The header line now ends with ext.ai.sap.com/plant=CP11, and the report is the same as in Step 7.
Run python unit10/batch_lab.py check unit10/batch/retry.jsonl. You should see retry.jsonl: 6 lines, OK.
In unit10/batch-note.md, write three lines: how many notifications would go back for review, how many go into the retry job, and which label you would use to compare prompt versions next month.
Done when:observe prints the plant label in its header line, check passes on retry.jsonl, and batch-note.md is committed. The proposed codes in codes_proposed.csv are the input a reviewer would confirm in the maintenance triage project.
Pick one answer for each question. The explanation appears after you choose.
1A batch job for 240 notifications ends with status COMPLETED. What must your collect step still do?
Answer: C. SAP says COMPLETED means the job as a whole was processed; single requests can still fail and land in the error file. In the lab, four answers had HTTP 200 but no usable code, so the collect step checks every line and writes a retry file.
2Why does the lab use the notification number as the custom_id?
Answer: D. Output order isn't guaranteed, so each answer is matched by custom_id. Using the business key means the answer leads straight to the notification it belongs to.
3Your poller stops when the status is not PENDING or IN_PROGRESS. A job reports INPUT_PREPARED. What happens, and what should the rule be?
Answer: B. SAP's sources list different in-progress statuses, including INPUT_PREPARED and PREPARING_OUTPUT. A poller that ends only on the three final statuses tolerates statuses it hasn't seen.
4You must batch-classify supplier emails, and the design uses orchestration's data masking to remove names first. What do you change?
Answer: C. Batch consumption supports native model calls only, not orchestration requests. Masking must happen before the file is written, or the work stays on the online path.
5Which headers record an orchestration call with its prompt and answer, plus a prompt-version label?
Answer: D. Full mode stores request and response and needs the object store secret name; labels go in ai-inference-observability-labels. The ai-inference-id comes back on the response; you don't send it.
6After a prompt change, planners complain about codes but your records are in metadata mode. What can and can't you learn from them?
Answer: C. Metadata mode keeps model, tokens, latency and labels, so you can compare versions on speed and cost. Feedback needs full mode, and request and response aren't stored.
7A colleague wants to clean up records with a delete request that has no time range or labels. What happens?
Answer: A. SAP's documentation says a delete request without criteria deletes all inference record data for the resource group. Deletion covers metadata and labels; the request, response and feedback in S3 stay until you remove them.
8What drives the monthly storage cost of inference records most in the lab's estimate?
Answer: D. SAP's worked example charges by records stored per day. In Step 8, keeping 2,000 a day for 90 days gives 180,000 records and about 9.84 capacity units a month, against 1.31 for 800 a day kept 30 days.
SAP AI Core service guide, PDF edition of 16 November 2026 (SAP Help Portal)— read 2026-11-19; What's New: inference observability for the generative AI hub, general availability, 27 April 2026; batch consumption to reduce cost, general availability, 8 May 2026; metering example: an inference record uses 0.002048 MB a day, 25,000 records kept a month come to about 1.37 capacity units; conversion in SAP Note 3720903
Batch Consumption (SAP AI Core documentation, SAP-docs on GitHub)— read 2026-11-19; native LLM calls only, no orchestration; EU and US regions except prod-euonly and sovereign cloud; object stores Amazon S3, Azure Blob Storage, Google Cloud Storage, Alibaba Cloud OSS, SAP HANA Cloud data lake; reduced cost, automatic retries, no client-side rate limit handling; models in SAP Note 3437766. Linked pages read: input file (custom_id, method POST, url /v1/chat/completions, body with model and messages, one model per file), create (POST $AI_API/llm-batch-service/v1/batches, type llm-native, provider azure-openai, output URI ends with /), status (GET .../batches/{id}/status returns current_status, target_status, updated_at, message; statuses PENDING, PREPARING_INPUT, INPUT_PREPARED, IN_PROGRESS, PREPARING_OUTPUT, COMPLETED, FAILED, CANCELLING, CANCELLED), results (output.jsonl and error.jsonl under the batch ID; COMPLETED does not mean every request succeeded)
Batch Consumption tutorial (SAP Developers, source on GitHub sap-tutorials/Tutorials)— read 2026-11-19; extended plan needed for the generative AI hub; use for 50 or more non-urgent requests; output order not guaranteed, match on custom_id; limits 200 MB per file, 100,000 requests per file, 500 input files without expiry or 10,000 with expiry; errors invalid_json_line and too_many_tasks
Inference Observability (SAP AI Core documentation, SAP-docs on GitHub)— read 2026-11-19; stores payloads of calls to foundation models or orchestration only when request headers ask; full mode needs an S3 object store, metadata mode needs none; payloads stored without masking or sanitizing; storage cost in SAP Note 3720903
Record an Inference in Inference Observability (SAP AI Core documentation, SAP-docs on GitHub)— read 2026-11-19; extended plan; headers ai-inference-observability-persistence-mode (full or metadata), ai-object-store-secret-name, ai-inference-observability-labels (up to 16, prefix ext.ai.sap.com, 64 characters, ASCII letters, digits, '-', '.', '/'); feedback needs full mode; the response carries an inference ID. Linked pages read: add labels and feedback, retrieve by ID or labelSelector, delete requests (no criteria deletes all record data of the resource group; payloads in S3 stay)
SAP Business AI: Release Highlights Q2 2026 (SAP News, July 2026)— read 2026-11-19; Batch API for high-volume foundation model workloads submitted as a single input file; inference observability service for centralized logging and feedback; no GA labels on these items
Getting started with Azure OpenAI batch deployments (Microsoft Learn)— read 2026-11-19; the provider behind SAP's batch service; Azure's own global batch: 24-hour target turnaround at 50% less cost than global standard, separate enqueued-token quota, same file limits as SAP lists