# Batch and observability in the generative AI hub

> 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.

- Course: Orchestrate, Unit 10 · Production and LLMOps
- Page: https://erpfde.com/topics/batch-and-observability-in-the-generative-ai-hub/
- Updated: 2026-11-19
- Reading time: Foundational 8 min, Deep 40 min

Independent learning resource. Not affiliated with, sponsored by or endorsed by SAP SE. SAP and other SAP products mentioned are trademarks of SAP SE in Germany and other countries.

## Foundational layer

### The 60-second version

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.

### Why it matters to the business

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.

### How SAP does it

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](https://help.sap.com/doc/c31b38b32a5d4e07a4488cb0f8bb55d9/CLOUD/en-US/f17fa8568d0448c685f2a0301061a6ee.pdf)). Azure OpenAI models only, native model calls only (no orchestration), EU and US regions except `prod-euonly` and sovereign cloud ([SAP documentation](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/batch-consumption-e6a5a0e.md)). 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](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/inference-observability-8e9dacc.md)). Storage is charged by data volume (SAP Note 3720903) |

SAP's Q2 2026 release highlights announced both ([SAP News](https://news.sap.com/2026/07/sap-business-ai-release-highlights-q2-2026/)). In the SAP pages we read, both are used through APIs; reports and alerts on top of them are yours to build.

### Online, batch or not AI at all

Use this guide before you pick an approach for a model workload.

| Question | If yes | If no |
| --- | --- | --- |
| Is a person or a process waiting for the answer right now? | Online call (with observability) | Consider batch |
| Will you send 50 or more requests of the same kind in one go? | Batch is worth setting up (SAP's tutorial uses this threshold) | Online calls are simpler |
| Does each request need orchestration (grounding, masking, filters)? | Online, or redesign: batch takes plain model calls only | Batch is possible |
| Can all requests use the same model? | Batch is possible | Split into one job per model |
| Would a rule, lookup or report do the job? | Don't use a model | Continue |

> **Note** **For functional consultants.** Batch changes how a mass AI job is tested and signed off. Plan a sample check of the results before anything is written back to SAP, and decide who confirms the proposed codes. Observability changes data protection: if full recording is on, prompts with names or customer data are stored. Add both to the test plan and the data protection review, and agree which labels (use case, prompt version, plant) every call must carry.

### Questions to ask

1. Which of our AI workloads have no one waiting? What would they cost as a batch?
2. Is batch consumption available in our SAP AI Core region, and for the model we use?
3. What does SAP charge for batch in our contract, compared with the same calls online?
4. Who checks a sample of a batch job's answers before results reach SAP?
5. Which live AI calls should we record, in full or as metadata only, and for how long?
6. Does anything we would record contain personal data? Who approved storing it unmasked?
7. Who deletes old records, including the payloads in our object store?
8. Which labels must every call carry so we can split results by use case and prompt version?

### Common misconceptions

- **"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.

### Key terms

- **Batch consumption:** the generative AI hub feature that runs many model requests as one background job.
- **JSON Lines (JSONL):** a text file with one JSON object per line; the batch input and output format.
- **custom_id:** your own ID on each batch request, used to match each answer to its request.
- **Object store:** cloud file storage, such as Amazon S3, that SAP AI Core reads and writes through a registered secret.
- **Inference observability:** the SAP AI Core feature that records model calls on request, with labels and feedback.
- **Persistence mode:** the recording level of an observed call: `full` (request, response, metadata) or `metadata` only.
- **Inference record:** one stored model call, found by its inference ID or by its labels.
- **Label:** a key and value attached to a record for filtering, such as the prompt version.
- **Capacity unit:** SAP's billing unit for SAP AI Core usage, including stored inference records.

### Check yourself

1. Calder wants to fill missing damage codes on 240 old maintenance notifications. Nobody is waiting for the result. Which approach fits best?
   - A. Online calls in a loop, as fast as the quota allows
   - B. One batch job, with a sample check before codes go back to SAP
   - C. Inference observability in full mode for each call
   - D. A new orchestration deployment with grounding for each notification

   Answer: B. 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.

2. A project lead says: "The batch job finished with status COMPLETED, so we can load all the codes." What should you ask first?
   - A. Whether the job used the newest model available to the team
   - B. Whether observability was switched on for the job
   - C. Whether the results file came back in the input order
   - D. Whether every request succeeded and a sample was checked

   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.

3. Your team plans to batch requests that use grounding on SAP documents and data masking. What is the problem?
   - A. Batch takes plain model calls only, not orchestration
   - B. Batch jobs can only hold 50 requests at a time
   - C. Grounding is only available in the metadata recording mode
   - D. Batch jobs need a separate SAP AI Core instance per model

   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.

4. Which statement about inference observability is accurate as of November 2026?
   - A. It records every model call automatically once the extended plan is active
   - B. It masks personal data in prompts before storing them
   - C. It records a call only when the request headers ask for it
   - D. It deletes the stored prompts when you delete a record

   Answer: C. 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.

5. Legal asks whether recording the order assistant's prompts in full is safe. What is the right first answer?
   - A. Yes, because SAP masks personal data before it is stored
   - B. Yes, because the records are deleted after 30 days by default
   - C. No, because full recording is only offered in sovereign cloud regions
   - D. Only with consent for any personal data, or use metadata mode instead

   Answer: D. 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.

6. Why should every observed call carry labels such as the use case and prompt version?
   - A. Labels are required before SAP AI Core accepts the call
   - B. They let you split records and compare versions after a change
   - C. They raise the number of records that SAP keeps for free each month
   - D. They decide which model the call is routed to

   Answer: B. Labels exist for filtering and analysis. When a prompt changes, records labeled by version let you compare speed, errors and feedback before and after.

## Deep layer

### Mental model

Think of two lanes and a flight recorder.

- **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](https://erpfde.com/topics/observability-for-ai-systems/), where you recorded traces with OpenTelemetry, and [Token economics](https://erpfde.com/topics/token-economics/), where you priced calls. Here you see what SAP now does for you, and what still sits in your code.

### How it works

#### The batch job

```mermaid
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:

1. **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](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/prepare-and-upload-your-input-file-0b9d245.md)).
2. **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.
3. **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](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/create-a-batch-job-bb19774.md)). The `AI-Resource-Group` header picks the resource group.
4. **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.
5. **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](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/retrieve-results-7d18a48.md)). 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](https://github.com/sap-tutorials/Tutorials/blob/master/tutorials/ai-core-genaihub-batch-consumption/ai-core-genaihub-batch-consumption.md)). These match Microsoft's limits for Azure OpenAI batch ([Microsoft Learn](https://learn.microsoft.com/azure/foundry/openai/how-to/batch)), which SAP's page names as the detailed input specification.

> **Note** Three statuses differ between SAP sources. The Python SDK's `BatchStatus` lists `RUNNING` and no `PREPARING_INPUT`; the JavaScript docs list `RUNNING`; the documentation and tutorial list `IN_PROGRESS`, `INPUT_PREPARED` and `PREPARING_OUTPUT`. Write your poller so that only `COMPLETED`, `FAILED` and `CANCELLED` end the wait, and any other status means "still working". The error file is `error.jsonl` in the documentation and `errors.jsonl` in the JavaScript docs; read whichever exists.

#### Inference observability

```mermaid
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
```

You switch recording on per call with headers ([SAP: record an inference](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/record-an-inference-in-inference-observability-7d493c7.md)):

| Header | Value |
| --- | --- |
| `ai-inference-observability-persistence-mode` | `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](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/deleting-inference-record-data-637b8a8.md)) |

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.

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 10](https://erpfde.com/topics/set-up-for-unit-10/). They create your `orchestrate-course` folder with `.venv`, `.env` and the `unit10` folder.

```mermaid
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]
```

> **Note** New words. **JSON** is a text format for data in `{"key": "value"}` pairs. **JSON Lines** puts one JSON object on each line of a file. An **object store** is cloud file storage, such as an Amazon S3 bucket. A **job** is work you hand to a service to run in the background. **Polling** means asking again and again whether a job is done. A **header** is a named value sent alongside a web request, such as `AI-Resource-Group`.

#### What you need

- Your course folder from the setup topics, with Python 3.10 or newer.
- About 45 to 60 minutes.
- No accounts and nothing to install. The script uses only Python's built-in modules and costs nothing.
- Optional, later: an SAP AI Core tenant with the extended plan for the sketch in [The SAP way](#d-the-sap-way).

> **Note** Everything in this section is **synthetic**. The notifications are generated with a fixed seed (42), and a keyword rule stands in for the model, so your output matches the expected output line for line. The agreement rate, token counts, costs and latencies show the method. They say nothing about any real model or SAP system.

#### Step 1: Open your course folder

1. Open VS Code, choose **File > Open Folder**, and open `orchestrate-course`.
2. Open a terminal: **Terminal > New Terminal**.
3. If the prompt doesn't start with `(.venv)`, turn it on:

   - **Windows (PowerShell):**

     ```powershell
     .venv\Scripts\Activate.ps1
     ```

   - **macOS / Linux:**

     ```bash
     source .venv/bin/activate
     ```

4. Check Python:

   ```bash
   python --version
   ```

   You should see `Python 3.10` or newer.

#### Step 2: Create the script

1. In VS Code's Explorer, right-click the `unit10` folder, choose **New File** and name it `batch_lab.py`.
2. Paste this code and save (**Ctrl+S** on Windows, **Cmd+S** on macOS):

```python
"""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()
```

#### Step 3: Write the batch input file

1. In the terminal, run:

   ```bash
   python unit10/batch_lab.py prepare
   ```

2. You should see:

   ```text
   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
   ```

3. 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.
4. 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.

#### Step 4: Catch a bad file before the service does

A rejected file costs you a round trip of minutes or hours. Check it first.

1. Write a file with three deliberate mistakes:

   ```bash
   python unit10/batch_lab.py prepare --broken
   ```

2. Check it:

   ```bash
   python unit10/batch_lab.py check unit10/batch/input_broken.jsonl
   ```

3. You should see:

   ```text
   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.

#### Step 5: Run the batch job locally

1. Run:

   ```bash
   python unit10/batch_lab.py submit
   ```

2. You should see:

   ```text
   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
   ```

3. 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.

#### Step 6: Match the answers back

1. Run:

   ```bash
   python unit10/batch_lab.py collect
   ```

2. You should see:

   ```text
   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)
   ```

> **Note** These numbers are synthetic. The 96.2% compares a keyword rule with made-up "true" codes. The cost uses course prices (2.00 and 8.00 USD per million input and output tokens) and a course assumption that batch costs half. They show how to count, not what a real model or SAP charges.

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](https://erpfde.com/topics/project-maintenance-notification-triage/).

#### Step 7: Record a day of live calls

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.

1. Run:

   ```bash
   python unit10/batch_lab.py observe
   ```

2. You should see:

   ```text
   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)
   ```

3. 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.

> **Note** Synthetic again: the latencies, error codes and stars are generated to show a quiet regression. The storage line uses the factors from SAP's worked example in the service guide (0.002048 MB per record per day). Your real rates are in SAP Note 3720903 and your own metering.

#### Step 8: Record metadata only

1. Run:

   ```bash
   python unit10/batch_lab.py observe --mode metadata
   ```

2. 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.

3. 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.

#### Step 9: Save your work

1. Keep generated files out of Git. Open `.gitignore` in your course folder and add a line:

   ```text
   unit10/batch/
   ```

2. Commit the script:

   ```bash
   git add .gitignore unit10/batch_lab.py
   git commit -m "Unit 10: batch and observability lab"
   ```

#### How the code works

| Part | What it does |
| --- | --- |
| `make_notifications` | Generates the made-up notifications with seed 42, so every run is the same |
| `batch_line` | Builds one batch request in SAP's line format, with the notification number as `custom_id` |
| `check_file` | Applies the rules from SAP's pages: size, line count, valid JSON, unique IDs, `POST`, the one allowed URL, one model |
| `fake_model` | A keyword rule standing in for the model, wrong on purpose sometimes |
| `cmd_submit` | Plays the batch service: statuses, shuffled `output.jsonl`, failed requests in `error.jsonl` |
| `cmd_collect` | Matches on `custom_id`, separates failed, unusable and missing lines, scores against the sample, writes proposals and retries |
| `check_labels` | Applies SAP's label rules: prefix, count, length, characters |
| `cmd_observe` | Writes inference records in SAP's shape, reports by prompt version, estimates storage |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python` is "not recognized" / "command not found" | Python isn't on the path, or `.venv` isn't on | Turn on `.venv` (Step 1); see [Set up your computer](https://erpfde.com/topics/set-up-your-computer/) |
| `can't open file ... batch_lab.py` | You're not in the course folder, or the file has another name | Open `orchestrate-course` and check the file is `unit10/batch_lab.py` |
| `unit10/batch/input.jsonl not found` | `prepare` wasn't run | Run `python unit10/batch_lab.py prepare` |
| `No batch output yet` | `collect` ran before `submit`, or `--batch` names a folder that doesn't exist | Run `submit`, or check the folder under `unit10/batch/output/` |
| `ModuleNotFoundError` | You ran the SAP sketch below, not the lab | The lab needs no libraries; the sketch needs `pip install -r requirements.txt` |
| Your numbers differ from the page | The script was changed, or a different `--count` was used | Paste the script again and run `prepare` without options |
| A network or proxy error | Not possible in the lab | The lab makes no network calls; check you ran `batch_lab.py` |

### The SAP way

#### Batch consumption

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.

> **Note** This is a **sketch**. It needs an SAP AI Core tenant with the extended plan, an object store secret registered in your resource group, and the `AICORE_*` values in `.env` that Unit 3 set up ([Choosing and calling LLMs](https://erpfde.com/topics/choosing-and-calling-llms/)). Running it sends real requests and is charged. Add `sap-ai-sdk-gen==7.4.1` and `httpx` to `requirements.txt` if you try it.

```python
"""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.

#### Inference observability

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:

```python
# 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](https://erpfde.com/topics/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.

### Build vs. SAP

| Need | Build yourself (this course) | SAP generative AI hub | Choose |
| --- | --- | --- | --- |
| Many requests that can wait | A queue worker with retries and backoff, as in [Set up for Unit 4](https://erpfde.com/topics/set-up-for-unit-04/) | Batch consumption: one file, retries and rate limits handled | SAP, if the model and region are supported and you don't need orchestration |
| Bulk work that needs grounding or masking | Your own loop through orchestration, throttled | Not supported in batch | Build, or mask and ground before you write the file |
| Record live calls | Traces in your own store, with your own masking ([Observability for AI systems](https://erpfde.com/topics/observability-for-ai-systems/)) | Inference observability: metadata or full, labels, feedback | Both: SAP's record at the model, your trace across the whole request |
| User feedback | Your own feedback table ([Online evaluation](https://erpfde.com/topics/online-evaluation-and-user-feedback/)) | Feedback on the inference record, full mode only | Yours if you need masking or joins to business data; SAP's if the record is the unit |
| Alerts and SLOs | Your health report and alerts | Not offered by these features | Build |
| Release decisions | Your evaluation gate ([CI/CD](https://erpfde.com/topics/cicd-for-ai-applications/)) | Not offered | Build; use SAP's records as input |

### Architecture view

**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.

```mermaid
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.

**The decision to record** (short ADR form from [Writing a solution design doc](https://erpfde.com/topics/writing-a-solution-design-doc/)):

- **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**

1. What enters the batch file, and who approved it for a model provider?
2. How do answers reach SAP, and who confirms them?
3. What happens to a job that fails at 03:00, and who is told?
4. Which calls are recorded in full, why, and when are the payloads deleted?
5. What does batch cost per 1,000 requests in our contract, and how was that measured?

### Production concerns

- **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.

### Pitfalls

- **Trusting `COMPLETED`.** It means the job ran, not that every request worked. Count failed, unusable and missing lines.
- **Matching by position.** Output order isn't guaranteed. Match on `custom_id`, and make it a business key, such as the notification number.
- **Two models in one file.** The service expects one model per job. Split the file.
- **Expecting orchestration in batch.** Grounding, masking and filters don't run. Prepare the content before the file is written.
- **A poller that knows every status.** SAP's sources list different statuses. End the wait only on the three final ones.
- **Recording in full by default.** You inherit unmasked content and an S3 bucket to govern. Start with metadata.
- **Deleting without criteria.** A delete request with no time range or labels removes all record data in the resource group. Always pass criteria.
- **Assuming deletion is complete.** Record deletion leaves the payloads in S3. Delete them with your object store's lifecycle rules.

### Exercise

Add a plant label to every recorded call, see SAP's label rules stop a bad one, and prepare the retry job.

1. Open `unit10/batch_lab.py`. Find the line in `cmd_observe` that starts with `labels = {`.
2. Add a third label with a mistake in it, so the line reads:

   ```python
   labels = {"ext.ai.sap.com/use-case": "notif-coding", "ext.ai.sap.com/prompt": "v3", "plant": "CP11"}
   ```

3. 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.
4. 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.
5. Run `python unit10/batch_lab.py check unit10/batch/retry.jsonl`. You should see `retry.jsonl: 6 lines, OK`.
6. 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](https://erpfde.com/topics/project-maintenance-notification-triage/).

### Check yourself

1. A batch job for 240 notifications ends with status COMPLETED. What must your collect step still do?
   - A. Sort the output lines back into input order before reading them
   - B. Re-submit the whole file, because COMPLETED is not final
   - C. Count failed, unusable and missing lines per custom_id
   - D. Load all codes into SAP, since the service already retried failures

   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.

2. Why does the lab use the notification number as the custom_id?
   - A. The batch service rejects IDs that aren't numbers
   - B. It is the only link from an unordered answer back to its record
   - C. It makes the model answer faster for known equipment
   - D. SAP AI Core uses it to choose the resource group

   Answer: B. 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.

3. Your poller stops when the status is not PENDING or IN_PROGRESS. A job reports INPUT_PREPARED. What happens, and what should the rule be?
   - A. Nothing goes wrong, because INPUT_PREPARED is a final status
   - B. The job is cancelled, so the rule should cancel on any new status
   - C. The poller waits forever, so the rule should add a timeout only
   - D. It stops too early; end the wait only on COMPLETED, FAILED or CANCELLED

   Answer: D. 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.

4. You must batch-classify supplier emails, and the design uses orchestration's data masking to remove names first. What do you change?
   - A. Nothing, because batch jobs run the orchestration modules too
   - B. Mask the text yourself before writing the file, or keep it online
   - C. Switch observability to metadata mode for the batch job
   - D. Add the masking module name to the batch spec's provider field

   Answer: B. 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.

5. Which headers record an orchestration call with its prompt and answer, plus a prompt-version label?
   - A. AI-Resource-Group set to observe, plus a labels query parameter
   - B. Persistence mode full, the object store secret name, and the labels header
   - C. Persistence mode metadata, plus the labels header with a feedback key
   - D. The ai-inference-id header on the request, plus the object store secret name

   Answer: B. 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.

6. After a prompt change, planners complain about codes but your records are in metadata mode. What can and can't you learn from them?
   - A. Speed, errors and tokens by version, but no answers and no feedback
   - B. Everything, because metadata mode keeps the answers in a summary
   - C. Nothing, because metadata records can't be filtered by labels
   - D. Only the feedback, because SAP removes tokens and latency in this mode

   Answer: A. 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.

7. A colleague wants to clean up records with a delete request that has no time range or labels. What happens?
   - A. SAP refuses the request, because criteria are mandatory
   - B. Only records older than 30 days are deleted
   - C. All record data in the resource group is deleted, but S3 payloads remain
   - D. All records and their S3 payloads are deleted in one step

   Answer: C. 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.

8. What drives the monthly storage cost of inference records most in the lab's estimate?
   - A. The model chosen for each call
   - B. The number of labels per record
   - C. The number of records kept, which retention multiplies
   - D. Whether the calls used orchestration or a model directly

   Answer: C. 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.

## Sources

- [SAP AI Core service guide, PDF edition of 16 November 2026 (SAP Help Portal)](https://help.sap.com/doc/c31b38b32a5d4e07a4488cb0f8bb55d9/CLOUD/en-US/f17fa8568d0448c685f2a0301061a6ee.pdf): 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)](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/batch-consumption-e6a5a0e.md): 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)](https://github.com/sap-tutorials/Tutorials/blob/master/tutorials/ai-core-genaihub-batch-consumption/ai-core-genaihub-batch-consumption.md): 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
- [Processing Batch LLM Requests with the Batch API (SAP Cloud SDK for AI for JavaScript docs, SAP/ai-sdk on GitHub)](https://github.com/SAP/ai-sdk/blob/main/docs-js/tutorials/llm-batch-api.mdx): read 2026-11-19; selected Azure OpenAI models only; jobs can run up to 24 hours; poll every 30 to 60 minutes for large batches; the @sap-ai-sdk/llm-batch package (2.18.0) is marked experimental; its model type lists gpt-4.1, gpt-4.1-mini, gpt-4.1-nano, gpt-5, gpt-5.4 and gpt-5.4-mini
- [sap-ai-sdk-gen 7.4.1 (SAP Cloud SDK for AI for Python, PyPI)](https://pypi.org/project/sap-ai-sdk-gen/): read 2026-11-19; gen_ai_hub.batch_service.BatchService with create, list, get, get_status, cancel, delete; base path /llm-batch-service/v1/batches; batch support added in 7.2.0
- [Inference Observability (SAP AI Core documentation, SAP-docs on GitHub)](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/inference-observability-8e9dacc.md): 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)](https://github.com/SAP-docs/sap-artificial-intelligence/blob/main/docs/sap-ai-core/generativeAI/record-an-inference-in-inference-observability-7d493c7.md): 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)
- [Inference observability tutorial and its Bruno request collection (sap-tutorials/Tutorials and SAP-samples/aicore-genai-samples on GitHub)](https://github.com/sap-tutorials/Tutorials/blob/master/tutorials/ai-core-genaihub-inference-observability/ai-core-genaihub-inference-observability.md): read 2026-11-19; the response header ai-inference-id carries the inference ID; the collection calls {{deploymentUrl}}/v2/completion and {{AI_API}}/observability/inferences...; sample records show latency 637.341 and 8.058194893994369 with no unit
- [SAP Business AI: Release Highlights Q2 2026 (SAP News, July 2026)](https://news.sap.com/2026/07/sap-business-ai-release-highlights-q2-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)](https://learn.microsoft.com/azure/foundry/openai/how-to/batch): 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
