Agent.network()
The .network() method enables multi-agent collaboration and routing. This method accepts messages and optional execution options.
The .network() primitive has been deprecated and will be removed in a future major release. Use supervisor agents with agent.stream() or agent.generate() instead. See the migration guide to upgrade.
Usage exampleDirect link to Usage example
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.
`)
ParametersDirect link to Parameters
messages:
options?:
maxSteps?:
abortSignal?:
onAbort?:
memory?:
thread:
id and optional metadata.resource:
options?:
tracingContext?:
currentSpan?:
tracingOptions?:
metadata?:
requestContextKeys?:
traceId?:
parentSpanId?:
tags?:
telemetry?:
isEnabled?:
recordInputs?:
recordOutputs?:
functionId?:
modelSettings?:
temperature?:
maxOutputTokens?:
maxRetries?:
topP?:
topK?:
presencePenalty?:
frequencyPenalty?:
timeout?:
totalMs, the maximum duration of the entire agent run across every loop iteration, tool call and retry, and stepMs, the maximum duration of a single model call including the time spent consuming its stream. Exceeding either budget fails with a MastraTimeoutError. A totalMs timeout ends the run and does not try fallback models, because it is a hard deadline for the whole run. A stepMs timeout is not retried against the same model but does advance to the next entry in models when fallback models are configured. Also accepts firstChunkMs, which only applies to streaming calls and is the maximum time the model may take to emit its first content-bearing chunk (text, reasoning, tool call, file or source; stream-start and metadata chunks do not count). A firstChunkMs timeout fails with timeoutType: 'firstChunk', behaves like stepMs for fallback, and is reset for each provider retry attempt. Nested timeout keys are merged across call-time and per-model settings.stopSequences?:
structuredOutput?:
schema:
model?:
instructions?:
runId?:
requestContext?:
traceId?:
spanId?:
onStepFinish?:
onError?:
ReturnsDirect link to Returns
stream:
status:
result:
usage:
object:
objectStream:
Structured outputDirect link to Structured output
When you need typed, validated results from your network, use the structuredOutput option. The network will generate a response matching your schema after task completion.
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)
Streaming Partial ObjectsDirect link to Streaming Partial Objects
You can also stream partial objects as they're being generated:
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 TypesDirect link to Chunk Types
When using structured output, additional chunk types are emitted:
network-object: Emitted with partial objects during streamingnetwork-object-result: Emitted with the final structured object
Aborting a networkDirect link to Aborting a network
Use abortSignal to cancel a running network. When aborted, the network stops routing, cancels any in-progress sub-agent, tool, or workflow execution, and doesn't save partial results to memory.
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')
}
}