convex-agents
Convex Agents provides a framework for building stateful AI agents on the Convex backend, managing conversation threads, integrating tools as executable functions, streaming responses in real time, and orchestrating retrieval-augmented generation patterns. Use this when building multi-turn conversational applications requiring persistent conversation history, reliable tool execution, and durable long-running workflows that survive application restarts.
git clone --depth 1 https://github.com/waynesutton/convexskills /tmp/convex-agents && cp -r /tmp/convex-agents/skills/convex-agents ~/.claude/skills/convex-agentsSKILL.md
# Convex Agents
Build persistent, stateful AI agents with Convex including thread management, tool integration, streaming responses, RAG patterns, and workflow orchestration.
## Documentation Sources
Before implementing, do not assume; fetch the latest documentation:
- Primary: https://docs.convex.dev/ai
- Convex Agent Component: https://www.npmjs.com/package/@convex-dev/agent
- For broader context: https://docs.convex.dev/llms.txt
## Instructions
### Why Convex for AI Agents
- **Persistent State** - Conversation history survives restarts
- **Real-time Updates** - Stream responses to clients automatically
- **Tool Execution** - Run Convex functions as agent tools
- **Durable Workflows** - Long-running agent tasks with reliability
- **Built-in RAG** - Vector search for knowledge retrieval
### Setting Up Convex Agent
```bash
npm install @convex-dev/agent ai openai
```
```typescript
// convex/agent.ts
import { Agent } from "@convex-dev/agent";
import { components } from "./_generated/api";
import { OpenAI } from "openai";
const openai = new OpenAI();
export const agent = new Agent(components.agent, {
chat: openai.chat,
textEmbedding: openai.embeddings,
});
```
### Thread Management
```typescript
// convex/threads.ts
import { mutation, query } from "./_generated/server";
import { v } from "convex/values";
import { agent } from "./agent";
// Create a new conversation thread
export const createThread = mutation({
args: {
userId: v.id("users"),
title: v.optional(v.string()),
},
returns: v.id("threads"),
handler: async (ctx, args) => {
const threadId = await agent.createThread(ctx, {
userId: args.userId,
metadata: {
title: args.title ?? "New Conversation",
createdAt: Date.now(),
},
});
return threadId;
},
});
// List user's threads
export const listThreads = query({
args: { userId: v.id("users") },
returns: v.array(v.object({
_id: v.id("threads"),
title: v.string(),
lastMessageAt: v.optional(v.number()),
})),
handler: async (ctx, args) => {
return await agent.listThreads(ctx, {
userId: args.userId,
});
},
});
// Get thread messages
export const getMessages = query({
args: { threadId: v.id("threads") },
returns: v.array(v.object({
role: v.string(),
content: v.string(),
createdAt: v.number(),
})),
handler: async (ctx, args) => {
return await agent.getMessages(ctx, {
threadId: args.threadId,
});
},
});
```
### Sending Messages and Streaming Responses
```typescript
// convex/chat.ts
import { action } from "./_generated/server";
import { v } from "convex/values";
import { agent } from "./agent";
import { internal } from "./_generated/api";
export const sendMessage = action({
args: {
threadId: v.id("threads"),
message: v.string(),
},
returns: v.null(),
handler: async (ctx, args) => {
// Add user message to thread
await ctx.runMutation(internal.chat.addUserMessage, {
threadId: args.threadId,
content: args.message,
});
// Generate AI response with streaming
const response = await agent.chat(ctx, {
threadId: args.threadId,
messages: [{ role: "user", content: args.message }],
stream: true,
onToken: async (token) => {
// Stream tokens to client via mutation
await ctx.runMutation(internal.chat.appendToken, {
threadId: args.threadId,
token,
});
},
});
// Save complete response
await ctx.runMutation(internal.chat.saveResponse, {
threadId: args.threadId,
content: response.content,
});
return null;
},
});
```
### Tool Integration
Define tools that agents can use:
```typescript
// convex/tools.ts
import { tool } from "@convex-dev/agent";
import { v } from "convex/values";
import { api } from "./_generated/api";
// Tool to search knowledge base
export const searchKnowledge = tool({
name: "search_knowledge",
description: "Search the knowledge base for relevant information",
parameters: v.object({
query: v.string(),
limit: v.optional(v.number()),
}),
handler: async (ctx, args) => {
const results = await ctx.runQuery(api.knowledge.search, {
query: args.query,
limit: args.limit ?? 5,
});
return results;
},
});
// Tool to create a task
export const createTask = tool({
name: "create_task",
description: "Create a new task for the user",
parameters: v.object({
title: v.string(),
description: v.optional(v.string()),
dueDate: v.optional(v.string()),
}),
handler: async (ctx, args) => {
const taskId = await ctx.runMutation(api.tasks.create, {
title: args.title,
description: args.description,
dueDate: args.dueDate ? new Date(args.dueDate).getTime() : undefined,
});
return { success: true, taskId };
},
});
// Tool to get weather
export const getWeather = tool({
name: "get_weather",
description: "Get current weather for a location",
parameters: v.object({
location: v.string(),
}),
handler: async (ctx, args) => {
const response = await fetch(
`https://api.weather.com/current?location=${encodeURIComponent(args.location)}`
);
return await response.json();
},
});
```
### Agent with Tools
```typescript
// convex/assistant.ts
import { action } from "./_generated/server";
import { v } from "convex/values";
import { agent } from "./agent";
import { searchKnowledge, createTask, getWeather } from "./tools";
export const chat = action({
args: {
threadId: v.id("threads"),
message: v.string(),
},
returns: v.string(),
handler: async (ctx, args) => {
const response = await agent.chat(ctx, {
threadId: args.threadId,
messages: [{ role: "user", content: args.message }],
tools: [searchKnowledge, createTask, getWeather],
systemPrompt: `You are a helpful assistant. You have access to tools to:
- Search the knowledge base for informationPrevent feature creep when building software, apps, and AI-powered products. Use this skill when planning features, reviewing scope, building MVPs, managing backlogs, or when a user says "just one more feature." Helps developers and AI agents stay focused, ship faster, and avoid bloated products.
Guidelines for building production-ready Convex apps covering function organization, query patterns, validation, TypeScript usage, error handling, and the Zen of Convex design philosophy
How to create, structure, and publish self-contained Convex components with proper isolation, exports, and dependency management
Scheduled function patterns for background tasks including interval scheduling, cron expressions, job monitoring, retry strategies, and best practices for long-running tasks
Complete file handling including upload flows, serving files via URL, storing generated files from actions, deletion, and accessing file metadata from system tables
Writing queries, mutations, actions, and HTTP actions with proper argument validation, error handling, internal functions, and runtime considerations
External API integration and webhook handling including HTTP endpoint routing, request/response handling, authentication, CORS configuration, and webhook signature validation
Schema migration strategies for evolving applications including adding new fields, backfilling data, removing deprecated fields, index migrations, and zero-downtime migration patterns