Mastra 是一个用于构建 AI 驱动应用程序和代理的 TypeScript 框架。使用 Mastra 的 LangSmith 导出器,您可以将 Mastra 代理和工作流的追踪数据发送到 LangSmith 进行调试、评估和可观测性分析。
本指南向您展示如何将 Mastra 与 LangSmith 集成,使用 Mastra 的 AI 追踪系统。
安装
安装 Mastra 和 LangSmith 导出器:
npm install @mastra/core @mastra/langsmith @mastra/observability @mastra/libsql
设置
- 设置您的 LangSmith API 密钥和(可选)LangSmith 项目名称:
- 如果您计划使用 OpenAI 模型,还请确保在运行时提供 OpenAI API 密钥:
- 在您的项目目录中,创建以下项目结构和文件:
src/
mastra.ts
agent.ts
index.ts
使用 LangSmith 导出器配置 Mastra
Mastra 追踪直接在 Mastra 构造函数上配置。将以下内容添加到 mastra.ts file:
agents: { echoAgent },
storage: new LibSQLStore({
url: "file:./mastra.db",
}),
observability: {
configs: {
langsmith: {
serviceName: "mastra-langsmith-demo",
exporters: [
new LangSmithExporter({
apiKey: process.env.LANGSMITH_API_KEY,
}),
],
},
},
},
// Disable deprecated telemetry system
telemetry: {
enabled: false,
},
});
- 存储是追踪所必需的 (即使在外部导出追踪时也需要)。 - LangSmith 导出器从环境变量中读取凭据。 - 已弃用的遥测系统 被禁用以避免警告。 - 在 Mastra 服务器外部运行 Mastra 时,不需要单独的工具文件。 更多详情,请参阅 Mastra 文档.
定义一个代理
为保持兼容性,请使用 基于字符串的模型标识符。将以下代码添加到 agent.ts file:
name: "echoAgent",
instructions: "You are a helpful assistant.",
model: "openai/gpt-4o-mini",
});
Mastra 会自动使用您配置的 API 密钥路由模型调用,并捕获每次调用的追踪数据。
运行代理
- 将以下内容添加到
index.tsfile:
async function main() {
const agent = mastra.getAgent("echoAgent");
const result = await agent.generate("Say hello and explain what Mastra is.");
console.log(result.text);
}
main();
- 运行您的应用程序:
npx ts-node src/index.ts
在 LangSmith 中查看追踪
运行代理后:
- 打开 LangSmith UI.
- 选择您的项目。例如
LANGCHAIN_PROJECT. - 的值对应的追踪
echoAgent.generate.
您将能够检查:
- - 模型输入和输出
- - 代理执行步骤
- - 时间和错误信息