跳至主要內容

Agent.network()

.network() 方法可啟用多 Agent 協作及路由。此方法接受訊息及可選的執行選項。

已棄用

.network() primitive 已棄用,並會在未來的主要版本中移除。請改用搭配 agent.stream()agent.generate()supervisor Agent。請參閱遷移指南進行升級。

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

import { Agent } from '@mastra/core/agent'
import { agent1, agent2 } from './agents'
import { workflow1 } from './workflows'
import { tool1, tool2 } from './tools'

const agent = new Agent({
id: 'network-agent',
name: 'Network Agent',
instructions: 'You are a network agent that can help users with a variety of tasks.',
model: 'openai/gpt-5.6-sol',
agents: {
agent1,
agent2,
},
workflows: {
workflow1,
},
tools: {
tool1,
tool2,
},
})

await agent.network(`
Find me the weather in Tokyo.
Based on the weather, plan an activity for me.
`)

參數
參數 的直接連結

messages:

string | string[] | CoreMessage[] | AiMessageType[] | UIMessageWithMetadata[]
要傳送給 Agent 的訊息。可以是單一字串、字串陣列或結構化訊息物件。

options?:

MultiPrimitiveExecutionOptions
網絡程序的可選配置。
MultiPrimitiveExecutionOptions

maxSteps?:

number
執行期間最多可運行的步驟數目。

abortSignal?:

AbortSignal
用於中止網絡執行的訊號。中止時,網絡會停止路由、取消任何進行中的子 Agent、Tool 或 Workflow 執行,並略過將部分結果儲存至記憶體。

onAbort?:

(event: { primitiveType: string; primitiveId: string; iteration: number }) => void | Promise<void>
網絡中止時觸發的回呼。接收一個事件,當中包含中止發生時正在執行的 primitive 類型及 ID。

memory?:

object
記憶體配置。這是管理記憶體的建議方式。
object

thread:

string | { id: string; metadata?: Record<string, any>, title?: string }
對話 thread,可以是字串 ID,或包含 id 及可選 metadata 的物件。

resource:

string
與 thread 關聯的用戶或資源識別碼。

options?:

MemoryConfig
記憶體行為的配置,例如訊息記錄及語意回憶。

tracingContext?:

TracingContext
用於建立子 span 及加入 metadata 的 tracing context。使用 Mastra tracing 系統時會自動注入。
TracingContext

currentSpan?:

Span
用於建立子 span 及加入 metadata 的目前 span。可用於建立自訂子 span,或在執行期間更新 span 屬性。

tracingOptions?:

TracingOptions
Tracing 配置的選項。
TracingOptions

metadata?:

Record<string, any>
要加入根 trace span 的 metadata。適合用於加入用戶 ID、工作階段 ID 或功能旗標等自訂屬性。

requestContextKeys?:

string[]
要擷取為此 trace metadata 的其他 RequestContext key。支援以點記法表示巢狀值(例如 'user.id')。

traceId?:

string
此執行使用的 Trace ID(1 至 32 個十六進制字元)。如有提供,此 trace 將成為指定 trace 的一部分。

parentSpanId?:

string
此執行使用的父 span ID(1 至 16 個十六進制字元)。如有提供,根 span 將建立為此 span 的子項。

tags?:

string[]
要套用至此 trace 的標籤。用於分類及篩選 trace 的字串標籤。

telemetry?:

TelemetrySettings
串流期間的 OTLP 遙測收集設定(並非 Tracing)。
TelemetrySettings

isEnabled?:

boolean
啟用或停用遙測。實驗階段預設為停用。

recordInputs?:

boolean
啟用或停用輸入記錄。預設為啟用。為免記錄敏感資料,你可能需要停用輸入記錄。

recordOutputs?:

boolean
啟用或停用輸出記錄。預設為啟用。為免記錄敏感資料,你可能需要停用輸出記錄。

functionId?:

string
此函式的識別碼,用於按函式將遙測資料分組。

modelSettings?:

CallSettings
Model-specific settings like temperature, maxOutputTokens, topP, etc. These settings control how the language model generates responses.

temperature?:

number
Controls randomness in generation (0-2). Higher values make output more random.

maxOutputTokens?:

number
Maximum number of tokens to generate in the response. Note: Use maxOutputTokens (not maxTokens) as per AI SDK v5 convention.

maxRetries?:

number
Maximum number of retry attempts for failed requests.

topP?:

number
Nucleus sampling parameter (0-1). Controls diversity of generated text.

topK?:

number
Top-k sampling parameter. Limits vocabulary to k most likely tokens.

presencePenalty?:

number
Penalty for token presence (-2 to 2). Reduces repetition.

frequencyPenalty?:

number
Penalty for token frequency (-2 to 2). Reduces repetition of frequent tokens.

stopSequences?:

string[]
Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated.

structuredOutput?:

StructuredOutputOptions
從網絡結果產生具型別結構化輸出的配置。
StructuredOutputOptions

schema:

ZodSchema | JSONSchema7
用於驗證輸出的 schema。可以是 Zod schema 或 JSON Schema。

model?:

MastraModelConfig
用於產生結構化輸出的模型。預設使用 Agent 的模型。

instructions?:

string
用於產生結構化輸出的自訂指示。

runId?:

string
此次產生運行的唯一 ID,適合用於追蹤及除錯。

requestContext?:

RequestContext
用於依賴注入及情境資訊的 Request Context。

traceId?:

string
啟用 Tracing 時與此執行關聯的 Trace ID。可用於關聯記錄及除錯執行流程。

spanId?:

string
啟用 Tracing 時與此執行關聯的根 span ID。可用於 span 層級的查找及關聯。

onStepFinish?:

(event: any) => Promise<void> | void
子 Agent 執行中每個 LLM 步驟完成後觸發的回呼。接收步驟詳情,包括完成原因及 token 用量。

onError?:

({ error }: { error: Error | string }) => Promise<void> | void
子 Agent 執行期間發生錯誤時觸發的回呼。

傳回值
傳回值 的直接連結

stream:

MastraAgentNetworkStream<NetworkChunkType>
擴充 ReadableStream<NetworkChunkType> 並加入網絡特定屬性的自訂 stream

status:

Promise<RunStatus>
解析為目前 Workflow 運行狀態的 promise

result:

Promise<WorkflowResult<TState, TOutput, TSteps>>
解析為最終 Workflow 結果的 promise

usage:

Promise<{ promptTokens: number; completionTokens: number; totalTokens: number }>
解析為 token 用量統計資料的 promise

object:

Promise<OUTPUT | undefined>
解析為結構化輸出物件的 promise。只有在提供 structuredOutput 選項時才可用。如未指定 schema,則解析為 undefined。

objectStream:

ReadableStream<Partial<OUTPUT>>
產生結構化輸出期間的部分物件 stream,適合在產生部分結果時串流傳送。

結構化輸出
結構化輸出 的直接連結

如需從網絡取得具型別並經驗證的結果,請使用 structuredOutput 選項。網絡會在任務完成後產生符合 schema 的回應。

import { z } from 'zod'

const resultSchema = z.object({
summary: z.string().describe('A brief summary of the findings'),
recommendations: z.array(z.string()).describe('List of recommendations'),
confidence: z.number().min(0).max(1).describe('Confidence score'),
})

const stream = await agent.network('Research AI trends and summarize', {
structuredOutput: {
schema: resultSchema,
},
})

// Consume the stream
for await (const chunk of stream) {
// Handle streaming events
}

// Get the typed result
const result = await stream.object
// result is typed as { summary: string; recommendations: string[]; confidence: number }
console.log(result?.summary)
console.log(result?.recommendations)

串流傳送部分物件
串流傳送部分物件 的直接連結

你亦可在產生部分物件時串流傳送:

const stream = await agent.network('Analyze data', {
structuredOutput: { schema: resultSchema },
})

// Stream partial objects
for await (const partial of stream.objectStream) {
console.log('Partial result:', partial)
}

// Get final result
const final = await stream.object

Chunk 類型
Chunk 類型 的直接連結

使用結構化輸出時,會發出以下額外 chunk 類型:

  • network-object:串流期間隨部分物件發出
  • network-object-result:隨最終結構化物件發出

中止網絡
中止網絡 的直接連結

使用 abortSignal 取消正在運行的網絡。中止時,網絡會停止路由、取消任何進行中的子 Agent、Tool 或 Workflow 執行,並且不會將部分結果儲存至記憶體。

const controller = new AbortController()

// Abort after 30 seconds
setTimeout(() => controller.abort(), 30_000)

const stream = await agent.network('Research this topic thoroughly', {
abortSignal: controller.signal,
onAbort: ({ primitiveType, primitiveId, iteration }) => {
console.log(`Aborted ${primitiveType} "${primitiveId}" at iteration ${iteration}`)
},
})

for await (const chunk of stream) {
if (
chunk.type === 'routing-agent-abort' ||
chunk.type === 'agent-execution-abort' ||
chunk.type === 'tool-execution-abort' ||
chunk.type === 'workflow-execution-abort'
) {
console.log('Network was aborted')
}
}