跳至主要內容

Memory.listThreads()

listThreads() method 可擷取 threads,支援分頁,並可選擇按 resourceIdmetadata 或兩者篩選。

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

以分頁方式列出所有 threads
以分頁方式列出所有 threads 的直接連結

const result = await memory.listThreads({
page: 0,
perPage: 10,
})

不使用分頁擷取所有 threads
不使用分頁擷取所有 threads 的直接連結

使用 perPage: false 一次過擷取所有符合條件的 threads。

注意

請使用分頁,尤其是處理大型 dataset 時。請謹慎使用此選項。

const result = await memory.listThreads({
filter: { resourceId: 'user-123' },
perPage: false,
})

resourceId 篩選
filter-by-resourceid 的直接連結

const result = await memory.listThreads({
filter: { resourceId: 'user-123' },
page: 0,
perPage: 10,
})

按 metadata 篩選
按 metadata 篩選 的直接連結

const result = await memory.listThreads({
filter: { metadata: { category: 'support', priority: 'high' } },
page: 0,
perPage: 10,
})

組合篩選條件(resourceId 及 metadata)
組合篩選條件(resourceId 及 metadata) 的直接連結

const result = await memory.listThreads({
filter: {
resourceId: 'user-123',
metadata: { status: 'active' },
},
page: 0,
perPage: 10,
})

參數
參數 的直接連結

filter?:

{ resourceId?: string; metadata?: Record<string, unknown> }
可選的 filter object。resourceId 會按 resource ID 篩選 threads;metadata 會按 metadata key-value pair 篩選 threads(使用 AND 邏輯——所有條件均須符合)。

page?:

number
要擷取的頁碼(從 0 開始)

perPage?:

number | false
每頁最多傳回的 thread 數目;設為 false 則擷取全部

orderBy?:

{ field: 'createdAt' | 'updatedAt', direction: 'ASC' | 'DESC' }
包含 field 及 direction 的排序設定(預設為 { field: 'createdAt', direction: 'DESC' })

傳回值
傳回值 的直接連結

result:

Promise<StorageListThreadsOutput>
一個 promise,會解析為附有 metadata 的分頁 thread 結果

傳回的 object 包含:

  • threads:thread object array
  • total:符合篩選條件的 thread 總數
  • page:目前頁碼(與輸入的 page 參數相同)
  • perPage:每頁項目數目(與輸入的 perPage 參數相同)
  • hasMore:表示是否尚有更多結果的 boolean

進階使用範例
進階使用範例 的直接連結

src/test-memory.ts
import { mastra } from './mastra'

const agent = mastra.getAgent('agent')
const memory = await agent.getMemory()

let currentPage = 0
const perPage = 25
let hasMorePages = true

// Fetch all active threads for a user, sorted by creation date
while (hasMorePages) {
const result = await memory?.listThreads({
filter: {
resourceId: 'user-123',
metadata: { status: 'active' },
},
page: currentPage,
perPage: perPage,
orderBy: { field: 'createdAt', direction: 'ASC' },
})

if (!result) {
console.log('No threads')
break
}

result.threads.forEach(thread => {
console.log(`Thread: ${thread.id}, Created: ${thread.createdAt}`)
})

hasMorePages = result.hasMore
currentPage++ // Move to next page
}

Metadata 篩選
Metadata 篩選 的直接連結

metadata filter 使用 AND 邏輯;只有所有指定的 key-value pair 均符合,thread 才會包含在結果中:

// This will only return threads where BOTH conditions are true:
// - category === 'support'
// - priority === 'high'
await memory.listThreads({
filter: {
metadata: {
category: 'support',
priority: 'high',
},
},
})