48  One program, four surfaces — Python, the CLI, Rust and TypeScript

Verbs: jammi sources add · jammi embed · jammi search (the CLI) · InferenceSession::add_source / generate_text_embeddings / search_by_id (Rust) · catalog.addSource / embedding.generateEmbeddings / embedding.search (TypeScript, @f-inverse/jammi-client) · add_source / generate_embeddings / search (Python) · Checked: parity (one program, the same rows on every surface).

Every other chapter reaches the engine from Python. Python is one of four surfaces: the jammi command line, the Rust crates, and the TypeScript client drive the same engine through the same verbs. This chapter writes one small program — register a source, embed it, search it — and runs it on all four, then checks that they return the same rows.

The CLI, the TypeScript client and Python’s remote arm talk to one server over the jammi.v1 wire; the Rust program links the engine in process, the way the Rust quickstart does. So the chapter checks two properties at once: every surface exposes the program, and the in-process engine and the server agree.

48.1 The program and the server

The corpus is the twenty-row tiny_corpus and the encoder the tiny BERT checkpoint the book ships, so every surface finishes in seconds once built. The query is by example: the rows nearest the vector stored for row 1. Every surface can ask it without a text encoder of its own.

import contextlib
import importlib.metadata
import json
import os
import subprocess
import tempfile
from pathlib import Path

import jammi
from jammi.testing import LiveServer
from jammi_cookbook import fixtures, programs
from jammi_cookbook.claims import claim

VERSION = importlib.metadata.version("jammi-ai")
CORPUS = fixtures.url("tiny_corpus.parquet")
MODEL = fixtures.model("tiny_bert")
ROW_KEY = "1"
work = Path(tempfile.mkdtemp(prefix="jammi_surfaces_"))

stack = contextlib.ExitStack()
server = stack.enter_context(LiveServer(work / "server"))
print(f"jammi {VERSION}; server at {server.endpoint}")
print(f"built from {'this checkout' if programs.checkout() else 'the release'}")


def rows(records) -> list[tuple[int, float]]:
    """Ranked `(id, similarity)` pairs, similarity to five places."""
    return [(int(r["id"]), round(float(r["similarity"]), 5)) for r in records]
jammi 0.54.0; server at grpc://127.0.0.1:41893
built from this checkout

48.2 Python

with jammi.connect(server.endpoint) as db:
    db.add_source("corpus_py", url=CORPUS, format="parquet")
    db.generate_embeddings(source="corpus_py", model=MODEL, columns=["content"], key="id")
    hits = db.search("corpus_py", row_key=ROW_KEY, k=3, select=["id", "similarity"])
python_rows = rows(hits.to_pylist())
print(python_rows)
[(1, 1.0), (5, 0.97997), (16, 0.97653)]

48.3 The command line

The jammi binary is a strict client of a running server. jammi embed and jammi search are its data verbs, beside the control verbs (sources, models, jobs and the rest). search prints its rows as JSON lines, one object per row in rank order, so a shell pipeline or a script reads them exactly.

jammi_cli = programs.cli(VERSION)


def cli(*args: str) -> str:
    return subprocess.run([jammi_cli, "--target", server.endpoint, *args],
                          capture_output=True, text=True, check=True).stdout


print(cli("sources", "add", "corpus_cli", "--url", CORPUS, "--format", "parquet"))
print(cli("embed", "corpus_cli", "--model", MODEL, "--columns", "content", "--key", "id"))
cli_out = cli("search", "corpus_cli", "--row-key", ROW_KEY, "-k", "3",
              "--select", "id,similarity")
print(cli_out)
cli_rows = rows(json.loads(line) for line in cli_out.splitlines())
Source 'corpus_cli' added.

table:      corpus_cli__text_embedding_____w_jammi-ai_jammi-ai_cookbook_book_jammi_cookbook__fixtures_ti__20261003T074347077454698_23887e97
rows:       20
dimensions: 32
cache:      computed

{"id":1,"retrieved_by":["vector"],"annotated_by":[],"similarity":1.0}
{"id":5,"retrieved_by":["vector"],"annotated_by":[],"similarity":0.97996515}
{"id":16,"retrieved_by":["vector"],"annotated_by":[],"similarity":0.9765265}

48.4 Rust

The Rust program is the Rust quickstart’s shape: an InferenceSession over a JammiConfig, the engine linked into the binary, with no server. Its artifact directory comes from the environment, as any other setting would.

print((programs.program("one_program") / "main.rs").read_text())
//! The cookbook's one program through the Rust API: register a source, embed
//! it, and search it with an in-process `InferenceSession` — the engine linked
//! into this binary, no server.
//!
//! Usage: `one_program <corpus-url> <model> <row-key>`. The artifact directory
//! and every other setting come from `jammi.toml` or the `JAMMI_*` environment.
//! Prints the three rows nearest `<row-key>` as JSON lines, in rank order.

use std::sync::Arc;

use arrow::json::LineDelimitedWriter;
use jammi_ai::session::InferenceSession;
use jammi_ai::SearchMethod;
use jammi_db::config::JammiConfig;
use jammi_db::source::{FileFormat, SourceConnection, SourceType};
use jammi_db::store::CachePolicy;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut args = std::env::args().skip(1);
    let (Some(corpus), Some(model), Some(row_key)) = (args.next(), args.next(), args.next())
    else {
        return Err("usage: one_program <corpus-url> <model> <row-key>".into());
    };

    let session = Arc::new(InferenceSession::new(JammiConfig::load(None)?).await?);

    // 1. Register the source.
    let connection = SourceConnection::parse(&corpus, FileFormat::Parquet)?;
    session
        .add_source("corpus", SourceType::File, connection)
        .await?;

    // 2. Embed its `content` column, one vector per `id`.
    session
        .generate_text_embeddings(
            "corpus",
            &model,
            &["content".to_string()],
            "id",
            CachePolicy::Bypass,
            None,
        )
        .await?;

    // 3. Search: the rows nearest the vector stored for `row_key`.
    let hits = session
        .search_by_id("corpus", &row_key, 3, None, SearchMethod::default(), None)
        .await?
        .select(&["id".to_string(), "similarity".to_string()])?
        .run()
        .await?;

    let mut out = LineDelimitedWriter::new(std::io::stdout().lock());
    out.write_batches(&hits.iter().collect::<Vec<_>>())?;
    out.finish()?;
    Ok(())
}

It builds against the crates of this release: from crates.io in a fresh runtime, or from the workspace when the book renders in a checkout. The first build compiles the engine, so it takes minutes; a rerun takes seconds.

project = programs.rust_program(work, VERSION, "one_program")
rust_env = dict(os.environ, JAMMI_ARTIFACT_DIR=str(work / "rust"))
build = subprocess.run([programs.cargo(), "run", "-q", "--manifest-path",
                        str(project / "Cargo.toml"), "--", CORPUS, MODEL, ROW_KEY],
                       capture_output=True, text=True, env=rust_env)
assert build.returncode == 0, build.stderr[-4000:]
print(build.stdout)
rust_rows = rows(json.loads(line) for line in build.stdout.splitlines())
{"id":1,"retrieved_by":["vector"],"annotated_by":[],"similarity":1.0}
{"id":5,"retrieved_by":["vector"],"annotated_by":[],"similarity":0.97996515}
{"id":16,"retrieved_by":["vector"],"annotated_by":[],"similarity":0.9765265}

48.5 TypeScript

The TypeScript client speaks gRPC-web over fetch, so the same script runs in Node, a browser, or a Worker. It reads the search result, an Arrow IPC stream, with Apache Arrow’s JavaScript library.

print((programs.program("one_program") / "search.ts").read_text())
// The cookbook's one program through the TypeScript client: register a source,
// embed it, and search it over gRPC-web against a running server.
//
// Usage: `npx tsx search.ts <endpoint> <corpus-url> <model> <row-key>`. Prints
// the three rows nearest `<row-key>` as JSON lines, in rank order.

import { connect, FileFormat, Modality, SourceKind } from "@f-inverse/jammi-client";
import { tableFromIPC } from "apache-arrow";

const [endpoint, corpus, model, rowKey] = process.argv.slice(2);
const jammi = connect(endpoint);
const sourceId = "corpus_ts";

// 1. Register the source.
await jammi.catalog.addSource({
  sourceId,
  sourceKind: SourceKind.FILE,
  connection: { url: corpus, format: FileFormat.PARQUET },
});

// 2. Embed its `content` column, one vector per `id`.
await jammi.embedding.generateEmbeddings({
  sourceId,
  modelId: model,
  columns: ["content"],
  keyColumn: "id",
  modality: Modality.TEXT,
});

// 3. Search: the rows nearest the vector stored for `rowKey`. The result is an
// Arrow IPC stream (header + body), read with Apache Arrow's JS library.
const { result } = await jammi.embedding.search({
  sourceId,
  query: { case: "rowKey", value: rowKey },
  k: 3,
  select: ["id", "similarity"],
});
if (!result) throw new Error("search returned no result batch");
const ipc = new Uint8Array(result.dataHeader.length + result.dataBody.length);
ipc.set(result.dataHeader, 0);
ipc.set(result.dataBody, result.dataHeader.length);
for (const row of tableFromIPC(ipc)) {
  console.log(JSON.stringify({ id: Number(row.id), similarity: row.similarity }));
}
ts_project, ts_env = programs.ts_program(work, VERSION)
http = server.endpoint.replace("grpc://", "http://")
ts = subprocess.run([str(ts_project / "node_modules" / ".bin" / "tsx"), "search.ts",
                     http, CORPUS, MODEL, ROW_KEY],
                    cwd=ts_project, capture_output=True, text=True, env=ts_env)
assert ts.returncode == 0, ts.stderr[-4000:]
print(ts.stdout)
ts_rows = rows(json.loads(line) for line in ts.stdout.splitlines())
stack.close()
{"id":1,"similarity":1}
{"id":5,"similarity":0.9799651503562927}
{"id":16,"similarity":0.9765264987945557}

48.6 The same rows

surfaces = {"Python": python_rows, "CLI": cli_rows, "Rust": rust_rows,
            "TypeScript": ts_rows}
print(f"{'surface':<12}{'ranked (id, similarity)'}")
for name, ranked in surfaces.items():
    print(f"{name:<12}{ranked}")
agreeing = sum(ranked == python_rows for ranked in surfaces.values())
print(f"surfaces agreeing with Python: {agreeing} of {len(surfaces)}")
surface     ranked (id, similarity)
Python      [(1, 1.0), (5, 0.97997), (16, 0.97653)]
CLI         [(1, 1.0), (5, 0.97997), (16, 0.97653)]
Rust        [(1, 1.0), (5, 0.97997), (16, 0.97653)]
TypeScript  [(1, 1.0), (5, 0.97997), (16, 0.97653)]
surfaces agreeing with Python: 4 of 4
claim("every surface returns the same neighbours", agreeing == len(surfaces),
      f"{agreeing} of {len(surfaces)} surfaces")
✓ every surface returns the same neighbours (4 of 4 surfaces)

All four surfaces return the same three rows in the same order, with the same similarities: row 1 itself, then its two nearest neighbours. The program is the same three verbs in each language — register, embed, search — because every surface is a binding of the one jammi.v1 vocabulary, and the in-process engine behind the Rust program is the same engine behind the server.