Dashboard

Cookbook Recipe

Batch & Storage

Batch-embed a corpus onto a Network Volume

Embed a document corpus in batches from a CPU instance, record completed document IDs on a Network Volume, and resume cleanly without re-embedding finished batches.

POSThttps://api.devupai.com/v1/embeddings

What you'll build

A batch embedding script that writes JSONL vector records (/workspace/embeddings/vectors.jsonl) and an atomic checkpoint file (/workspace/embeddings/checkpoint.json) to an attached Network Volume. If the instance is paused or the run is interrupted, rerunning the script skips every document ID already recorded in checkpoint.json.

Before you start

  • An API key (sk-devup-...) exported as DEVUP_API_KEY. See Authentication.
  • A running CPU or GPU instance with a Network Volume mounted at /workspace.
  • Python 3.11 or later, or Node.js 22 or later.
pip install devupai

The complete program

Both programs use the official devupai SDK (client.embeddings.create) and store both the vectors and the checkpoint file on /workspace.

"""Batch-embed a corpus onto a Network Volume at /workspace with checkpointing."""

import json
import os
from pathlib import Path
import sys

from devupai import APIConnectionError, DevupAI, DevupAPIError

EMBEDDING_MODEL = "Qwen/Qwen3-Embedding-8B"
BATCH_SIZE = 4
TIMEOUT_S = 60.0

WORKSPACE_DIR = Path(os.environ.get("WORKSPACE_DIR", "/workspace/embeddings"))
OUTPUT_FILE = WORKSPACE_DIR / "vectors.jsonl"
CHECKPOINT_FILE = WORKSPACE_DIR / "checkpoint.json"

CORPUS = [
    {"id": "doc-1", "text": "Network Volumes persist files across GPU and CPU instance lifecycles."},
    {"id": "doc-2", "text": "Pausing an instance releases its compute hardware and switches to the reduced idle rate."},
    {"id": "doc-3", "text": "Container Disk contents are reset whenever an instance is paused or terminated."},
    {"id": "doc-4", "text": "Deploying or resuming an instance holds one hour of its running rate while it starts."},
]


def load_completed_ids(path: Path) -> set[str]:
    """Load the set of document IDs already written to OUTPUT_FILE."""
    if not path.exists():
        return set()
    data = json.loads(path.read_text(encoding="utf-8"))
    if isinstance(data, dict) and isinstance(data.get("completed"), list):
        return {str(item) for item in data["completed"]}
    return set()


def save_completed_ids(path: Path, completed: set[str]) -> None:
    """Persist completed document IDs atomically so a rerun skips finished batches."""
    tmp = path.with_suffix(".tmp")
    tmp.write_text(
        json.dumps({"model": EMBEDDING_MODEL, "completed": sorted(completed)}, indent=2),
        encoding="utf-8",
    )
    tmp.replace(path)


def embed_batch(client: DevupAI, texts: list[str]) -> list[list[float]]:
    """Embed one batch of non-empty strings and order vectors by data[].index."""
    response = client.embeddings.create(
        model=EMBEDDING_MODEL,
        input=texts,
        encoding_format="float",
    )
    if not response.data:
        raise ValueError("The embeddings response contained no data.")
    vectors: list[list[float] | None] = [None] * len(texts)
    for item in response.data:
        if not isinstance(item.index, int) or not 0 <= item.index < len(texts):
            raise ValueError(f"Unexpected embedding index: {item.index}")
        vectors[item.index] = list(item.embedding)
    if any(vec is None for vec in vectors):
        raise ValueError("The embeddings response left an input without a vector.")
    return [vec for vec in vectors if vec is not None]


def error_line(error: Exception) -> str:
    """One diagnostic line for an error that stops the program, including x-request-id."""
    if isinstance(error, APIConnectionError):
        return f"No response from the API: {error}"
    if isinstance(error, DevupAPIError):
        return f"The API answered {error.status} {error.code or 'no code'} (x-request-id: {error.request_id or 'none'})."
    return str(error)


def main() -> None:
    if not os.environ.get("DEVUP_API_KEY", "").strip():
        print("Set DEVUP_API_KEY.", file=sys.stderr)
        sys.exit(1)

    client = DevupAI(api_key=os.environ["DEVUP_API_KEY"], max_retries=0, timeout=TIMEOUT_S)
    WORKSPACE_DIR.mkdir(parents=True, exist_ok=True)
    completed = load_completed_ids(CHECKPOINT_FILE)
    pending = [doc for doc in CORPUS if doc["id"] not in completed and doc["text"].strip()]

    try:
        with OUTPUT_FILE.open("a", encoding="utf-8") as handle:
            for start in range(0, len(pending), BATCH_SIZE):
                batch = pending[start : start + BATCH_SIZE]
                vectors = embed_batch(client, [doc["text"] for doc in batch])
                for doc, vector in zip(batch, vectors):
                    record = {"id": doc["id"], "model": EMBEDDING_MODEL, "embedding": vector}
                    handle.write(json.dumps(record) + "\n")
                    completed.add(doc["id"])
                handle.flush()
                save_completed_ids(CHECKPOINT_FILE, completed)
        print(f"Completed {len(completed)} embeddings in {OUTPUT_FILE}")
    except Exception as exc:
        print(error_line(exc), file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
Output shape
Plain text
Completed 4 embeddings in /workspace/embeddings/vectors.jsonl

How it works

1Place each embedding by data[].index

Each batch is sent with encoding_format: "float". The program places every returned vector at item.index within the batch and verifies that no input document was left without a vector before writing to disk.

def embed_batch(client: DevupAI, texts: list[str]) -> list[list[float]]:
    """Embed one batch of non-empty strings and order vectors by data[].index."""
    response = client.embeddings.create(
        model=EMBEDDING_MODEL,
        input=texts,
        encoding_format="float",
    )
    if not response.data:
        raise ValueError("The embeddings response contained no data.")
    vectors: list[list[float] | None] = [None] * len(texts)
    for item in response.data:
        if not isinstance(item.index, int) or not 0 <= item.index < len(texts):
            raise ValueError(f"Unexpected embedding index: {item.index}")
        vectors[item.index] = list(item.embedding)
    if any(vec is None for vec in vectors):
        raise ValueError("The embeddings response left an input without a vector.")
    return [vec for vec in vectors if vec is not None]

2Checkpoint completed document IDs on /workspace

After each batch is flushed to vectors.jsonl, the program writes the updated set of completed document IDs to a temporary file on the Network Volume and renames it over checkpoint.json. In Node.js, the program also awaits once(out, "finish") after closing the output stream.

def save_completed_ids(path: Path, completed: set[str]) -> None:
    """Persist completed document IDs atomically so a rerun skips finished batches."""
    tmp = path.with_suffix(".tmp")
    tmp.write_text(
        json.dumps({"model": EMBEDDING_MODEL, "completed": sorted(completed)}, indent=2),
        encoding="utf-8",
    )
    tmp.replace(path)

Next steps