跳至主要內容

libSQL 向量儲存

libSQL 儲存實作透過與 SQLite 相容、具向量擴充功能的 SQLite 分支 libSQL,以及具向量擴充功能的 Turso 提供向量搜尋,是輕量且高效的向量資料庫解決方案。 它是 @mastra/libsql 套件的一部分,可搭配中繼資料篩選進行高效率的向量相似度搜尋。

安裝
「安裝」的直接連結

npm install @mastra/libsql@latest

使用方式
「使用方式」的直接連結

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
});

建構函式選項
「建構函式選項」的直接連結

url:

string
libSQL 資料庫 URL。使用 ':memory:' 代表記憶體內資料庫、'file:dbname.db' 代表本機檔案,或使用 'libsql://your-database.turso.io' 之類與 libSQL 相容的連線字串。

authToken?:

string
Turso 雲端資料庫的驗證權杖

syncUrl?:

string
資料庫複寫 URL(Turso 專用)

syncInterval?:

number
資料庫同步間隔,單位為毫秒(Turso 專用)

方法
「方法」的直接連結

createIndex()
「createindex」的直接連結

建立新的向量集合。索引名稱必須以字母或底線開頭,且只能包含字母、數字和底線字元。維度必須是正整數。

indexName:

string
要建立的索引名稱

dimension:

number
向量維度大小(必須與嵌入模型相符)

metric?:

'cosine' | 'euclidean' | 'dotproduct'
= cosine
相似度搜尋使用的距離度量。注意:libSQL 目前僅支援餘弦相似度。

upsert()
「upsert」的直接連結

在索引中新增或更新向量及其中繼資料。此方法使用交易確保所有向量以不可分割的方式插入;若任一插入失敗,整個操作都會回復。

indexName:

string
要插入資料的索引名稱

vectors:

number[][]
嵌入向量陣列

metadata?:

Record<string, any>[]
每個向量的中繼資料

ids?:

string[]
選用的向量 ID(未提供時會自動產生)

query()
「query」的直接連結

搜尋相似向量,並可選擇套用中繼資料篩選。

indexName:

string
要搜尋的索引名稱

queryVector:

number[]
用於尋找相似向量的查詢向量

topK?:

number
= 10
要傳回的結果數量

filter?:

Filter
中繼資料篩選條件

includeVector?:

boolean
= false
結果是否包含向量資料

minScore?:

number
= 0
最低相似度分數門檻

describeIndex()
「describeindex」的直接連結

取得索引的相關資訊。

indexName:

string
要描述的索引名稱

傳回:

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

deleteIndex()
「deleteindex」的直接連結

刪除索引及其中所有資料。

indexName:

string
要刪除的索引名稱

listIndexes()
「listindexes」的直接連結

列出資料庫中的所有向量索引。

傳回:Promise<string[]>

truncateIndex()
「truncateindex」的直接連結

移除索引中的所有向量,但保留索引結構。

indexName:

string
要清空的索引名稱

updateVector()
「updatevector」的直接連結

依 ID 或中繼資料篩選條件更新單一向量。必須提供 idfilter 其中一項,但不能同時提供兩者。

indexName:

string
包含該向量的索引名稱

id?:

string
要更新的向量項目 ID(不可與 filter 同時使用)

filter?:

Record<string, any>
用於識別待更新向量的中繼資料篩選條件(不可與 id 同時使用)

update:

object
包含向量及/或中繼資料的更新資料

update.vector?:

number[]
要更新的新向量資料

update.metadata?:

Record<string, any>
要更新的新中繼資料

deleteVector()
「deletevector」的直接連結

依 ID 從索引中刪除指定的向量項目。

indexName:

string
包含該向量的索引名稱

id:

string
要刪除的向量項目 ID

deleteVectors()
「deletevectors」的直接連結

依 ID 或中繼資料篩選條件刪除多個向量。必須提供 idsfilter 其中一項,但不能同時提供兩者。

indexName:

string
包含待刪除向量的索引名稱

ids?:

string[]
要刪除的向量 ID 陣列(不可與 filter 同時使用)

filter?:

Record<string, any>
用於識別待刪除向量的中繼資料篩選條件(不可與 ids 同時使用)

回應型別
「回應型別」的直接連結

查詢結果會以下列格式傳回:

interface QueryResult {
id: string
score: number
metadata: Record<string, any>
vector?: number[] // Only included if includeVector is true
}

錯誤處理
「錯誤處理」的直接連結

此儲存會針對不同失敗情況擲回特定錯誤:

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)
}
}

常見錯誤情況包括:

  • 索引名稱格式無效
  • 向量維度無效
  • 找不到資料表/索引
  • 資料庫連線問題
  • upsert 期間交易失敗

使用範例
「使用範例」的直接連結

使用 fastembed 的本機嵌入
「使用 fastembed 的本機嵌入」的直接連結

嵌入是記憶體的 semanticRecall 用來依語意(而非關鍵字)擷取相關訊息的數值向量。此設定使用 @mastra/fastembed 產生向量嵌入。

請先安裝 fastembed

npm install @mastra/fastembed@latest

將下列內容新增至你的 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.6-sol',
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
},
}),
})