Docs/Recipes

Search your own content (RAG)

Answer from the user's notes or documents: embed them once, find the closest passages, then ask.

Retrieval has two steps. When the user adds content, turn each passage into a vector with charge.ai.embed() and keep the vectors. When they ask something, embed the question, pick the passages whose vectors are closest, and pass those to charge.ai.chat().

search-notes.js
// 1. Once, when the user adds their notes: split them, embed the passages, keep the vectors.
const passages = notes.split(/\n\s*\n/).filter((p) => p.trim())
const { vectors } = await charge.ai.embed(passages)
const index = passages.map((text, i) => ({ text, vector: vectors[i] }))

// 2. Each question: embed it, take the closest passages, answer from them.
const cosine = (a, b) => {
  let dot = 0, na = 0, nb = 0
  for (let i = 0; i < a.length; i++) { dot += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i] }
  return dot / Math.sqrt(na * nb)
}

async function ask(question) {
  const { vectors: [q] } = await charge.ai.embed(question)
  const top = index
    .map((p) => ({ ...p, score: cosine(q, p.vector) }))
    .sort((a, b) => b.score - a.score)
    .slice(0, 4)
  const reply = await charge.ai.chat([
    { role: 'system', content: 'Answer only from these passages. If they don't say, say so.\n\n' + top.map((p) => p.text).join('\n---\n') },
    { role: 'user', content: question },
  ])
  return reply.text
}
  • charge.ai.embed(texts, { model?, dimensions? }) takes a string or up to 2,048 strings and returns { vectors, inputTokens, costPaise }, one vector per text, in order.
  • The user pays per input token, held up front and settled like a reply, and far less than a reply. Embed content once and keep the vectors (IndexedDB, or your own database); only the question is embedded per search.
  • Embed passages and questions with the same model, so their vectors compare. dimensions makes vectors shorter where the model allows it, which saves storage.
  • Keep passages to a few paragraphs each. Very long passages are cut at the model's limit.

With the OpenAI SDK

POST /v1/embeddings speaks OpenAI's embeddings API, so with the client from Keep your AI code it is one call. model is embedding for the default, or an embedding model's id from /v1/models.

openai-sdk.js
const res = await ai.embeddings.create({ model: 'embedding', input: passages })
const vectors = res.data.map((d) => d.embedding)

Read next

Still stuck? Talk to us and we'll help.