Memory.query()
.query()
メソッドは、特定のスレッドからメッセージを取得し、ページネーション、フィルターリング、セマンティック検索に対応しています。
使用例
await memory?.query({ threadId: "user-123" });
パラメータ
threadId:
string
メッセージを取得する対象スレッドの一意の識別子
resourceId?:
string
スレッドを所有するリソースの任意のID。指定された場合はスレッドの所有権を検証します
selectBy?:
object
メッセージのフィルタリングおよび選択用のオプション
threadConfig?:
MemoryConfig
メッセージ取得およびセマンティック検索に関する設定オプション
format?:
'v1' | 'v2'
返すメッセージのフォーマット。現在の形式には 'v2' がデフォルト、後方互換のためには 'v1' を使用します
selectBy パラメーター
vectorSearchString?:
string
意味的に類似したメッセージを検索するための文字列。threadConfig で semantic recall を有効にしておく必要があります。
last?:
number | false
取得する最新メッセージの件数。制限を無効化するには false を指定します。注意: threadConfig.lastMessages(既定値: 10)がこれより小さい場合はそちらが優先されます。
include?:
{ id: string; threadId?: string; withPreviousMessages?: number; withNextMessages?: number }[]
任意のコンテキストメッセージを添えて取得する特定のメッセージ ID の配列。各要素には必須の `id`、任意の `threadId`(既定ではメインの threadId)、`withPreviousMessages`(前に含めるメッセージ数。ベクトル検索時は既定で 2、それ以外は 0)、`withNextMessages`(後に含めるメッセージ数。ベクトル検索時は既定で 2、それ以外は 0)が含まれます。
pagination?:
{ dateRange?: { start?: Date; end?: Date }; page?: number; perPage?: number }
メッセージをバッチで取得するためのページネーション設定。`dateRange`(日付範囲でのフィルター)、`page`(0 始まりのページ番号)、`perPage`(1 ページあたりのメッセージ数)を指定します。
threadConfig のパラメータ
lastMessages?:
number | false
= 10
取得する最新メッセージ数。無効化する場合は false を指定します。
semanticRecall?:
boolean | { topK: number; messageRange: number | { before: number; after: number }; scope?: 'thread' | 'resource' }
= false
メッセージ履歴でのセマンティック検索を有効にします。boolean か、設定オプションを持つオブジェクトを指定できます。有効化するには、ベクターストアとエンベッダーの両方の設定が必要です。
workingMemory?:
WorkingMemory
= { enabled: false, template: '# User Information\n- **First Name**:\n- **Last Name**:\n...' }
ワーキングメモリ機能の設定。`{ enabled: boolean; template?: string; schema?: ZodObject<any> | JSONSchema7; scope?: 'thread' | 'resource' }` または `{ enabled: boolean }`(無効化)を指定できます。
threads?:
{ generateTitle?: boolean | { model: DynamicArgument<MastraLanguageModel>; instructions?: DynamicArgument<string> } }
= { generateTitle: false }
メモリスレッドの作成に関する設定。`generateTitle` はユーザーの最初のメッセージからスレッドタイトルを自動生成するかを制御します。boolean か、カスタムの model と instructions を指定するオブジェクトを渡せます。
戻り値
messages:
CoreMessage[]
取得したメッセージをコア形式で収めた配列
uiMessages:
UIMessageWithMetadata[]
UI 表示用に整形されたメッセージの配列。ツール呼び出しとその結果のスレッド化を適切に反映
詳細な使用例
src/test-memory.ts
import { mastra } from "./mastra";
const agent = mastra.getAgent("agent");
const memory = await agent.getMemory();
const { messages, uiMessages } = await memory!.query({
threadId: "thread-123",
selectBy: {
last: 50,
vectorSearchString: "What messages are there?",
include: [
{
id: "msg-123"
},
{
id: "msg-456",
withPreviousMessages: 3,
withNextMessages: 1
}
]
},
threadConfig: {
semanticRecall: true
}
});
console.log(messages);
console.log(uiMessages);