vectorize
Vector database for embeddings and semantic search at the edge. Load when building RAG pipelines, implementing semantic search, storing embeddings from Workers AI, finding similar documents, building recommendation systems, or querying vectors by similarity.
What this skill does
# Cloudflare Vectorize
Store and query high-dimensional vector embeddings at the edge for RAG (Retrieval Augmented Generation), semantic search, and similarity matching.
## FIRST: Create Index
```bash
# Create with preset (auto-configures dimensions and metric)
wrangler vectorize create my-index --preset @cf/baai/bge-base-en-v1.5
# Or create with explicit dimensions
wrangler vectorize create my-index --dimensions 768 --metric cosine
# List indexes
wrangler vectorize list
```
Add to `wrangler.jsonc`:
```jsonc
{
"vectorize": [
{ "binding": "SEARCH_INDEX", "index_name": "my-index" }
]
}
```
## When to Use
| Use Case | Description |
|----------|-------------|
| RAG Pipelines | Store document embeddings for context retrieval with LLMs |
| Semantic Search | Find similar content by meaning, not keywords |
| Recommendation Systems | Match users/items based on embedding similarity |
| Duplicate Detection | Find near-duplicate content using vector distance |
| Content Classification | Group similar items by vector clustering |
## Quick Reference
| Operation | API |
|-----------|-----|
| Insert vectors | `await env.INDEX.insert([{ id, values, metadata }])` |
| Query similar vectors | `await env.INDEX.query(vector, { topK: 5 })` |
| Upsert (insert or update) | `await env.INDEX.upsert([{ id, values, metadata }])` |
| Delete by IDs | `await env.INDEX.deleteByIds(["id1", "id2"])` |
| Get by IDs | `await env.INDEX.getByIds(["id1", "id2"])` |
## Basic RAG Example
```typescript
interface Env {
SEARCH_INDEX: Vectorize;
AI: Ai;
}
export default {
async fetch(req: Request, env: Env): Promise<Response> {
const url = new URL(req.url);
// Index documents with embeddings
if (url.pathname === "/index" && req.method === "POST") {
const { text, id } = await req.json<{ text: string; id: string }>();
// Generate embedding using Workers AI
const { data } = await env.AI.run("@cf/baai/bge-base-en-v1.5", {
text: [text],
});
const embedding = data[0];
// Insert into Vectorize
await env.SEARCH_INDEX.insert([{
id,
values: embedding,
metadata: { text }
}]);
return Response.json({ success: true, id });
}
// Search similar documents
if (url.pathname === "/search" && req.method === "POST") {
const { query } = await req.json<{ query: string }>();
// Generate query embedding
const { data } = await env.AI.run("@cf/baai/bge-base-en-v1.5", {
text: [query],
});
const queryEmbedding = data[0];
// Find similar vectors
const results = await env.SEARCH_INDEX.query(queryEmbedding, {
topK: 5,
returnMetadata: true
});
return Response.json({
matches: results.matches.map(match => ({
id: match.id,
score: match.score,
text: match.metadata?.text
}))
});
}
return new Response("Not found", { status: 404 });
}
};
```
## Configuration
### wrangler.jsonc
```jsonc
{
"name": "vectorize-demo",
"main": "src/index.ts",
"compatibility_date": "2026-01-01",
"compatibility_flags": ["nodejs_compat"],
// AI binding for generating embeddings
"ai": { "binding": "AI" },
// Vectorize binding
"vectorize": [
{
"binding": "SEARCH_INDEX",
"index_name": "my-index"
}
]
}
```
### Type Definitions
```typescript
interface Env {
SEARCH_INDEX: Vectorize;
AI: Ai;
}
// Vector insert/upsert format
interface VectorRecord {
id: string;
values: number[];
metadata?: Record<string, any>;
}
// Query result format
interface VectorQueryResult {
matches: Array<{
id: string;
score: number;
values?: number[];
metadata?: Record<string, any>;
}>;
count: number;
}
```
## Index Creation
### Using Presets
Presets automatically configure dimensions and distance metrics to match Workers AI embedding models:
```bash
# BGE Base English (768 dimensions, cosine)
wrangler vectorize create docs-index --preset @cf/baai/bge-base-en-v1.5
# BGE Large English (1024 dimensions, cosine)
wrangler vectorize create docs-index --preset @cf/baai/bge-large-en-v1.5
# BGE Small English (384 dimensions, cosine)
wrangler vectorize create docs-index --preset @cf/baai/bge-small-en-v1.5
```
### Manual Configuration
For custom embeddings or external models:
```bash
# Create with specific dimensions and metric
wrangler vectorize create custom-index \
--dimensions 1536 \
--metric cosine
# Available metrics: cosine, euclidean, dot-product
```
**Distance Metrics:**
| Metric | Use Case | Range |
|--------|----------|-------|
| `cosine` | Most common for text embeddings | -1 to 1 (1 = identical) |
| `euclidean` | Absolute distance in space | 0 to ∞ (0 = identical) |
| `dot-product` | When embeddings are normalized | -∞ to ∞ (higher = more similar) |
## Insert and Query Operations
### Insert Vectors
```typescript
// Insert single vector
await env.SEARCH_INDEX.insert([{
id: "doc-1",
values: [0.1, 0.2, 0.3, ...], // Must match index dimensions
metadata: {
title: "Getting Started",
category: "docs",
created: new Date().toISOString()
}
}]);
// Batch insert (more efficient)
const vectors = documents.map(doc => ({
id: doc.id,
values: doc.embedding,
metadata: { title: doc.title, url: doc.url }
}));
await env.SEARCH_INDEX.insert(vectors);
```
### Upsert Vectors
Use `upsert` to insert new vectors or update existing ones:
```typescript
await env.SEARCH_INDEX.upsert([{
id: "doc-1",
values: updatedEmbedding,
metadata: { title: "Updated Title" }
}]);
```
### Query for Similar Vectors
```typescript
// Basic query
const results = await env.SEARCH_INDEX.query(queryEmbedding, {
topK: 10,
returnMetadata: true,
returnValues: false // Set true to get vector values back
});
// Process results
for (const match of results.matches) {
console.log(`ID: ${match.id}`);
console.log(`Score: ${match.score}`);
console.log(`Metadata:`, match.metadata);
}
// Filter by metadata (optional)
const filtered = await env.SEARCH_INDEX.query(queryEmbedding, {
topK: 10,
returnMetadata: true,
filter: { category: "docs" } // Namespace filtering
});
```
### Delete Vectors
```typescript
// Delete by IDs
await env.SEARCH_INDEX.deleteByIds(["doc-1", "doc-2"]);
// Delete all with specific namespace (if using namespace metadata)
const allDocs = await env.SEARCH_INDEX.query(zeroVector, { topK: 10000 });
const idsToDelete = allDocs.matches
.filter(m => m.metadata?.namespace === "old")
.map(m => m.id);
await env.SEARCH_INDEX.deleteByIds(idsToDelete);
```
### Retrieve by IDs
```typescript
// Get specific vectors
const vectors = await env.SEARCH_INDEX.getByIds(["doc-1", "doc-2"]);
for (const vector of vectors) {
console.log(vector.id, vector.metadata);
}
```
## Integration with Workers AI
### Complete RAG Pipeline
```typescript
interface Env {
SEARCH_INDEX: Vectorize;
AI: Ai;
}
const EMBEDDING_MODEL = "@cf/baai/bge-base-en-v1.5";
const CHAT_MODEL = "@cf/meta/llama-3.1-8b-instruct";
export default {
async fetch(req: Request, env: Env): Promise<Response> {
const { question } = await req.json<{ question: string }>();
// 1. Generate embedding for user question
const { data: embeddings } = await env.AI.run(EMBEDDING_MODEL, {
text: [question],
});
const queryEmbedding = embeddings[0];
// 2. Search for relevant context
const results = await env.SEARCH_INDEX.query(queryEmbedding, {
topK: 3,
returnMetadata: true
});
// 3. Build context from results
const context = results.matches
.map(match => match.metadata?.text)
.join("\n\n");
// 4. Generate answer with RAG
const response = await env.AI.run(CHAT_MODEL, {
messages: [
{
role: "system",
content: `Answer the question using only the following context:\n\n${context}`
},Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.