ExamplesRAGInsert Embedding in Chroma

Insert Embedding in Chroma

After generating embeddings, you need to store them in a vector database for similarity search. The ChromaVector class provides methods to create collections and insert embeddings into Chroma, an open-source embedding database. This example shows how to store embeddings in Chroma for later retrieval.

import { openai } from '@ai-sdk/openai';
import { ChromaVector } from '@mastra/chroma';
import { MDocument } from '@mastra/rag';
import { embedMany } from 'ai';
 
const doc = MDocument.fromText('Your text content...');
 
const chunks = await doc.chunk();
 
const { embeddings } = await embedMany({
  values: chunks.map(chunk => chunk.text),
  model: openai.embedding('text-embedding-3-small'),
});
 
const chroma = new ChromaVector({
  path: "path/to/chroma/db",
});
 
await chroma.createIndex({
  indexName: 'test_collection',
  dimension: 1536,
});
 
// Store both metadata and original documents in Chroma
await chroma.upsert({
  indexName: 'test_collection',
  vectors: embeddings,
  metadata: chunks.map(chunk => ({ text: chunk.text })), // metadata
  documents: chunks.map(chunk => chunk.text), // store original documents
});





View Example on GitHub