48One 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 contextlibimport importlib.metadataimport jsonimport osimport subprocessimport tempfilefrom pathlib import Pathimport jammifrom jammi.testing import LiveServerfrom jammi_cookbook import fixtures, programsfrom jammi_cookbook.claims import claimVERSION = 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.
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.
//! 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())
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.
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.