> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # Memory.listThreads() `listThreads()` 方法會擷取執行緒,支援分頁,並可選擇依 `resourceId`、`metadata` 或兩者同時篩選。 ## 使用範例 ### 以分頁方式列出所有執行緒 ```typescript const result = await memory.listThreads({ page: 0, perPage: 10, }) ``` ### 不使用分頁擷取所有執行緒 使用 `perPage: false`,一次擷取所有相符的執行緒。 > **警告:** 請使用分頁,尤其是處理大型資料集時。請審慎使用此選項。 ```typescript const result = await memory.listThreads({ filter: { resourceId: 'user-123' }, perPage: false, }) ``` ### 依 `resourceId` 篩選 ```typescript const result = await memory.listThreads({ filter: { resourceId: 'user-123' }, page: 0, perPage: 10, }) ``` ### 依中繼資料篩選 ```typescript const result = await memory.listThreads({ filter: { metadata: { category: 'support', priority: 'high' } }, page: 0, perPage: 10, }) ``` ### 組合篩選器(resourceId 和中繼資料) ```typescript const result = await memory.listThreads({ filter: { resourceId: 'user-123', metadata: { status: 'active' }, }, page: 0, perPage: 10, }) ``` ## 參數 **filter** (`{ resourceId?: string; metadata?: Record }`): 選用的篩選器物件。resourceId 依資源 ID 篩選執行緒;metadata 則依中繼資料 key-value 配對篩選執行緒(AND 邏輯,必須全部相符) **page** (`number`): 要擷取的頁碼(從 0 開始) **perPage** (`number | false`): 每頁要回傳的執行緒數量上限;設為 false 則擷取全部 **orderBy** (`{ field: 'createdAt' | 'updatedAt', direction: 'ASC' | 'DESC' }`): 包含欄位與方向的排序設定(預設為 { field: 'createdAt', direction: 'DESC' }) ## 回傳值 **result** (`Promise`): 會解析為含有中繼資料之分頁執行緒結果的 promise 回傳物件包含: - `threads`:執行緒物件陣列 - `total`:符合篩選器的執行緒總數 - `page`:目前頁碼(與輸入的 `page` 參數相同) - `perPage`:每頁項目數(與輸入的 `perPage` 參數相同) - `hasMore`:指出是否還有更多結果的布林值 ## 延伸使用範例 ```typescript 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 } ``` ## 中繼資料篩選 中繼資料篩選器使用 AND 邏輯:執行緒必須符合所有指定的 key-value 配對,才會包含在結果中: ```typescript // This will only return threads where BOTH conditions are true: // - category === 'support' // - priority === 'high' await memory.listThreads({ filter: { metadata: { category: 'support', priority: 'high', }, }, }) ``` ## 相關內容 - [Memory 類別參考](https://mastra.zisheng.pro/zh-TW/reference/memory/memory-class) - [Memory 入門](https://mastra.zisheng.pro/zh-TW/docs/memory/overview) - [createThread](https://mastra.zisheng.pro/zh-TW/reference/memory/createThread) - [getThreadById](https://mastra.zisheng.pro/zh-TW/reference/memory/getThreadById)