使用工具
🌐 Using Tools
代理可以使用工具来调用 API、查询数据库或运行你代码库中的自定义函数。工具通过提供对数据的结构化访问和执行明确定义的操作,为代理提供了超越语言生成的能力。你还可以从远程 MCP 服务器 加载工具,以扩展代理的功能。
🌐 Agents use tools to call APIs, query databases, or run custom functions from your codebase. Tools give agents capabilities beyond language generation by providing structured access to data and performing clearly defined operations. You can also load tools from remote MCP servers to expand an agent's capabilities.
何时使用工具Direct link to 何时使用工具
🌐 When to use tools
当代理需要从远程资源获取额外的上下文或信息,或者需要运行执行特定操作的代码时,请使用工具。这包括模型无法可靠独立处理的任务,例如获取实时数据或返回一致且明确定义的输出。
🌐 Use tools when an agent needs additional context or information from remote resources, or when it needs to run code that performs a specific operation. This includes tasks a model can't reliably handle on its own, such as fetching live data or returning consistent, well defined outputs.
创建一个工具Direct link to 创建一个工具
🌐 Creating a tool
在创建工具时,保持描述简洁,并专注于工具的功能,强调其主要用途。描述性架构名称也可以帮助引导代理如何使用该工具。
🌐 When creating tools, keep descriptions simple and focused on what the tool does, emphasizing its primary use case. Descriptive schema names can also help guide the agent on how to use the tool.
这个示例展示了如何创建一个从 API 获取天气数据的工具。当代理调用该工具时,它会根据工具的 inputSchema 定义提供所需的输入。该工具通过其 inputData 参数访问这些数据,在此示例中,该参数包含在天气 API 查询中使用的 location。
🌐 This example shows how to create a tool that fetches weather data from an API. When the agent calls the tool, it provides the required input as defined by the tool's inputSchema. The tool accesses this data through its inputData parameter, which in this example includes the location used in the weather API query.
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
export const weatherTool = createTool({
id: "weather-tool",
description: "Fetches weather for a location",
inputSchema: z.object({
location: z.string(),
}),
outputSchema: z.object({
weather: z.string(),
}),
execute: async (inputData) => {
const { location } = inputData;
const response = await fetch(`https://wttr.in/${location}?format=3`);
const weather = await response.text();
return { weather };
},
});
向代理添加工具Direct link to 向代理添加工具
🌐 Adding tools to an agent
要让代理使用某个工具,需要将其添加到 tools。在代理的系统提示中提到可用工具及其一般用途,有助于代理决定何时调用工具以及何时不调用。
🌐 To make a tool available to an agent, add it to tools. Mentioning available tools and their general purpose in the agent's system prompt helps the agent decide when to call a tool and when not to.
代理可以使用多种工具来处理更复杂的任务,通过将具体部分分配给各个工具。代理会根据用户的消息、代理的指令以及工具的描述和架构来决定使用哪些工具。
🌐 An agent can use multiple tools to handle more complex tasks by delegating specific parts to individual tools. The agent decides which tools to use based on the user's message, the agent's instructions, and the tool descriptions and schemas.
import { Agent } from "@mastra/core/agent";
import { weatherTool } from "../tools/weather-tool";
export const weatherAgent = new Agent({
id: "weather-agent",
name: "Weather Agent",
instructions: `
You are a helpful weather assistant.
Use the weatherTool to fetch current weather data.`,
model: "openai/gpt-5.1",
tools: { weatherTool },
});
在流响应中控制 toolNameDirect link to controlling-toolname-in-stream-responses
🌐 Controlling toolName in stream responses
流响应中的 toolName 是由你使用的 对象键 决定的,而不是工具、代理或工作流的 id 属性决定的。
🌐 The toolName in stream responses is determined by the object key you use, not the id property of the tool, agent, or workflow.
// Tool defined with id: "weather-tool"
export const weatherTool = createTool({
id: "weather-tool",
// ...
});
// Using the variable name as the key
tools: { weatherTool }
// Stream returns: toolName: "weatherTool"
// Using the tool's id as the key
tools: { [weatherTool.id]: weatherTool }
// Stream returns: toolName: "weather-tool"
// Using a custom key
tools: { "my-custom-name": weatherTool }
// Stream returns: toolName: "my-custom-name"
这让你可以指定流中工具的标识方式。如果你希望 toolName 与工具的 id 匹配,请使用工具的 id 作为对象键。
🌐 This lets you specify how tools are identified in the stream. If you want the toolName to match the tool's id, use the tool's id as the object key.
子代理和工作流程作为工具Direct link to 子代理和工作流程作为工具
🌐 Sub-agents and workflows as tools
子代理和工作流程遵循相同的模式。它们被转换为带有前缀并跟随你的对象键的工具:
🌐 Sub-agents and workflows follow the same pattern. They are converted to tools with a prefix followed by your object key:
| 属性 | 前缀 | 示例键 | toolName |
|---|---|---|---|
agents | agent- | weather | agent-weather |
workflows | workflow- | research | workflow-research |
const orchestrator = new Agent({
// ...
agents: {
weather: weatherAgent, // toolName: "agent-weather"
},
workflows: {
research: researchWorkflow, // toolName: "workflow-research"
},
});
请注意,对于子代理,你将在流响应中看到两个不同的标识符:
🌐 Note that for sub-agents, you'll see two different identifiers in stream responses:
toolName: "agent-weather"在工具调用事件中 — 生成的工具封装器名称data-tool-agent块中的id: "weather-agent"—— 子代理的实际id属性
调用代理Direct link to 调用代理
🌐 Calling an agent
代理使用工具的 inputSchema 来推断工具期望的数据。在这种情况下,它从消息中提取 London 作为 location,并将其传递给工具的 inputData 参数。
🌐 The agent uses the tool's inputSchema to infer what data the tool expects. In this case, it extracts London as the location from the message and passes it to the tool's inputData parameter.
import { mastra } from "./mastra";
const agent = mastra.getAgent("weatherAgent");
const result = await agent.generate("What's the weather in London?");
使用多种工具Direct link to 使用多种工具
🌐 Using multiple tools
当有多种工具可用时,代理可以根据回答查询所需选择使用一种、几种或不使用任何工具。
🌐 When multiple tools are available, the agent may choose to use one, several, or none, depending on what's needed to answer the query.
import { weatherTool } from "../tools/weather-tool";
import { activitiesTool } from "../tools/activities-tool";
export const weatherAgent = new Agent({
id: "weather-agent",
name: "Weather Agent",
tools: { weatherTool, activitiesTool },
});
将工作流作为工具使用Direct link to 将工作流作为工具使用
🌐 Using workflows as tools
工作流可以通过 workflows 配置添加到代理。当你添加工作流时,Mastra 会自动将其转换为代理可以调用的工具。生成的工具名为 workflow-<workflowName>,并使用工作流的 inputSchema 和 outputSchema。
🌐 Workflows can be added to agents through the workflows configuration. When you add a workflow, Mastra automatically converts it to a tool that the agent can call. The generated tool is named workflow-<workflowName> and uses the workflow's inputSchema and outputSchema.
import { Agent } from "@mastra/core/agent";
import { researchWorkflow } from "../workflows/research-workflow";
export const researchAgent = new Agent({
id: "research-agent",
name: "Research Agent",
instructions: `
You are a research assistant.
Use the research workflow to gather and compile information on topics.`,
model: "openai/gpt-5.1",
tools: {
weatherTool,
},
workflows: {
researchWorkflow,
},
});
工作流程应包括一个 description,以帮助代理了解何时使用它:
🌐 The workflow should include a description to help the agent understand when to use it:
import { createWorkflow } from "@mastra/core/workflows";
import { z } from "zod";
export const researchWorkflow = createWorkflow({
id: "research-workflow",
description: "Gathers information on a topic and compiles a summary report.",
inputSchema: z.object({
topic: z.string(),
}),
outputSchema: z.object({
summary: z.string(),
sources: z.array(z.string()),
}),
})
.then(gatherSourcesStep)
.then(compileReportStep)
.commit();
当代理调用工作流工具时,它会收到一个包含工作流结果和一个可用于跟踪执行的 runId 的响应:
🌐 When the agent calls the workflow tool, it receives a response containing the workflow result and a runId that can be used to track the execution:
{
result: { summary: "...", sources: ["..."] },
runId: "abc-123"
}
具有结构化输出的工具Direct link to 具有结构化输出的工具
🌐 Tools with structured output
在使用具有 结构化输出 的工具时,一些模型不支持在同一个 API 调用中同时使用这两种功能。如果在启用结构化输出时工具未被调用,或收到有关选项不兼容的错误,请参阅 组合工具与结构化输出 以获取模型兼容性信息和解决方法。
🌐 When using tools with structured output, some models don't support combining both features in the same API call. If your tools aren't being called when structured output is enabled, or you receive errors about incompatible options, see Combining tools and structured output for model compatibility information and workarounds.
相关Direct link to 相关
🌐 Related