跳至主要內容

askUserTool

這是一個與 Agent 無關的內置 Tool,可向用戶提問並等候回覆。此 Tool 支援自由文字問題、單選提示及多選提示。

此 Tool 透過原生的 Tool 暫停原語來暫停:它會使用問題負載呼叫 suspend(),令 Agent 發出 tool-call-suspended 事件並保存執行狀態。使用 agent.resumeStream(answer, { runId }) 恢復執行。

在 Agent 執行以外的環境執行時(沒有可用的 suspend),此 Tool 會傳回包含問題及選項、清晰易讀的後備字串。

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

askUserTool 加入 Agent 的 Tool 集合:

src/mastra/agents/index.ts
import { Agent } from '@mastra/core/agent'
import { askUserTool } from '@mastra/core/tools'

const agent = new Agent({
id: 'assistant',
name: 'Assistant',
instructions: 'Ask the user for clarification when the request is ambiguous.',
model,
tools: { askUserTool },
})

處理暫停並恢復執行:

src/run.ts
const stream = await agent.stream('Summarize my project')

for await (const chunk of stream.fullStream) {
if (chunk.type === 'tool-call-suspended') {
const { question, options, selectionMode } = chunk.payload.suspendPayload
// Present the question to the user, collect their answer, then resume:
const resumed = await agent.resumeStream('The main repo', { runId: stream.runId })
for await (const c of resumed.textStream) process.stdout.write(c)
}
}

如屬多選提示,請使用字串陣列恢復執行:

await agent.resumeStream(['Add tests', 'Update docs'], { runId: stream.runId })

輸入結構
輸入結構 的直接連結

模型會使用以下參數呼叫此 Tool:

question:

string
要向用戶提出的問題。不得為空白。

options?:

AskUserOption[]
供用戶選擇的結構化選項。如省略,提示會採用自由文字形式。
AskUserOption

label:

string
此選項的簡短顯示文字。選取後,此值會傳回模型。

description?:

string
此選項含義的說明。

selectionMode?:

'single_select' | 'multi_select'
控制用戶可選取的選項數目。提供選項時,預設為 'single_select'。必須提供選項。

暫停負載
暫停負載 的直接連結

tool-call-suspended 事件會包含一個與輸入結構相同的 suspendPayload

question:

string
正在向用戶提出的問題。

options?:

AskUserOption[]
結構化選項(如有)。

selectionMode?:

'single_select' | 'multi_select'
解析後的選取模式。自由文字提示會省略此項。

恢復資料
恢復資料 的直接連結

將用戶的答案傳入 agent.resumeStream()

  • 自由文字及單選: 一個 string
  • 多選: 一個由已選選項標籤組成的 string[]