Customizes what information the LLM receives for each generation. Use this to control message history, implement RAG context injection, search across threads, and provide custom context.
By default, the Agent includes recent messages as context. This skill covers customizing that behavior for advanced patterns like cross-thread search, memory injection, summarization, and filtering.
const myAgent = new Agent(components.agent, {
name: "My Agent",
languageModel: openai.chat("gpt-4o-mini"),
contextOptions: {
recentMessages: 50,
excludeToolMessages: true,
searchOptions: {
limit: 10,
textSearch: true,
vectorSearch: false,
},
},
});
export const generateWithCustomContext = action({
args: { threadId: v.string(), prompt: v.string() },
handler: async (ctx, { threadId, prompt }) => {
const result = await myAgent.generateText(
ctx,
{ threadId },
{ prompt },
{
contextOptions: {
recentMessages: 20,
searchOptions: {
limit: 5,
textSearch: true,
vectorSearch: true,
},
},
}
);
return result.text;
},
});
export const generateWithCrossThreadContext = action({
args: { threadId: v.string(), userId: v.string(), prompt: v.string() },
handler: async (ctx, { threadId, userId, prompt }) => {
const result = await myAgent.generateText(
ctx,
{ threadId, userId },
{ prompt },
{
contextOptions: {
searchOtherThreads: true,
searchOptions: {
limit: 15,
textSearch: true,
vectorSearch: true,
},
},
}
);
return result.text;
},
});
Completely customize context:
const myAgent = new Agent(components.agent, {
name: "My Agent",
languageModel: openai.chat("gpt-4o-mini"),
contextHandler: async (ctx, args) => {
const userMemories = await getUserMemories(ctx, args.userId);
const examples = getExamples();
return [
...userMemories,
...examples,
...args.search,
...args.recent,
...args.inputMessages,
];
},
});
Get context without calling LLM:
import { fetchContextWithPrompt } from "@convex-dev/agent";
export const getContextForPrompt = action({
args: { threadId: v.string(), prompt: v.string() },
handler: async (ctx, { threadId, prompt }) => {
const { messages } = await fetchContextWithPrompt(ctx, components.agent, {
threadId,
prompt,
contextOptions: {
recentMessages: 20,
searchOptions: { limit: 10, textSearch: true },
},
});
return messages;
},
});