AI agent framework for Convex with threads, messages, streaming, RAG, workflows, and tool calls. Manages long-running agentic workflows with real-time reactivity and multi-agent cooperation.
Integrate the Convex Agent Component (@convex-dev/agent v0.3.2+) into applications requiring AI agent capabilities with persistent threads, real-time streaming, and multi-agent workflows.
This skill helps you implement AI agents using the Convex Agent Component. It provides guidance on setting up agents with LLM integration, managing conversation threads, implementing tool calls, enabling RAG techniques, and building complex multi-step workflows. The component separates long-running agentic workflows from UI while maintaining full reactivity.
Install the Convex Agent Component:
```bash
npm install @convex-dev/agent
```
Initialize Convex if not already set up:
```bash
npx convex dev
```
Create agents with specific prompts, models, and behaviors:
```typescript
import { Agent } from "@convex-dev/agent";
// Define an agent with specific capabilities
const customerSupportAgent = new Agent({
name: "CustomerSupport",
model: "gpt-4",
prompt: "You are a helpful customer support agent...",
tools: [searchKnowledgeBase, createTicket],
});
```
Implement persistent conversation threads:
```typescript
// Create a new thread
const threadId = await createThread({
participants: [userId, agentId],
metadata: { topic: "product-inquiry" }
});
// Add messages to thread
await addMessage(threadId, {
role: "user",
content: "How do I reset my password?"
});
```
Enable real-time streaming over WebSockets:
```typescript
// Stream agent responses with deltas
const stream = await agent.streamResponse(threadId);
for await (const delta of stream) {
// Send delta to client via WebSocket
// All clients stay in sync automatically
}
```
Define and register tools that agents can use:
```typescript
const tools = [
{
name: "searchKnowledgeBase",
description: "Search the knowledge base for relevant articles",
parameters: {
query: { type: "string", required: true }
},
handler: async ({ query }) => {
// Implementation
return results;
}
}
];
```
Configure automatic context inclusion with hybrid search:
```typescript
// Enable automatic context from thread history
const agent = new Agent({
contextSettings: {
includeThreadHistory: true,
vectorSearch: true,
textSearch: true,
maxMessages: 20,
includeOtherThreads: true, // Search user's other threads
}
});
```
Integrate with RAG Component for external sources:
```typescript
import { RAG } from "@convex-dev/rag";
// Augment prompts with retrieved context
const relevantDocs = await rag.search(userQuery);
const augmentedPrompt = `${basePrompt}\n\nContext: ${relevantDocs}`;
```
Build workflows that coordinate multiple agents:
```typescript
// Define workflow with multiple steps
const workflow = {
steps: [
{ agent: researchAgent, task: "gather-info" },
{ agent: analysisAgent, task: "analyze-data" },
{ agent: summaryAgent, task: "create-summary" }
]
};
// Execute workflow durably
await executeWorkflow(workflow, threadId);
```
Support files in thread history:
```typescript
// Add message with file attachment
await addMessage(threadId, {
role: "user",
content: "Please analyze this document",
files: [{
storageId: fileStorageId,
filename: "report.pdf",
contentType: "application/pdf"
}]
});
// Files automatically saved to Convex file storage
// Ref-counting handles cleanup
```
Integrate human agents into workflows:
```typescript
// Route to human agent when needed
if (requiresHumanReview) {
await escalateToHuman(threadId, {
reason: "complex-issue",
priority: "high"
});
}
```
Set up callbacks for debugging:
```typescript
const agent = new Agent({
callbacks: {
onToolCall: (tool, args) => {
console.log(`Tool called: ${tool}`, args);
},
onCompletion: (response) => {
console.log("Response:", response);
},
onError: (error) => {
console.error("Agent error:", error);
}
}
});
```
Use the agent playground for testing and iteration:
Track usage per provider, model, user, and agent:
```typescript
// Configure usage tracking
await trackUsage({
userId,
agentId,
provider: "openai",
model: "gpt-4",
tokens: {
prompt: 150,
completion: 300,
total: 450
},
cost: 0.0135
});
// Query usage for billing
const userUsage = await getUserUsage(userId, dateRange);
```
Implement rate limiting with the Rate Limiter Component:
```typescript
import { RateLimiter } from "@convex-dev/rate-limiter";
// Limit user interactions with agents
const rateLimiter = new RateLimiter({
key: `agent-calls:${userId}`,
limit: 100,
window: "1h"
});
if (!await rateLimiter.check()) {
throw new Error("Rate limit exceeded");
}
```
1. **Agents**: Define agents with specific models, prompts, and tool access
2. **Threads**: Create persistent conversation threads with multi-participant support
3. **Streaming**: Enable real-time WebSocket streaming with deltas
4. **Context**: Automatic conversation context with hybrid vector/text search
5. **RAG**: Prompt augmentation from external sources via tool calls
6. **Workflows**: Multi-step operations spanning agents and users
7. **Files**: File attachment support with automatic storage management
8. **Debugging**: Callbacks, playground inspection, and dashboard monitoring
9. **Usage Tracking**: Granular tracking for billing and analytics
10. **Rate Limiting**: Control interaction rates per user/agent
```bash
git clone https://github.com/get-convex/agent.git
cd agent
npm run setup
npm run dev
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/convex-agent-component/raw