Embeddings & Ingestion
Built-in embedding providers and helpers that turn documents into records, in both SDKs (version 1.4 and later).
Embedding providers
Every provider has the same three members: dimension, embedDocuments(texts) for what you store and embedQuery(text) for what you search with (embed_documents and embed_query in Python). An index keeps the vector size of its first insert, so use the same model and size for storing and searching.
| Provider | Class (TS and Python) | Credentials | Notes |
|---|---|---|---|
| OpenAI | OpenAIEmbeddings | OPENAI_API_KEY | text-embedding-3-small and -large, with a configurable output size. Sends large inputs in batches for you. |
| Cloudflare Workers AI | WorkersAIEmbeddings | CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_API_TOKEN | BGE models. Inside a Worker, use the env.AI binding (TypeScript); anywhere else, the Cloudflare REST API. |
| Voyage AI | VoyageEmbeddings | VOYAGE_API_KEY | General and domain models, including voyage-code-3 for code. Embeds documents and queries differently for better matches. |
OpenAI
Without dimensions, text-embedding-3-small returns 1,536 numbers and -large 3,072. Smaller sizes such as 768 search faster and cost less to store, with little loss in quality.
import { OpenAIEmbeddings } from "@swarmv/sdk";
// OPENAI_API_KEY from the environment, or pass { apiKey }.
const embedder = new OpenAIEmbeddings({ model: "text-embedding-3-small", dimensions: 768 });
const vectors = await embedder.embedDocuments(["first chunk", "second chunk"]); // for storing
const query = await embedder.embedQuery("what is in the first chunk?"); // for searchingfrom swarmv import OpenAIEmbeddings
embedder = OpenAIEmbeddings(model="text-embedding-3-small", dimensions=768)
vectors = embedder.embed_documents(["first chunk", "second chunk"])
query = embedder.embed_query("what is in the first chunk?")Cloudflare Workers AI
A good fit when your app already runs on Cloudflare: the embedding call stays inside Cloudflare's network. Sizes: bge-small 384, bge-base 768, bge-large 1,024.
import { WorkersAIEmbeddings } from "@swarmv/sdk";
// Inside a Cloudflare Worker: use the AI binding, no API token needed.
const embedder = new WorkersAIEmbeddings({ binding: env.AI, model: "@cf/baai/bge-base-en-v1.5" }); // 768 dimensions
// Anywhere else: the Cloudflare REST API.
// CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN from the environment, or pass { accountId, apiToken }.
const remote = new WorkersAIEmbeddings({ model: "@cf/baai/bge-small-en-v1.5" }); // 384 dimensionsfrom swarmv import WorkersAIEmbeddings # Calls the Cloudflare REST API. CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN from the # environment, or pass account_id= and api_token=. embedder = WorkersAIEmbeddings(model="@cf/baai/bge-base-en-v1.5") # 768 dimensions
Voyage AI
Default model voyage-3 (1,024). outputDimension picks a smaller or larger size on models that support it (256 to 2,048), and long inputs are truncated unless you set truncation: false.
import { VoyageEmbeddings } from "@swarmv/sdk";
// VOYAGE_API_KEY from the environment, or pass { apiKey }.
const embedder = new VoyageEmbeddings({ model: "voyage-code-3", outputDimension: 1024 });
// embedDocuments sends input_type "document" and embedQuery sends "query", so a question
// in plain English lands near the code that answers it.
const vectors = await embedder.embedDocuments(sourceFiles.map((f) => f.text));
const query = await embedder.embedQuery("where do we validate API keys?");from swarmv import VoyageEmbeddings embedder = VoyageEmbeddings(model="voyage-code-3", output_dimension=1024)
Your own model
import type { EmbeddingProvider } from "@swarmv/sdk";
// Any model works: implement these three members and pass it wherever a provider is accepted.
class MyEmbeddings implements EmbeddingProvider {
readonly dimension = 768;
async embedDocuments(texts: string[]) { return myModel.embed(texts); }
async embedQuery(text: string) { return (await myModel.embed([text]))[0]; }
}Document chunks
embedDocumentChunks embeds a document's chunks and returns records ready for insertMany, with the same metadata fields every time. Each chunk's text is kept in its metadata when it's under about 7 KB, so search results can be passed straight to your LLM. Splitting the document into chunks is up to you or your framework.
import { SwarmV, OpenAIEmbeddings, embedDocumentChunks } from "@swarmv/sdk";
const swarmv = new SwarmV(); // SWARMV_API_KEY from the environment
const embedder = new OpenAIEmbeddings({ dimensions: 768 });
const records = await embedDocumentChunks({
embedder,
documentId: "handbook.md",
containerId: "container:handbook", // who can see it is decided by this container
chunks: ["Employees get 25 days of paid leave.", "Remote work stipends cover home office equipment."],
source: "https://wiki.example.com/handbook",
category: "hr",
startId: 10_000, // this document uses IDs 10000-10001; see "Choosing IDs"
});
await swarmv.insertMany(records);
// Each record's metadata: container_id, document_id, chunk_index, updated_at, source, category, textfrom swarmv import SwarmV, OpenAIEmbeddings, embed_document_chunks
swarmv = SwarmV()
embedder = OpenAIEmbeddings(dimensions=768)
records = embed_document_chunks(
embedder,
"handbook.md",
"container:handbook",
["Employees get 25 days of paid leave.", "Remote work stipends cover home office equipment."],
source="https://wiki.example.com/handbook",
category="hr",
start_id=10_000,
)
swarmv.insert_many(records)import { createDocumentChunks } from "@swarmv/sdk";
// Already have vectors (from LangChain, LlamaIndex, your own model)? Build the same records without embedding.
const records = createDocumentChunks({ documentId: "faq.md", containerId: "container:support", chunks: texts, vectors, startId: 20_000 });Choosing IDs
Record IDs are 32-bit numbers. Without startId, each chunk's ID is a hash of the document ID and chunk number. That's convenient: re-ingesting a document overwrites its old chunks instead of duplicating them. But two different chunks can end up with the same hash, and the chance grows with the index (roughly even odds by about 77,000 chunks). The newer chunk then replaces the older one, or the insert is refused if the two are in different containers. For anything beyond a small collection, give each document its own range with startId, for example from a counter in your database, and remember the range so you can update or delete that document later.
Semantic cache with a provider
Providers can be passed to SemanticCache directly. See Semantic Caching for how the cache works.
import { SwarmV, SemanticCache, OpenAIEmbeddings } from "@swarmv/sdk";
// Any provider can be passed straight to SemanticCache; it uses embedQuery for prompts.
const cache = new SemanticCache(new SwarmV(), new OpenAIEmbeddings({ dimensions: 768 }), 0.95);
const answer = await cache.call("How do I reset my password?", callMyLlm);from swarmv import SwarmV, SemanticCache, OpenAIEmbeddings
cache = SemanticCache(SwarmV(), OpenAIEmbeddings(dimensions=768), threshold=0.95)
answer = cache.call("How do I reset my password?", call_my_llm)Recipes
Multi-tenant RAG
Ingest documents per team and answer each user only from what they can see. TypeScript and Python.
Code search
Index source files with voyage-code-3 and find code from plain-English questions.
Assistant memory
Save and recall what each user tells your assistant, one private container per user.
Framework integrations (LangChain, LlamaIndex, Vercel AI SDK, Gemini, Databricks) are on the MCP & AI Agents, Multi-Agent State and Real-Time RAG pages.