EmbeddingBatch APIRAGAPI

Keep batched embeddings attached to the right source text

Map each embedding index to its request input and stable chunk ID. Async Batch adds custom_id for the outer request; reject incomplete or invalid mappings before indexing.

Keep batched embeddings attached to the right source text

An embedding batch can contain valid vectors that are attached to the wrong source records. In the OpenAI format, index identifies a position within the request input. Stable chunk IDs belong to the application. Validate that relationship before indexing, or retrieval may find one passage while citations point to another.

The cover illustrates batch pairing conceptually. API indices are zero-based; the diagrams and code below specify the actual mapping.

This article checks the OpenAI embeddings reference, Batch guide, and Nbility's Embeddings API on November 26, 2026. The reordered response below is constructed to test a consumer, not evidence that a particular provider reorders responses.

Is index a global document ID?

No. It identifies a position in the current input list. A different request has its own positions; item zero in two requests does not establish a shared source identity.

Before submission, retain an immutable mapping from request identity and input position to stable chunk ID, source revision, and actual input. Keep private text in appropriate task storage. Ordinary diagnostic logs should contain only the identifiers and summaries needed to investigate the job.

Request-local indices map to stable chunk IDs and then source revisions

Identical text does not necessarily mean identical source records. Permissions, effective dates, and citation locations may differ. Even if vector computation is reused, preserve each source relationship.

Is sorting by index and using zip enough?

No. Validate count, index coverage, duplicates, and vector structure too. Sorting [0, 0] still leaves item one missing, and zip silently stops at the shorter input.

This complete Python example uses synthetic records and two-dimensional vectors. dimensions=2 is for demonstration; use the verified index dimension in an actual integration:

import math


def align_embeddings(records, data, dimensions):
    ids = [row["id"] for row in records]
    if not records or len(set(ids)) != len(ids):
        raise ValueError("Empty input or duplicate source IDs")
    if len(data) != len(records):
        raise ValueError("Unexpected embedding count")
    aligned = [None] * len(records)
    for item in data:
        index = item["index"]
        if type(index) is not int or not 0 <= index < len(records):
            raise ValueError("Invalid input index")
        if aligned[index] is not None:
            raise ValueError("Duplicate input index")
        vector = item["embedding"]
        if not isinstance(vector, list) or len(vector) != dimensions:
            raise ValueError("Unexpected vector dimensions")
        if any(type(value) not in (int, float)
               or not math.isfinite(value) for value in vector):
            raise ValueError("Invalid vector value")
        aligned[index] = {"id": ids[index], "vector": vector}
    if any(row is None for row in aligned):
        raise ValueError("Missing input index")
    return aligned


records = [{"id": "demo-policy-v1-01"}, {"id": "demo-policy-v1-02"}]
data = [
    {"index": 1, "embedding": [0.3, 0.4]},
    {"index": 0, "embedding": [0.1, 0.2]},
]
print(align_embeddings(records, data, dimensions=2))

The result attaches [0.1, 0.2] to demo-policy-v1-01 and [0.3, 0.4] to demo-policy-v1-02. The function consumes an already parsed float-array response. It does not decode Base64, make requests, or write a database.

Validate count, indices, dimensions, and numeric values before releasing records for indexing

Matching dimensions do not prove compatibility with an existing model space or cache. This checker prevents mismapping and obvious structural failures, not a provider internally calculating the wrong representation.

Why does asynchronous Batch also need custom_id?

Batch output lines may not follow input line order. OpenAI's current guide explicitly says to map results by custom_id. If a request itself contains several embedding inputs, there are two mapping levels:

  1. Use custom_id to find the saved request and its input table.
  2. Check request success before reading its embedding data.
  3. Use each data[].index to identify the corresponding stable chunk.
  4. Validate completeness and source revision before writing.

An outer custom_id cannot replace an inner index, and index=0 cannot identify the outer request. Reconcile failures using the error file or status information instead of assuming an absent result succeeded.

custom_id identifies the request and index identifies an input inside that request

This is the OpenAI Batch contract. It does not establish that Nbility's text embedding endpoint provides the same asynchronous file API. Image and video task IDs are different mechanisms. The Gemini batch reconciliation guide covers another interface whose own result contract must be followed.

How can a retry avoid overwriting newer source text?

Keep the original request and source revision before choosing what to retry. Validate a response completely, stage it, and check that its source revision is still eligible when writing. A late result from an older request should not replace an embedding for updated text.

Versioned record identities or an explicit application-side revision check can enforce that policy, depending on storage. Recognize already processed results rather than creating duplicate chunks. A failed request observation alone does not establish that no previous write occurred.

This also protects the citation chain: a citation should refer to the text represented by the vector, not a newer page that reused a local sequence number.

What can be checked without calling a model?

Run the reordered happy path, then introduce a missing result, duplicate index, out-of-range index, Boolean index, wrong vector dimension, non-finite value, and duplicate source ID. We ran those cases against the program in both language versions.

These checks do not verify real model-to-text correspondence, database retries, concurrent writes, or atomic commits. Start the live integration with two clearly different public passages, inspect the saved request mapping and final retrieved sources, then expand the batch. If source selection is right but citations are wrong, continue with candidate and reranker source mapping.

Related posts

Run your Agent workflow through Nbility

Get an API key and connect OpenAI-compatible models and developer tools from one place.

Get an API key