Skip to main content

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 install @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:

string
libSQL database URL. Use ':memory:' for in-memory database, 'file:dbname.db' for local file, or a libSQL-compatible connection string like 'libsql://your-database.turso.io'.

authToken?:

string
Authentication token for Turso cloud databases

syncUrl?:

string
URL for database replication (Turso specific)

syncInterval?:

number
Interval in milliseconds for database sync (Turso specific)

方法
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:

string
Name of the index to create

dimension:

number
Vector dimension size (must match your embedding model)

metric?:

'cosine' | 'euclidean' | 'dotproduct'
= cosine
Distance metric for similarity search. Note: Currently only cosine similarity is supported by libSQL.

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:

string
Name of the index to insert into

vectors:

number[][]
Array of embedding vectors

metadata?:

Record<string, any>[]
Metadata for each vector

ids?:

string[]
Optional vector IDs (auto-generated if not provided)

query()
Direct link to query()

搜索具有可选元数据过滤的相似向量。

🌐 Searches for similar vectors with optional metadata filtering.

indexName:

string
Name of the index to search in

queryVector:

number[]
Query vector to find similar vectors for

topK?:

number
= 10
Number of results to return

filter?:

Filter
Metadata filters

includeVector?:

boolean
= false
Whether to include vector data in results

minScore?:

number
= 0
Minimum similarity score threshold

describeIndex()
Direct link to describeIndex()

获取有关索引的信息。

🌐 Gets information about an index.

indexName:

string
Name of the index to describe

返回:

🌐 Returns:

interface IndexStats {
dimension: number;
count: number;
metric: "cosine" | "euclidean" | "dotproduct";
}

deleteIndex()
Direct link to deleteIndex()

删除索引及其所有数据。

🌐 Deletes an index and all its data.

indexName:

string
Name of the index to delete

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:

string
Name of the index to truncate

updateVector()
Direct link to updateVector()

通过 ID 或元数据过滤器更新单个向量。必须提供 idfilter 中的一个,但不能同时提供两者。

🌐 Update a single vector by ID or by metadata filter. Either id or filter must be provided, but not both.

indexName:

string
Name of the index containing the vector

id?:

string
ID of the vector entry to update (mutually exclusive with filter)

filter?:

Record<string, any>
Metadata filter to identify vector(s) to update (mutually exclusive with id)

update:

object
Update data containing vector and/or metadata

update.vector?:

number[]
New vector data to update

update.metadata?:

Record<string, any>
New metadata to update

deleteVector()
Direct link to deleteVector()

通过其 ID 从索引中删除特定的向量条目。

🌐 Deletes a specific vector entry from an index by its ID.

indexName:

string
Name of the index containing the vector

id:

string
ID of the vector entry to delete

deleteVectors()
Direct link to deleteVectors()

通过 ID 或元数据过滤器删除多个向量。必须提供 idsfilter 中的一个,但不能同时提供两者。

🌐 Delete multiple vectors by IDs or by metadata filter. Either ids or filter must be provided, but not both.

indexName:

string
Name of the index containing the vectors to delete

ids?:

string[]
Array of vector IDs to delete (mutually exclusive with filter)

filter?:

Record<string, any>
Metadata filter to identify vectors to delete (mutually exclusive with ids)

响应类型
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 install @mastra/fastembed@latest

将以下内容添加到你的代理中:

🌐 Add the following to your agent:

src/mastra/agents/example-libsql-agent.ts
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
},
}),
});

🌐 Related