Build Your First RAG Application
🎯 Introduction
You have learned how embeddings help find semantically related text and how RAG retrieves source material before generating an answer. This article puts those ideas together: use JavaScript to find the material most relevant to a question, then ask a large language model to answer using that material.
To make each step clear, we will use just three fixed passages without a vector database. By the end, you will have a minimal RAG question-answering program that runs in your terminal.
🛠 Set Up the Environment
Continue with the Node.js project from the AI SDK course. These examples use Node.js 24.x and openai@7.62.0. If the SDK is not installed yet, run:
npm install --save-exact openai@7.62.0
Configure your model service in .env at the project root:
AI_API_KEY=your_model_service_api_key
AI_BASE_URL=https://aihubmix.com/v1
AI_MODEL=gpt-4o-mini
AI_EMBEDDING_MODEL=text-embedding-3-small
AI_MODEL generates answers, and AI_EMBEDDING_MODEL generates vectors. Use the same embedding model for both documents and questions so their similarity can be compared.
📄 Step 1: Prepare Three Passages
Create 02.first-rag.mjs and add the SDK client and three sample store policies:
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.AI_API_KEY,
baseURL: process.env.AI_BASE_URL
});
const documents = [
{ id: "refund", text: "You can request a refund within 7 days of purchase." },
{ id: "delivery", text: "Standard orders ship within 48 hours of payment." },
{ id: "support", text: "Customer support is available daily from 9:00 to 18:00." }
];
Each passage has an id so we can identify the retrieved passage in the terminal. The original text is stored in an array; no database is needed yet.
🔢 Step 2: Generate Embeddings
Append embed() to the same file:
async function embed(text) {
const result = await client.embeddings.create({
model: process.env.AI_EMBEDDING_MODEL,
input: text
});
return result.data[0].embedding;
}
Calling embed("You can request a refund within 7 days of purchase.") returns a sequence of numbers. result.data[0].embedding is the vector for that passage. We will generate vectors for each of the three passages and for the user’s question.
We also need to compare two vectors. Add a function that calculates cosine similarity, as introduced in the embeddings lesson:
function cosineSimilarity(a, b) {
const dot = a.reduce((sum, value, i) => sum + value * b[i], 0);
const normA = Math.hypot(...a);
const normB = Math.hypot(...b);
return dot / (normA * normB);
}
cosineSimilarity(a, b) takes two vectors and returns a similarity score. We will not repeat the mathematics here. The key point is that we will rank the three passages by score and select the most relevant one.
🔍 Step 3: Retrieve Relevant Material
Continue appending to the file:
const question = "How many days after a purchase can I return it?";
const vectors = await Promise.all(documents.map(async (doc) => ({
...doc,
vector: await embed(doc.text)
})));
const queryVector = await embed(question);
const ranked = vectors
.map((doc) => ({
...doc,
score: cosineSimilarity(queryVector, doc.vector)
}))
.sort((a, b) => b.score - a.score);
const best = ranked[0];
console.log("Retrieval result:", best.id, best.score.toFixed(3));
This code performs three steps in order:
vectorsconverts each passage into a vector while retaining its original text andid.queryVectorconverts the question into a vector, which is then compared with each passage’s vector.rankedsorts the results by descending score;bestis the top-ranked passage.
We have not called a chat model to generate an answer yet; we have only found candidate material. For the refund question, we would normally expect best.id to be refund.
🤖 Step 4: Generate an Answer from the Material
Finally, append the model call:
const result = await client.chat.completions.create({
model: process.env.AI_MODEL,
messages: [
{
role: "system",
content: "Answer only using the provided material. If it is insufficient, clearly say you do not know."
},
{
role: "user",
content: `Material: ${best.text}\nQuestion: ${question}`
}
]
});
console.log("Answer:", result.choices[0].message.content);
The chat model call follows the pattern from the AI SDK course. The key change here is that the user message contains both the question and the retrieved best.text. The model can refer to the store’s refund policy instead of answering solely from its existing knowledge.
Run and Verify
Save the file and run this from the project root:
node --env-file=.env 02.first-rag.mjs
On success, you might see output like this (illustrative, not fixed output):
Retrieval result: refund 0.823
Answer: You can request a refund within 7 days of purchase.
Check two things: whether the retrieved id is refund, and whether the answer agrees with the policy allowing refund requests within 7 days. Similarity scores and answer wording vary by model.
What Are the Limitations of This Minimal Implementation?
The program always selects the passage with the highest similarity, whatever the question. If the user asks, “What is the customer support phone number?”, best still contains a result even though none of the three passages provides a phone number.
Therefore, ranking first does not mean the material can answer the question. We instructed the model to say it does not know when information is insufficient, but that instruction alone cannot guarantee a reliable answer. Later lessons cover how to assess whether retrieval results are relevant enough.
❓ Knowledge Check
Q: Why are document vectors regenerated on every run?
This minimal example stores data only in memory, so its computed vectors are lost when the program exits. Production knowledge bases usually persist document vectors to avoid reprocessing every document for each question.
🧪 Exercise
Change question to “What time does customer support close?”, rerun the program, and check whether it retrieves support and answers using the support hours.
Then change the question to “What is the customer support phone number?” Observe whether the program still returns a passage despite the missing phone number, and how the model responds.
Success criteria: Distinguish between retrieving the closest match and retrieving enough information to answer the question. Identify the code for embedding generation, similarity ranking, and answer generation.
🎉 Congratulations! You can now implement a minimal RAG application that retrieves relevant material using embeddings and asks a large language model to answer from that material.
