libSQL 向量存储
🌐 libSQL Vector Store
libSQL 存储实现提供了一个兼容 SQLite 的向量搜索 libSQL,这是一个带有向量扩展的 SQLite 分支,以及带向量扩展的 Turso,提供了一种轻量且高效的向量数据库解决方案。它是 @mastra/libsql 包的一部分,并提供支持元数据过滤的高效向量相似性搜索。
🌐 The libSQL storage implementation provides a SQLite-compatible vector search libSQL, a fork of SQLite with vector extensions, and Turso with vector extensions, offering a lightweight and efficient vector database solution.
It's part of the @mastra/libsql package and offers efficient vector similarity search with metadata filtering.
安装Direct link to 安装
🌐 Installation
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/libsql@latest
pnpm add @mastra/libsql@latest
yarn add @mastra/libsql@latest
bun add @mastra/libsql@latest
用法Direct link to 用法
🌐 Usage
import { LibSQLVector } from "@mastra/libsql";
// Create a new vector store instance
const store = new LibSQLVector({
id: 'libsql-vector',
url: process.env.DATABASE_URL,
// Optional: for Turso cloud databases
authToken: process.env.DATABASE_AUTH_TOKEN,
});
// Create an index
await store.createIndex({
indexName: "myCollection",
dimension: 1536,
});
// Add vectors with metadata
const vectors = [[0.1, 0.2, ...], [0.3, 0.4, ...]];
const metadata = [
{ text: "first document", category: "A" },
{ text: "second document", category: "B" }
];
await store.upsert({
indexName: "myCollection",
vectors,
metadata,
});
// Query similar vectors
const queryVector = [0.1, 0.2, ...];
const results = await store.query({
indexName: "myCollection",
queryVector,
topK: 10, // top K results
filter: { category: "A" } // optional metadata filter
});
构造函数选项Direct link to 构造函数选项
🌐 Constructor Options
url:
authToken?:
syncUrl?:
syncInterval?:
方法Direct link to 方法
🌐 Methods
createIndex()Direct link to createIndex()
创建一个新的向量集合。索引名称必须以字母或下划线开头,并且只能包含字母、数字和下划线。维度必须是正整数。
🌐 Creates a new vector collection. The index name must start with a letter or underscore and can only contain letters, numbers, and underscores. The dimension must be a positive integer.
indexName:
dimension:
metric?:
upsert()Direct link to upsert()
在索引中添加或更新向量及其元数据。使用事务确保所有向量原子性插入——如果任何插入失败,整个操作将回滚。
🌐 Adds or updates vectors and their metadata in the index. Uses a transaction to ensure all vectors are inserted atomically - if any insert fails, the entire operation is rolled back.
indexName:
vectors:
metadata?:
ids?:
query()Direct link to query()
搜索具有可选元数据过滤的相似向量。
🌐 Searches for similar vectors with optional metadata filtering.
indexName:
queryVector:
topK?:
filter?:
includeVector?:
minScore?:
describeIndex()Direct link to describeIndex()
获取有关索引的信息。
🌐 Gets information about an index.
indexName:
返回:
🌐 Returns:
interface IndexStats {
dimension: number;
count: number;
metric: "cosine" | "euclidean" | "dotproduct";
}
deleteIndex()Direct link to deleteIndex()
删除索引及其所有数据。
🌐 Deletes an index and all its data.
indexName:
listIndexes()Direct link to listIndexes()
列出数据库中所有的向量索引。
🌐 Lists all vector indexes in the database.
返回:Promise<string[]>
🌐 Returns: Promise<string[]>
truncateIndex()Direct link to truncateIndex()
从索引中删除所有向量,同时保留索引结构。
🌐 Removes all vectors from an index while keeping the index structure.
indexName:
updateVector()Direct link to updateVector()
通过 ID 或元数据过滤器更新单个向量。必须提供 id 或 filter 中的一个,但不能同时提供两者。
🌐 Update a single vector by ID or by metadata filter. Either id or filter must be provided, but not both.
indexName:
id?:
filter?:
update:
update.vector?:
update.metadata?:
deleteVector()Direct link to deleteVector()
通过其 ID 从索引中删除特定的向量条目。
🌐 Deletes a specific vector entry from an index by its ID.
indexName:
id:
deleteVectors()Direct link to deleteVectors()
通过 ID 或元数据过滤器删除多个向量。必须提供 ids 或 filter 中的一个,但不能同时提供两者。
🌐 Delete multiple vectors by IDs or by metadata filter. Either ids or filter must be provided, but not both.
indexName:
ids?:
filter?:
响应类型Direct link to 响应类型
🌐 Response Types
查询结果以此格式返回:
🌐 Query results are returned in this format:
interface QueryResult {
id: string;
score: number;
metadata: Record<string, any>;
vector?: number[]; // Only included if includeVector is true
}
错误处理Direct link to 错误处理
🌐 Error Handling
针对不同的失败情况,存储会抛出特定的错误:
🌐 The store throws specific errors for different failure cases:
try {
await store.query({
indexName: "my-collection",
queryVector: queryVector,
});
} catch (error) {
// Handle specific error cases
if (error.message.includes("Invalid index name format")) {
console.error(
"Index name must start with a letter/underscore and contain only alphanumeric characters",
);
} else if (error.message.includes("Table not found")) {
console.error("The specified index does not exist");
} else {
console.error("Vector store error:", error.message);
}
}
常见错误情况包括:
🌐 Common error cases include:
- 索引名称格式无效
- 向量维度无效
- 未找到表格/索引
- 数据库连接问题
- 在 upsert 过程中交易失败
使用示例Direct link to 使用示例
🌐 Usage Example
使用 fastembed 的本地嵌入Direct link to 使用 fastembed 的本地嵌入
🌐 Local embeddings with fastembed
嵌入是由内存的 semanticRecall 用来按意义(而非关键词)检索相关信息的数字向量。这一设置使用 @mastra/fastembed 来生成向量嵌入。
🌐 Embeddings are numeric vectors used by memory's semanticRecall to retrieve related messages by meaning (not keywords). This setup uses @mastra/fastembed to generate vector embeddings.
安装 fastembed 以开始:
🌐 Install fastembed to get started:
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/fastembed@latest
pnpm add @mastra/fastembed@latest
yarn add @mastra/fastembed@latest
bun add @mastra/fastembed@latest
将以下内容添加到你的代理中:
🌐 Add the following to your agent:
import { Memory } from "@mastra/memory";
import { Agent } from "@mastra/core/agent";
import { LibSQLStore, LibSQLVector } from "@mastra/libsql";
import { fastembed } from "@mastra/fastembed";
export const libsqlAgent = new Agent({
id: "libsql-agent",
name: "libSQL Agent",
instructions:
"You are an AI agent with the ability to automatically recall memories from previous interactions.",
model: "openai/gpt-5.1",
memory: new Memory({
storage: new LibSQLStore({
id: 'libsql-agent-storage',
url: "file:libsql-agent.db",
}),
vector: new LibSQLVector({
id: 'libsql-agent-vector',
url: "file:libsql-agent.db",
}),
embedder: fastembed,
options: {
lastMessages: 10,
semanticRecall: {
topK: 3,
messageRange: 2,
},
generateTitle: true, // Explicitly enable automatic title generation
},
}),
});
相关Direct link to 相关
🌐 Related