new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

AI SDK · Cookbook · all subjects

rag/retrieval

3 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Find relevant content using cosine similarity search

Example function to embed a user query, search for similar embeddings in the database, and return relevant content: import { cosineDistance, desc, gt, sql } from 'drizzle-orm'; import { embeddings } from '../db/schema/embeddings'; import { db } from '../db'; export const findRelevantContent = async (userQuery: string) => { const userQueryEmbedded = await generateEmbedding(userQuery); const similarity = sql<number>`1 - (${cosineDistance( embeddings.embedding, userQueryEmbedded, )})`; const similarGuides = await db .select({ name: embeddings.content, similarity }) .from(embeddings) .where(gt(similarity, 0.5)) .orderBy(t => desc(t.similarity)) .limit(4); return similarGuides; };

Cosine distance calculation with Drizzle ORM

Drizzle ORM provides cosineDistance function for calculating similarity between vectors in PostgreSQL with pgvector. The similarity value is calculated as 1 - cosineDistance(), where values closer to 1 indicate higher similarity. Results can be filtered with gt(similarity, 0.5) to get only relevant matches.

RAG retrieval with cosine similarity scoring

Retrieve relevant context by calculating cosine similarity between the query embedding and each chunk embedding using cosineSimilarity() from the AI SDK. Sort results by similarity in descending order and select the top-k results (commonly 3) to use as context for the generation step.

Give your agent this brain