Skip to content

Repository files navigation

technicalwriting.dev

The source code for technicalwriting.dev.

// 1. Check if the API is available
if (!SemanticEmbedder || (await SemanticEmbedder.availability()) !== "available") {
  console.error("Semantic Embedder API is not available on this device.");
}

// 2. Create the embedder instance with a download monitor
const semanticEmbedder = await SemanticEmbedder.create({
  monitor(m) {
    m.addEventListener('downloadprogress', (e) => {
      console.log(`Downloaded ${e.loaded * 100}%`);
    });
  },
});

// 3. Embed a single string
const result1 = await semanticEmbedder.embed("The quick brown fox jumps over the lazy dog.", { taskType: "semantic-similarity" });
const vector1 = result1.embeddings[0].values;
console.log("Embedding for string 1:", vector1);

// 4. Embed a batch of strings
const passages = [
  "Built-in AI APIs use on-device models.",
  "Embeddings are high-dimensional vectors representing semantic meaning.",
];
const batchResult = await semanticEmbedder.embed(passages);
batchResult.embeddings.forEach((emb, i) => {
  console.log(`Embedding for passage ${i}:`, emb.values);
});

// 5. Compare similarity (Example utility function)
function cosineSimilarity(vecA, vecB) {
  if (!vecA || !vecB || vecA.length !== vecB.length) return 0;
  let dotProduct = 0, normA = 0, normB = 0;
  for (let i = 0; i < vecA.length; i++) {
    dotProduct += vecA[i] * vecB[i];
    normA += vecA[i] * vecA[i];
    normB += vecB[i] * vecB[i];
  }
  if (normA === 0 || normB === 0) return 0;
  return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
}

const result2 = await semanticEmbedder.embed("A fast, dark-colored fox leaps over a resting hound.", { taskType: "semantic-similarity" });
const vector2 = result2.embeddings[0].values;
const similarity = cosineSimilarity(vector1, vector2);
console.log(`Similarity score between string 1 and 2: ${similarity}`);

// 6. Proactively release resources
semanticEmbedder.destroy();

About

Source code for https://technicalwriting.dev

Resources

Stars

14 stars

Watchers

1 watching

Forks

Used by

Contributors

Languages