メインコンテンツへ移動

libSQL vector store

libSQL storage 実装は、vector 拡張を備えた SQLite のフォーク libSQL と、vector 拡張を備えた Turso による SQLite 互換のベクトル検索を提供し、軽量で効率的なベクトルデータベースソリューションを実現します。 これは @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 が対応しているのは cosine 類似度だけです。

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
}

エラー処理
エラー処理への直接リンク

失敗の種類に応じて、vector store は個別のエラーをスローします。

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 によるローカル埋め込みへの直接リンク

埋め込みは、Memory の 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
},
}),
})