Docs menu
Docs · Cookbook

Cookbook

Four patterns for a retrieval pipeline: register embeddings when you ingest, verify what you retrieve before it reaches a model, record how one object was derived from another, and gate product rows before a catalog assistant or shopping agent sees them. Each recipe is executed in CI against SDK 3.1.4 and the published OpenAPI schema.

Before you start

pip install mnemo-protocol

Set MNEMO_API_KEY to an API key from your dashboard (no key yet? sign in or create a workspace). Your model and vector store stay as they are: model.embed() and store.upsert() below stand for your own code. Calls made with an API key use your account's plan.

1. Register embeddings at ingest

Embed through Mnemo before you write to your store, and store the watermarked_vector in place of the original. Keep vector_uid with the row: it names the registered object and is the parent reference for lineage.

python · ingest
import os
from mnemo_sdk import MnemoClient

client = MnemoClient(api_key=os.environ["MNEMO_API_KEY"])

def ingest(docs, model, store):
    """Register each document's embedding; store the watermarked copy."""
    for doc_id, text in docs:
        r = client.embed(model.embed(text), model_id="text-embedding-3-small")
        # Store the watermarked copy, not the original: it is the vector that verifies.
        store.upsert(doc_id, r.watermarked_vector, {"vector_uid": r.vector_uid})

2. Gate retrieval before the model sees it

Verify each retrieved vector and pass on only the ones that resolve to the vector_uid stored on their row. verify() returns None when a vector does not verify, so check for None before reading .verified. Each call is one verification against your plan.

python · retrieval gate
import os
from mnemo_sdk import MnemoClient

client = MnemoClient(api_key=os.environ["MNEMO_API_KEY"])

def verified_hits(hits):
    """Keep hits that verify to the vector_uid stored on their row; report the rest."""
    kept, dropped = [], []
    for hit in hits:
        check = client.verify(hit.values)
        # None: attribution to your account could not be shown.
        # It is not proof that the vector is foreign or tampered with.
        # A different vector_uid: it resolves to another of your objects, not this row's.
        if check is not None and check.vector_uid == hit.metadata.get("vector_uid"):
            kept.append(hit)
        else:
            dropped.append(hit.id)
    return kept, dropped

A dropped hit either did not verify or resolved to a different registered object than its row names. Neither says who produced the vector, and neither is a judgment of the content. Log the ids and decide what your pipeline does with them.

3. Record lineage for a derived chunk

When you split, summarize, translate or re-embed an object, register the result with a parent: the parent's vector_uid, a relation (re_embed, summary, chunk, translation or transform) and the parent's watermarked vector, which must verify as that vector_uid. Lineage is part of the HTTP API; the Python SDK does not expose parent yet.

shell · curl
# 1. Register the source document. Random vectors stand in for your embeddings.
DOC=$(python3 -c 'import random; print([random.uniform(-1, 1) for _ in range(768)])')
curl -sS https://api.trymnemo.com/v1/embed \
  -H "X-API-Key: $MNEMO_API_KEY" -H "Content-Type: application/json" \
  -d "{\"vector\": $DOC, \"model_id\": \"text-embedding-3-small\"}" > parent.json

# 2. Register a chunk of it. The parent is its vector_uid plus the watermarked copy you hold.
CHUNK=$(python3 -c 'import random; print([random.uniform(-1, 1) for _ in range(768)])')
PARENT=$(python3 -c 'import json; p = json.load(open("parent.json")); print(json.dumps({"vector_uid": p["vector_uid"], "relation": "chunk", "vector": p["watermarked_vector"]}))')
curl -sS https://api.trymnemo.com/v1/embed \
  -H "X-API-Key: $MNEMO_API_KEY" -H "Content-Type: application/json" \
  -d "{\"vector\": $CHUNK, \"model_id\": \"text-embedding-3-small\", \"parent\": $PARENT}" > chunk.json

# 3. Read the chain, parent first. Every link is re-verified when it is read.
CHUNK_UID=$(python3 -c 'import json; print(json.load(open("chunk.json"))["vector_uid"])')
curl -sS https://api.trymnemo.com/v1/lineage/$CHUNK_UID -H "X-API-Key: $MNEMO_API_KEY"

GET /v1/lineage/{vector_uid} returns the chain, parent first, and re-verifies every link when it is read. A parent that does not verify as yours is refused with 403 LINEAGE_PARENT_NOT_VERIFIED. Lineage records which registered object another was derived from; it does not describe what the transformation did.

4. Product catalog RAG: verify retrieved rows before the model sees them

A catalog assistant or shopping agent retrieves product rows and passes them to a model. Register each product's embedding when you write the row, keep watermarked_vector and vector_uid on it, and verify each row you are about to pass on before a model sees it. The script runs as written: a dictionary stands in for your product database and stand_in_embed() for your embedding model. Mnemo does not create embeddings; it registers the vectors your model produces.

python · catalog RAG
import os
import random

from mnemo_sdk import MnemoClient

client = MnemoClient(api_key=os.environ["MNEMO_API_KEY"])

MODEL_ID = "text-embedding-3-small"  # the model_id label you declare; use your own model's id


def stand_in_embed(text, dim=768):
    """STAND-IN for your embedding model. Mnemo does not create embeddings.

    Adds up a fixed pseudo-random vector per word, so texts that share words
    score higher. Replace this with your model's embed call.
    """
    vec = [0.0] * dim
    for word in text.lower().split():
        rng = random.Random(word)
        for i in range(dim):
            vec[i] += rng.uniform(-1.0, 1.0)
    norm = sum(x * x for x in vec) ** 0.5
    return [x / norm for x in vec]


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


catalog = {}  # sku -> product row; stands in for your product database


def add_product(sku, title, price):
    """On insert: register the item's embedding, store the watermarked copy."""
    r = client.embed(stand_in_embed(title), model_id=MODEL_ID)
    # Write the row only after embed() returns, with both fields on it.
    catalog[sku] = {
        "sku": sku,
        "title": title,
        "price": price,
        "vector": r.watermarked_vector,  # store this copy, not the original
        "vector_uid": r.vector_uid,
    }


def search(query, k=3):
    """Stand-in for your vector store's query: top k rows by dot product."""
    q = stand_in_embed(query)
    return sorted(catalog.values(), key=lambda row: dot(q, row["vector"]), reverse=True)[:k]


def verify_candidates(rows):
    """On retrieval: verify each candidate before a model or agent sees it."""
    passed, held_back = [], []
    for row in rows:
        check = client.verify(row["vector"])
        if check is None:
            # The API answered verified=false: attribution to your account
            # could not be shown. It is not a verdict on the product.
            held_back.append((row["sku"], "not verified"))
        elif check.vector_uid != row["vector_uid"]:
            # Resolves to your account, but not to the object this row names.
            held_back.append((row["sku"], "vector_uid mismatch"))
        else:
            # check.confidence is a relative signal, not a probability:
            # log it if useful, do not set a threshold on it.
            passed.append(row)
    return passed, held_back


def context_for_model(query, k=3):
    """What you hand to an LLM or shopping agent: only rows that resolved to their own vector_uid."""
    passed, held_back = verify_candidates(search(query, k))
    for sku, reason in held_back:
        print("held back:", sku, reason)  # log for review
    return [{"sku": r["sku"], "title": r["title"], "price": r["price"]} for r in passed]


for sku, title, price in [
    ("sku-101", "waterproof leather hiking boots", 189.0),
    ("sku-102", "lightweight trail running shoes", 129.0),
    ("sku-103", "insulated waterproof winter boots", 219.0),
    ("sku-104", "merino wool hiking socks", 24.0),
]:
    add_product(sku, title, price)

# A row written without add_product(), for example by a bulk import that
# skipped registration. It has no stored vector_uid, so it is held back
# whatever verify() answers.
catalog["sku-999"] = {
    "sku": "sku-999",
    "title": "waterproof hiking boots",
    "price": 49.0,
    "vector": stand_in_embed("waterproof hiking boots"),
    "vector_uid": None,
}

print(context_for_model("waterproof hiking boots"))

A row is passed on only when verify() returns a result whose vector_uid is the one stored on that row. Otherwise the row is held back: verify() returned None (the API answered verified=false), or the result names a different registered object than the row does, for example after the row's vector was overwritten with another product's. A row written without add_product(), such as sku-999 here, has no stored vector_uid, so it is held back whatever verify() answers. If verify() raises (for example when the plan is out of verifications), no rows are passed. The script prints the held-back row and returns the two rows that pass.

A held-back row means the vector could not be attributed to the object recorded on the row; a passed row means only that it was. Neither says who produced the vector, whether the listing is accurate, or what an agent should do next. Verification is tenant-scoped: it resolves only to objects registered to your own account or namespace. confidence is a relative signal, not a probability; decide on the result, not on a confidence threshold.

Each verify() call is one verification against your plan, whether or not the vector verifies, so verify the top few candidates you will pass on rather than every hit. One run of this script makes four embed calls and three verify calls.

Agents without an account

Agents can run the same embed, verify and lineage calls with a namespace capability instead of an API key, and pay per verification. Start at agent onboarding or read the agent protocol.