Embeddings

rw.embed()

Generate vector embeddings for text. Input can be a single string or an array of strings.

Signature

TypeScript
rw.embed(model: string, input: string | string[], options?: EmbeddingOptions): Promise<EmbeddingResponse>

Parameters

ParameterTypeDescription
model
required
stringEmbedding model slug, e.g. "text-embedding-3-small", "text-embedding-3-large"
input
required
string | string[]Single text or array of texts to embed.
options.encoding_formatstringOutput encoding format, e.g. "float" or "base64".

Response

TypeScript
interface EmbeddingResponse {
  object: "list";
  data: {
    object: "embedding";
    embedding: number[];
    index: number;
  }[];
  model: string;
  usage: {
    prompt_tokens: number;
    total_tokens: number;
  };
}

Examples

Single text embedding

TypeScript
const res = await rw.embed("text-embedding-3-small", "Hello world");
console.log(res.data[0].embedding.length); // 1536 dimensions

Batch embedding

TypeScript
const res = await rw.embed("text-embedding-3-small", [
  "How do I reset my password?",
  "I forgot my login credentials",
  "What are your pricing plans?",
]);

for (const item of res.data) {
  console.log(`Index ${item.index}: ${item.embedding.length} dimensions`);
}

Cosine similarity search

TypeScript
function cosineSimilarity(a: number[], b: number[]): number {
  let dot = 0, normA = 0, normB = 0;
  for (let i = 0; i < a.length; i++) {
    dot += a[i] * b[i];
    normA += a[i] * a[i];
    normB += b[i] * b[i];
  }
  return dot / (Math.sqrt(normA) * Math.sqrt(normB));
}

const docs = ["JavaScript tutorial", "Python guide", "Cooking recipes"];
const query = "How to learn programming";

const docsRes = await rw.embed("text-embedding-3-small", docs);
const queryRes = await rw.embed("text-embedding-3-small", query);

const queryVec = queryRes.data[0].embedding;
const scores = docsRes.data.map((d, i) => ({
  doc: docs[i],
  score: cosineSimilarity(queryVec, d.embedding),
}));

scores.sort((a, b) => b.score - a.score);
console.log(scores[0]); // { doc: "JavaScript tutorial", score: 0.87 }

Supported embedding models

text-embedding-3-small (1536d), text-embedding-3-large (3072d), text-embedding-ada-002, Nomic Embed, BGE Large, and more.