Agent.network()
La méthode .network() permet la collaboration et le routage entre plusieurs Agents. Elle accepte des messages et des options d’exécution facultatives.
La primitive .network() est obsolète et sera supprimée dans une prochaine version majeure. Utilisez plutôt des Agents superviseurs avec agent.stream() ou agent.generate(). Consultez le guide de migration pour effectuer la mise à niveau.
Exemple d’utilisationLien direct vers Exemple d’utilisation
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.
`)
ParamètresLien direct vers Paramètres
messages:
options?:
maxSteps?:
abortSignal?:
onAbort?:
memory?:
thread:
id et des metadata facultatives.resource:
options?:
tracingContext?:
currentSpan?:
tracingOptions?:
metadata?:
requestContextKeys?:
traceId?:
parentSpanId?:
tags?:
telemetry?:
isEnabled?:
recordInputs?:
recordOutputs?:
functionId?:
modelSettings?:
temperature?:
maxOutputTokens?:
maxRetries?:
topP?:
topK?:
presencePenalty?:
frequencyPenalty?:
stopSequences?:
structuredOutput?:
schema:
model?:
instructions?:
runId?:
requestContext?:
traceId?:
spanId?:
onStepFinish?:
onError?:
Valeurs renvoyéesLien direct vers Valeurs renvoyées
stream:
status:
result:
usage:
object:
objectStream:
Sortie structuréeLien direct vers Sortie structurée
Lorsque vous avez besoin de résultats typés et validés provenant de votre réseau, utilisez l’option structuredOutput. Le réseau génère une réponse correspondant à votre schéma une fois la tâche terminée.
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)
Diffusion d’objets partielsLien direct vers Diffusion d’objets partiels
Vous pouvez également diffuser les objets partiels à mesure qu’ils sont générés :
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
Types de fragmentsLien direct vers Types de fragments
Lors de l’utilisation d’une sortie structurée, des types de fragments supplémentaires sont émis :
network-object: émis avec les objets partiels pendant la diffusion en continunetwork-object-result: émis avec l’objet structuré final
Interrompre un réseauLien direct vers Interrompre un réseau
Utilisez abortSignal pour annuler un réseau en cours d’exécution. Lors de l’interruption, le réseau arrête le routage, annule toute exécution en cours de sous-Agent, de Tool ou de Workflow et n’enregistre pas les résultats partiels dans la mémoire.
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')
}
}