跳到主要内容

LangfuseExporter

将 Tracing 数据发送到 Langfuse,用于可观测性。

构造函数
构造函数的直接链接

new LangfuseExporter(config: LangfuseExporterConfig)

LangfuseExporterConfig
langfuseexporterconfig的直接链接

interface LangfuseExporterConfig extends BaseExporterConfig {
publicKey?: string
secretKey?: string
baseUrl?: string
realtime?: boolean
flushAt?: number
flushInterval?: number
environment?: string
release?: string
}

扩展 BaseExporterConfig,其中包含:

  • logger?: IMastraLogger - Logger 实例
  • logLevel?: LogLevel | 'debug' | 'info' | 'warn' | 'error' - 日志级别(默认值:INFO)

属性
属性的直接链接

client
client的直接链接

get client(): LangfuseClient | undefined

用于 Langfuse 高级功能的 LangfuseClient 实例。Exporter 被禁用(缺少凭据)时返回 undefined。可用于 prompt 管理、评估、数据集和直接访问 API。

方法
方法的直接链接

flush
flush的直接链接

async flush(): Promise<void>

强制将缓冲区中的所有 Span 和 score 刷新到 Langfuse,而不关闭 Exporter。适用于需要确保运行时终止前已导出数据的 serverless 环境。

shutdown
shutdown的直接链接

async shutdown(): Promise<void>

刷新待处理数据,并同时关闭 Span processor 和客户端。

用法
用法的直接链接

零配置(使用环境变量)
零配置(使用环境变量)的直接链接

import { LangfuseExporter } from '@mastra/langfuse'

// Reads from LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, LANGFUSE_BASE_URL
const exporter = new LangfuseExporter()

显式配置
显式配置的直接链接

import { LangfuseExporter } from '@mastra/langfuse'

const exporter = new LangfuseExporter({
publicKey: process.env.LANGFUSE_PUBLIC_KEY,
secretKey: process.env.LANGFUSE_SECRET_KEY,
baseUrl: 'https://cloud.langfuse.com',
realtime: true,
})

Span 映射
Span 映射的直接链接

Mastra Span 会转换为 OTel 格式,并通过 LangfuseSpanProcessor 发送到 Langfuse。Langfuse 会根据 Span 的 gen_ai.* 属性自动进行映射:

  • 带有 model 属性的 Span → Langfuse generation
  • 所有其他 Span → Langfuse Span
  • 通过 OTel Trace/Span ID 保留父子关系

Prompt 关联
Prompt 关联的直接链接

使用 withLangfusePrompt helper 将 LLM generation 关联到 Langfuse Prompt Management

import { buildTracingOptions } from '@mastra/observability'
import { LangfuseExporter, withLangfusePrompt } from '@mastra/langfuse'

const exporter = new LangfuseExporter()

// Fetch prompt via the Langfuse client
const prompt = await exporter.client.prompt.get('customer-support', { type: 'text' })

const agent = new Agent({
id: 'support-agent',
name: 'support-agent',
instructions: prompt.compile(),
model: 'openai/gpt-5.6-sol',
defaultGenerateOptions: {
tracingOptions: buildTracingOptions(
withLangfusePrompt({ name: prompt.name, version: prompt.version }),
),
},
})

Helper 函数
Helper 函数的直接链接

withLangfusePrompt(prompt)
withlangfusepromptprompt的直接链接

将 Langfuse prompt 元数据添加到 Tracing 选项。

// Link by name and version (required for Langfuse v5)
withLangfusePrompt({ name: 'my-prompt', version: 1 })

Prompt 元数据会作为 Span 属性透传,Langfuse 会将 generation 关联到相应的 prompt。