操作场景
Langfuse SDK 可用于追踪 LLM 应用中的请求链路、模型调用、输入输出、用户信息、会话信息、耗时和异常状态。您可以将 Langfuse SDK 生成的 OpenTelemetry Trace 数据上报到日志服务(Cloud Log Service,CLS),并在 CLS 中进行检索分析和链路排查。
本文介绍如何将 Langfuse SDK 生成的 Trace 数据上报到 CLS。本文提供以下接入方式:
通过 Skill 快速接入与分析:如果您使用支持 Skill 的 AI 工具,可由 AI 自动创建或复用日志主题、识别项目语言并生成接入代码,同时完成上报验证与数据分析。
手动配置接入:按步骤完成环境变量配置、代码接入和上报验证。
接入方式 | 数据路径 | 推荐场景 |
OTLP/HTTP 标准直传 | 应用 > 标准 OTLP HTTP Exporter > CLS | 手动接入推荐首选。适用于新项目、快速试用、希望减少自定义代码、希望按 OpenTelemetry 标准语义上报 Trace 的场景。 |
说明:
本方案不需要部署 Langfuse Server,也不需要将数据发送到 Langfuse Cloud。业务代码仍使用 Langfuse SDK 生成 Trace,数据出口改为 CLS。
前提条件
开始接入前,请确保已完成以下准备工作:
已开通 日志服务 CLS。
已准备具备 CLS 写入权限的访问凭证,例如 CAM 子账号、CAM Role 或临时密钥。云 API 密钥信息请前往 API 密钥管理 获取。
应用使用 TypeScript/Node.js 或 Python,并已接入或计划接入 Langfuse SDK。
通过 Skill 快速接入与分析
如果您使用支持 Skill 的 AI 工具,可使用 腾讯云 Agent 可观测接入助手 自动完成接入与分析。该 Skill 已合并接入与分析能力,可自动创建或复用日志主题、生成标准 OTLP/HTTP Exporter 直传方案,并处理 Endpoint 拼接、Basic 鉴权、
topic_id header、字段映射、时间单位、退出 flush 和验证说明,还支持基于上报数据的错误诊断、性能、Token 成本、用户会话等多维度分析。使用前请准备以下信息:
参数 | 说明 |
CLS_DEFAULT_REGION | |
TENCENTCLOUD_SECRET_ID | 腾讯云访问凭证 SecretId。 |
TENCENTCLOUD_SECRET_KEY | 腾讯云访问凭证 SecretKey。 |
在 AI 工具中输入以下提示词:
请使用腾讯云 Agent 可观测接入助手 Skill:https://skillhub.cn/skills/tencentcloud-cls-agent-obs帮我把当前项目接入腾讯云 Agent 可观测。接入方式:Langfuse地域:ap-guangzhou(替换为您的实际地域)
手动配置接入
步骤1:配置环境变量
手动接入前,请先登录 日志服务控制台 > Agent 可观测,通过应用接入创建应用,并在日志主题列表中找到名称为 {应用名称}-trace-topic 的日志主题,复制其日志主题 ID(用于下方
CLS_TOPIC_ID)。请在应用项目中创建或更新
.env 文件。请确保 .env 已加入 .gitignore,避免密钥泄露。CLS_DEFAULT_REGION=ap-guangzhouCLS_TOPIC_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxTENCENTCLOUD_SECRET_ID=AKIDxxxxxxxxTENCENTCLOUD_SECRET_KEY=xxxxxxxxSERVICE_NAME=my-llm-app# Python 额外需要。Langfuse Python SDK 启动时会校验密钥是否存在,此处可填写任意非空占位值。LANGFUSE_PUBLIC_KEY=pk-placeholderLANGFUSE_SECRET_KEY=sk-placeholder
说明:
OTLP/HTTP 标准直传不需要单独配置
CLS_ENDPOINT,Endpoint 由 CLS_DEFAULT_REGION 自动拼接而成。常见地域 Endpoint 如下:
地域 | 公网 Endpoint | 内网 Endpoint |
广州 | ap-guangzhou.cls.tencentcs.com | ap-guangzhou.cls.tencentyun.com |
上海 | ap-shanghai.cls.tencentcs.com | ap-shanghai.cls.tencentyun.com |
北京 | ap-beijing.cls.tencentcs.com | ap-beijing.cls.tencentyun.com |
新加坡 | ap-singapore.cls.tencentcs.com | ap-singapore.cls.tencentyun.com |
说明:
公网 Endpoint 适用于公网访问场景。内网 Endpoint 适用于同地域 VPC/CVM 环境,可降低网络延迟并避免公网流量。
步骤2:接入应用
手动接入使用标准 OTLP/HTTP Exporter 将 Trace 上报到 CLS,无需编写自定义导出代码。请根据项目语言选择 TypeScript/Node.js 或 Python 示例完成接入。
说明:
不同语言的 OpenTelemetry SDK 对 Endpoint 参数的要求不同。本文 TypeScript/Node.js 和 Python 示例使用完整 OTLP Trace URL,即
https://{CLS_DEFAULT_REGION}.cls.tencentcs.com/v1/traces。1. 安装依赖。
npm install @langfuse/tracing @langfuse/otel @langfuse/openai \\@opentelemetry/sdk-node \\@opentelemetry/exporter-trace-otlp-http \\dotenv
2. 创建
instrumentation.ts。import "dotenv/config";import { NodeSDK } from "@opentelemetry/sdk-node";import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";import { LangfuseSpanProcessor } from "@langfuse/otel";const secretId = process.env.TENCENTCLOUD_SECRET_ID!;const secretKey = process.env.TENCENTCLOUD_SECRET_KEY!;const region = process.env.CLS_DEFAULT_REGION!;const topicId = process.env.CLS_TOPIC_ID!;const auth = Buffer.from(`${secretId}:${secretKey}`).toString("base64");export const sdk = new NodeSDK({spanProcessors: [new LangfuseSpanProcessor({exporter: new OTLPTraceExporter({url: `https://${region}.cls.tencentcs.com/v1/traces`,headers: {Authorization: `Basic ${auth}`,topic_id: topicId,},}),flushAt: 512,flushInterval: 5000,}),],});sdk.start();process.on("SIGTERM", async () => {await sdk.shutdown();});
3. 在业务入口文件顶部引入
instrumentation.ts。请确保该引入早于 OpenAI、LangChain 等会被 instrumentation patch 的模块。import { sdk } from "./instrumentation";import OpenAI from "openai";import { observeOpenAI } from "@langfuse/openai";import { startActiveObservation, propagateAttributes } from "@langfuse/tracing";const openai = observeOpenAI(new OpenAI());async function chat(userMessage: string) {return startActiveObservation("chat", async (span) => {span.update({ input: [{ role: "user", content: userMessage }] });return propagateAttributes({ userId: "u-123", sessionId: "s-456", tags: ["model:gpt-4o"] },async () => {const res = await openai.chat.completions.create({model: "gpt-4o",messages: [{ role: "user", content: userMessage }],});span.update({ output: res.choices[0].message });return res;},);});}await chat("您好");await sdk.shutdown();
1. 安装依赖。
pip install langfuse opentelemetry-sdk opentelemetry-exporter-otlp python-dotenv
2. 创建
instrumentation.py。该文件必须早于任何 langfuse 模块导入。import osimport base64from dotenv import load_dotenvfrom opentelemetry import tracefrom opentelemetry.sdk.resources import Resourcefrom opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import BatchSpanProcessorfrom opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporterload_dotenv()secret_id = os.environ["TENCENTCLOUD_SECRET_ID"]secret_key = os.environ["TENCENTCLOUD_SECRET_KEY"]region = os.environ["CLS_DEFAULT_REGION"]topic_id = os.environ["CLS_TOPIC_ID"]auth = base64.b64encode(f"{secret_id}:{secret_key}".encode()).decode()provider = TracerProvider(resource=Resource.create({"service.name": os.environ.get("SERVICE_NAME", "my-llm-app")}))provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint=f"https://{region}.cls.tencentcs.com/v1/traces",headers={"Authorization": f"Basic {auth}","topic_id": topic_id,},),max_export_batch_size=512,schedule_delay_millis=5000,))trace.set_tracer_provider(provider)
3. 在业务入口中引入
instrumentation.py。import instrumentationfrom langfuse import observe, propagate_attributes, get_clientfrom langfuse.openai import openai@observe(name="chat", as_type="generation")def chat(user_message: str):with propagate_attributes(user_id="u-123", session_id="s-456", tags=["model:gpt-4o"]):return openai.chat.completions.create(model="gpt-4o",messages=[{"role": "user", "content": user_message}],)if __name__ == "__main__":chat("您好")get_client().flush()
进阶配置
采样配置:您可以在
TracerProvider 上配置采样策略,控制上报到 CLS 的 Trace 数据量。采样器 | 说明 | 适用场景 |
ALWAYS_ON | 全量采样 | 测试环境或低流量环境。 |
ALWAYS_OFF | 全部不采样 | 临时关闭 Trace。 |
TraceIdRatioBased(0.1) | 按比例采样 10% | 生产环境控制写入量。 |
ParentBased(root) | 根据父 Span 决定是否采样 | 分布式链路,保证整条链路采样一致。 |
1. 安装额外依赖。
npm install @opentelemetry/sdk-trace-base
2. instrumentation.ts 中配置采样器。
import {ParentBasedSampler,TraceIdRatioBasedSampler,} from "@opentelemetry/sdk-trace-base";export const sdk = new NodeSDK({sampler: new ParentBasedSampler({root: new TraceIdRatioBasedSampler(0.1),}),// 其他配置保持不变});
在 instrumentation.py 中配置采样器。
from opentelemetry.sdk.trace.sampling import ParentBased, TraceIdRatioBasedprovider = TracerProvider(sampler=ParentBased(TraceIdRatioBased(0.1)),resource=Resource.create({"service.name": os.environ.get("SERVICE_NAME", "my-llm-app")}))
跨地域上报:如果上报链路需要跨地域,可在 OTLP 请求 Header 中添加源地域标识。
new OTLPTraceExporter({url: `https://${region}.cls.tencentcs.com/v1/traces`,headers: {Authorization: `Basic ${auth}`,topic_id: topicId,"x-cross-region": "ap-guangzhou", // 源地域标识},})
OTLPSpanExporter(endpoint=f"https://{region}.cls.tencentcs.com/v1/traces",headers={"Authorization": f"Basic {auth}","topic_id": topic_id,"x-cross-region": "ap-guangzhou", # 源地域标识},)
关闭 HTTPS(仅测试环境)。
可传入 http:// 协议的 URL 来使用明文 HTTP。
url: `http://${region}.cls.tencentcs.com/v1/traces`,
可使用 insecure=True 参数。
OTLPSpanExporter(endpoint=f"http://{region}.cls.tencentcs.com/v1/traces",insecure=True, # 仅测试环境# ...)
步骤3:验证上报结果
完成接入后,在应用中触发一次 LLM 调用,然后在 CLS 控制台中查询 Trace 数据。
1. 登录 日志服务控制台,在左侧导航栏中,选择检索分析。
2. 选择用于存储 Trace 数据的日志主题。
3. 在检索框中输入以下语句,查询最新上报的 Trace 数据。

* | SELECT traceID, spanID, name, duration, statusCode ORDER BY __TIMESTAMP__ DESC LIMIT 10
也可以查询指定调用链:
traceID:"4bf92f3577b34da6a3ce929d0e0e4736"
如需按模型统计平均耗时,请确保模型字段已写入
attribute 并已配置索引或使用 JSON 提取函数:* | SELECT json_extract_scalar(attribute,'$."gen_ai.request.model"') AS model,AVG(duration) AS avg_duration_nsGROUP BY model
字段说明
使用 OTLP/HTTP 标准直传时,
resource、scope、span 等信息会按 OpenTelemetry 标准协议结构上报到 CLS。上报后,OTel Span 字段在 CLS 中的对应关系如下,便于您进行检索和分析:
OTel Span 字段 | CLS LogItem Key | 说明 |
traceId | traceID | Trace ID,hex 字符串。 |
spanId | spanID | Span ID,hex 字符串。 |
parentSpanId | parentSpanID | 父 Span ID,根 Span 为空。 |
span.name | name | Span 名称。 |
SpanKind | kind | Span 类型。 |
startTime | start | Span 开始时间,纳秒。 |
endTime | end | Span 结束时间,纳秒。 |
endTime - startTime | duration | Span 耗时,纳秒。 |
status.code | statusCode | Span 状态码。 |
status.message | statusMessage | Span 状态说明。 |
attributes | attribute | Span attributes,JSON 字符串。 |
resource.attributes | resource | Resource attributes,JSON 字符串。 |
events / links | logs / links | 可选。如需保留 Span Events 或 Links,可序列化为 JSON 字符串写入。 |
注意事项
start、end、duration 字段需要保持纳秒单位。请勿将这些字段除以 1000 转成微秒,否则耗时会显示为实际值的千分之一。短生命周期脚本退出前需要执行
flush() 或 shutdown(),避免最后一批 Span 未完成上报。访问凭证请通过环境变量或密钥管理工具注入,不要硬编码到代码中。