代理 API
🌐 Agents API
Agents API 提供与 Mastra AI 代理交互的方法,包括生成响应、流式交互以及管理代理工具。
🌐 The Agents API provides methods to interact with Mastra AI agents, including generating responses, streaming interactions, and managing agent tools.
获取所有代理Direct link to 获取所有代理
🌐 Getting All Agents
检索所有可用代理的列表:
🌐 Retrieve a list of all available agents:
const agents = await mastraClient.listAgents();
返回一个将代理 ID 对应到其序列化代理配置的记录。
🌐 Returns a record of agent IDs to their serialized agent configurations.
与特定代理合作Direct link to 与特定代理合作
🌐 Working with a Specific Agent
通过其 ID 获取特定代理的实例:
🌐 Get an instance of a specific agent by its ID:
export const myAgent = new Agent({
id: "my-agent",
});
const agent = mastraClient.getAgent("my-agent");
代理方法Direct link to 代理方法
🌐 Agent Methods
details()Direct link to details()
检索有关代理的详细信息:
🌐 Retrieve detailed information about an agent:
const details = await agent.details();
generate()Direct link to generate()
生成来自代理的回复:
🌐 Generate a response from the agent:
const response = await agent.generate(
[
{
role: "user",
content: "Hello, how are you?",
},
],
{
memory: {
thread: "thread-abc", // Optional: Thread ID for conversation context
resource: "user-123", // Optional: Resource ID
},
structuredOutput: {} // Optional: Structured Output configuration
}
);
你也可以使用带有内存选项的简化字符串格式:
🌐 You can also use the simplified string format with memory options:
const response = await agent.generate("Hello, how are you?", {
memory: {
thread: "thread-1",
resource: "resource-1",
},
});
stream()Direct link to stream()
从代理流式传输响应以实现实时交互:
🌐 Stream responses from the agent for real-time interactions:
const response = await agent.stream("Tell me a story");
// Process data stream with the processDataStream util
response.processDataStream({
onChunk: async (chunk) => {
console.log(chunk);
},
});
你也可以使用带有内存选项的简化字符串格式:
🌐 You can also use the simplified string format with memory options:
const response = await agent.stream("Tell me a story", {
memory: {
thread: "thread-1",
resource: "resource-1",
},
clientTools: { colorChangeTool },
});
response.processDataStream({
onChunk: async (chunk) => {
if (chunk.type === "text-delta") {
console.log(chunk.payload.text);
}
},
});
你也可以直接从响应正文读取:
🌐 You can also read from response body directly:
const reader = response.body.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log(new TextDecoder().decode(value));
}
AI SDK兼容格式Direct link to AI SDK兼容格式
🌐 AI SDK compatible format
要在客户端从 agent.stream(...) 响应中流式传输 AI SDK 格式的部分,将 response.processDataStream 封装到 ReadableStream<ChunkType> 中并使用 toAISdkStream:
🌐 To stream AI SDK-formatted parts on the client from an agent.stream(...) response, wrap response.processDataStream into a ReadableStream<ChunkType> and use toAISdkStream:
import { createUIMessageStream } from "ai";
import { toAISdkStream } from "@mastra/ai-sdk";
import type { ChunkType, MastraModelOutput } from "@mastra/core/stream";
const response = await agent.stream("Tell me a story");
const chunkStream: ReadableStream<ChunkType> = new ReadableStream<ChunkType>({
start(controller) {
response
.processDataStream({
onChunk: async (chunk) => controller.enqueue(chunk as ChunkType),
})
.finally(() => controller.close());
},
});
const uiMessageStream = createUIMessageStream({
execute: async ({ writer }) => {
for await (const part of toAISdkStream(
chunkStream as unknown as MastraModelOutput,
{ from: "agent" },
)) {
writer.write(part);
}
},
});
for await (const part of uiMessageStream) {
console.log(part);
}
getTool()Direct link to getTool()
检索有关代理可用的特定工具的信息:
🌐 Retrieve information about a specific tool available to the agent:
const tool = await agent.getTool("tool-id");
executeTool()Direct link to executeTool()
为代理执行特定工具:
🌐 Execute a specific tool for the agent:
const result = await agent.executeTool("tool-id", {
data: { input: "value" },
});
network()Direct link to network()
针对多智能体交互,从代理网络流式获取响应:
🌐 Stream responses from an agent network for multi-agent interactions:
const response = await agent.network("Research this topic and write a summary");
response.processDataStream({
onChunk: async (chunk) => {
console.log(chunk);
},
});
approveToolCall()Direct link to approveToolCall()
批准需要人工确认的待处理工具调用:
🌐 Approve a pending tool call that requires human confirmation:
const response = await agent.approveToolCall({
runId: "run-123",
toolCallId: "tool-call-456",
});
response.processDataStream({
onChunk: async (chunk) => {
console.log(chunk);
},
});
declineToolCall()Direct link to declineToolCall()
拒绝需要人工确认的待处理工具调用:
🌐 Decline a pending tool call that requires human confirmation:
const response = await agent.declineToolCall({
runId: "run-123",
toolCallId: "tool-call-456",
});
response.processDataStream({
onChunk: async (chunk) => {
console.log(chunk);
},
});
approveToolCallGenerate()Direct link to approveToolCallGenerate()
在使用 generate()(非流式)时批准待处理的工具调用。返回完整响应:
🌐 Approve a pending tool call when using generate() (non-streaming). Returns the complete response:
const output = await agent.generate("Find user John", {
requireToolApproval: true,
});
if (output.finishReason === "suspended") {
const result = await agent.approveToolCallGenerate({
runId: output.runId,
toolCallId: output.suspendPayload.toolCallId,
});
console.log(result.text);
}
declineToolCallGenerate()Direct link to declineToolCallGenerate()
在使用 generate()(非流式)时拒绝待处理的工具调用。返回完整响应:
🌐 Decline a pending tool call when using generate() (non-streaming). Returns the complete response:
const output = await agent.generate("Find user John", {
requireToolApproval: true,
});
if (output.finishReason === "suspended") {
const result = await agent.declineToolCallGenerate({
runId: output.runId,
toolCallId: output.suspendPayload.toolCallId,
});
console.log(result.text);
}
客户端工具Direct link to 客户端工具
🌐 Client Tools
客户端工具允许你在代理请求时在客户端执行自定义功能。
🌐 Client-side tools allow you to execute custom functions on the client side when the agent requests them.
import { createTool } from "@mastra/client-js";
import { z } from "zod";
const colorChangeTool = createTool({
id: "changeColor",
description: "Changes the background color",
inputSchema: z.object({
color: z.string(),
}),
execute: async (inputData) => {
document.body.style.backgroundColor = inputData.color;
return { success: true };
},
});
// Use with generate
const response = await agent.generate("Change the background to blue", {
clientTools: { colorChangeTool },
});
// Use with stream
const response = await agent.stream("Tell me a story", {
memory: {
thread: "thread-1",
resource: "resource-1",
},
clientTools: { colorChangeTool },
});
response.processDataStream({
onChunk: async (chunk) => {
if (chunk.type === "text-delta") {
console.log(chunk.payload.text);
} else if (chunk.type === "tool-call") {
console.log(
`calling tool ${chunk.payload.toolName} with args ${JSON.stringify(
chunk.payload.args,
null,
2
)}`
);
}
},
});
存储代理Direct link to 存储代理
🌐 Stored Agents
存储的代理是存储在数据库中的代理配置,可以在运行时创建、更新和删除。它们通过键引用原语(工具、工作流、其他代理、内存、评分器),在代理实例化时从 Mastra 注册表中解析这些键。
🌐 Stored agents are agent configurations stored in a database that can be created, updated, and deleted at runtime. They reference primitives (tools, workflows, other agents, memory, scorers) by key, which are resolved from the Mastra registry when the agent is instantiated.
listStoredAgents()Direct link to listStoredAgents()
检索所有存储代理的分页列表:
🌐 Retrieve a paginated list of all stored agents:
const result = await mastraClient.listStoredAgents();
console.log(result.agents); // Array of stored agents
console.log(result.total); // Total count
带有分页和排序:
🌐 With pagination and ordering:
const result = await mastraClient.listStoredAgents({
page: 0,
perPage: 20,
orderBy: {
field: "createdAt",
direction: "DESC",
},
});
createStoredAgent()Direct link to createStoredAgent()
创建新的存储代理:
🌐 Create a new stored agent:
const agent = await mastraClient.createStoredAgent({
id: "my-agent",
name: "My Assistant",
instructions: "You are a helpful assistant.",
model: {
provider: "openai",
name: "gpt-4",
},
});
配置齐全
🌐 With all options:
const agent = await mastraClient.createStoredAgent({
id: "full-agent",
name: "Full Agent",
description: "A fully configured agent",
instructions: "You are a helpful assistant.",
model: {
provider: "openai",
name: "gpt-4",
},
tools: ["calculator", "weather"],
workflows: ["data-processing"],
agents: ["sub-agent-1"],
memory: "my-memory",
scorers: {
"quality-scorer": {
sampling: { type: "ratio", rate: 0.1 },
},
},
defaultOptions: {
maxSteps: 10,
},
metadata: {
version: "1.0",
team: "engineering",
},
});
getStoredAgent()Direct link to getStoredAgent()
获取特定存储代理的实例:
🌐 Get an instance of a specific stored agent:
const storedAgent = mastraClient.getStoredAgent("my-agent");
存储的代理方法Direct link to 存储的代理方法
🌐 Stored Agent Methods
details()Direct link to details()
检索已存储的代理配置:
🌐 Retrieve the stored agent configuration:
const details = await storedAgent.details();
console.log(details.name);
console.log(details.instructions);
console.log(details.model);
update()Direct link to update()
更新已存储代理的特定字段。所有字段都是可选的:
🌐 Update specific fields of a stored agent. All fields are optional:
const updated = await storedAgent.update({
name: "Updated Agent Name",
instructions: "New instructions for the agent.",
});
// Update just the tools
await storedAgent.update({
tools: ["new-tool-1", "new-tool-2"],
});
// Update metadata
await storedAgent.update({
metadata: {
version: "2.0",
lastModifiedBy: "admin",
},
});
delete()Direct link to delete()
删除已存储的代理:
🌐 Delete a stored agent:
const result = await storedAgent.delete();
console.log(result.success); // true