Implements Retrieval-Augmented Generation (RAG) patterns to enhance agents with custom knowledge bases.
Enables agents to search through custom content and knowledge bases to provide accurate, context-grounded responses. RAG combines LLM capabilities with semantic search.
Install and configure RAG in your convex.config.ts:
import { defineApp } from "convex/server";
import agent from "@convex-dev/agent/convex.config";
import rag from "@convex-dev/rag/convex.config";
const app = defineApp();
app.use(agent);
app.use(rag);
export default app;
Ingest documents into a namespace:
import { rag } from "@convex-dev/rag";
export const addContent = action({
args: { userId: v.string(), key: v.string(), text: v.string() },
handler: async (ctx, { userId, key, text }) => {
const namespace = `user:${userId}`;
await rag.addContent(ctx, components.rag, {
namespace,
key,
text,
filters: { filterNames: [filename] },
});
},
});
Use RAG with agents:
export const answerWithContext = action({
args: { threadId: v.string(), userId: v.string(), question: v.string() },
handler: async (ctx, { threadId, userId, question }) => {
const { thread } = await myAgent.continueThread(ctx, { threadId });
const context = await rag.search(ctx, components.rag, {
namespace: `user:${userId}`,
query: question,
limit: 10,
});
const augmentedPrompt = `# Context:\n\n${context.text}\n\n# Question:\n\n${question}`;
const result = await thread.generateText({ prompt: augmentedPrompt });
return result.text;
},
});
user:userId or team:teamId for multi-tenant safetyfilterNames to target specific documents