跳至主要內容

chatRoute()

建立聊天路由處理器,使用 AI SDK 格式串流 Agent 對話。此函式會註冊一個 HTTP POST 端點,用來接收訊息、執行 Agent,並以 AI SDK 相容格式將回應串流傳回使用者端。你必須在自訂 API 路由中使用此函式。

如果需要與框架無關的處理器,請使用 handleChatStream()

chatRoute() 會保留現有的 AI SDK v5/預設行為。如果你的應用程式使用 AI SDK v6 型別,請傳入 version: 'v6'

中斷連線時的行為

chatRoute() 會將傳入請求的 AbortSignal 轉送至 agent.stream()。如果使用者端中斷連線,Mastra 會中止進行中的生成作業。

如果希望伺服器在中斷連線後繼續生成並保存最終回應,請以 agent.stream() 建立自訂 API 路由,接著呼叫 consumeStream();呼叫對象是傳回的 MastraModelOutput

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

以下範例說明如何在 /chat 端點設定聊天路由,並使用 ID 為 weatherAgent 的 Agent。

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { chatRoute } from '@mastra/ai-sdk'

export const mastra = new Mastra({
server: {
apiRoutes: [
chatRoute({
path: '/chat',
agent: 'weatherAgent',
}),
],
},
})

你也可以根據 agentId 使用執行階段定義的 Agent 路由。URL /chat/weatherAgent 會解析為 ID 是 weatherAgent 的 Agent。

src/mastra/index.ts
import { Mastra } from '@mastra/core'
import { chatRoute } from '@mastra/ai-sdk'

export const mastra = new Mastra({
server: {
apiRoutes: [
chatRoute({
path: '/chat/:agentId',
}),
],
},
})

參數
「參數」的直接連結

version?:

'v5' | 'v6'
= 'v5'
選擇要輸出的 AI SDK 串流契約。省略此參數或傳入 'v5',即可使用現有的預設行為。當你的應用程式使用 AI SDK v6 回應輔助函式的型別時,請傳入 'v6'

path:

string
= '/chat/:agentId'
路由路徑(例如 /chat/chat/:agentId)。若要使用動態 Agent 路由,請加入 :agentId

agent?:

string
此聊天路由要使用的 Agent ID。如果路徑未包含 :agentId,則此參數為必要參數。

agentVersion?:

{ versionId: string } | { status?: 'draft' | 'published' }
選擇特定 Agent 版本。傳入 { versionId: '<id>' } 可指定確切版本;傳入 { status: 'draft' }{ status: 'published' } 則可依狀態解析。呼叫路由時,查詢參數 ?versionId=<id>?status=draft|published 的優先順序高於這個靜態值。必須設定 Editor

defaultOptions?:

AgentExecutionOptions
傳遞至 Agent 執行作業的預設選項。其中可包含指示、記憶體設定、maxSteps,以及其他執行設定。

sendStart?:

boolean
= true
是否在串流中傳送開始事件。

sendFinish?:

boolean
= true
是否在串流中傳送完成事件。

sendReasoning?:

boolean
= false
是否在串流中包含推理步驟。

sendSources?:

boolean
= false
是否在串流中包含來源引用。

heartbeatMs?:

number
SSE 活動訊號的間隔(毫秒),可讓連線在設有閒置逾時的基礎設施中維持運作。

其他設定
「其他設定」的直接連結

你可以使用 prepareSendMessagesRequest 自訂傳送至聊天路由的請求,例如將其他設定傳遞給 Agent:

const { error, status, sendMessage, messages, regenerate, stop } = useChat({
transport: new DefaultChatTransport({
api: 'http://localhost:4111/chat',
prepareSendMessagesRequest({ messages }) {
return {
body: {
messages,
// Pass memory config
memory: {
thread: 'user-1',
resource: 'user-1',
},
},
}
},
}),
})