アクセス方法 | データパス | 推奨シナリオ |
OTLP/HTTP標準直接転送 | アプリケーション > 標準OTLP HTTP Exporter > CLS | 手動接続を推奨します。新規プロジェクト、迅速な試用、カスタムコードの削減、OpenTelemetry 標準セマンティクスに従って Trace を報告するシナリオに適しています。 |
topic_id header、フィールドマッピング、時間単位、終了flush、検証説明の処理が可能です。また、報告データに基づくエラー診断、パフォーマンス、Tokenコスト、ユーザーセッションなどの多次元分析もサポートします。パラメータ | 説明 |
CLS_DEFAULT_REGION | |
TENCENTCLOUD_SECRET_ID | Tencent Cloudアクセス認証情報SecretId。 |
TENCENTCLOUD_SECRET_KEY | Tencent Cloudアクセス認証情報SecretKey。 |
Tencent Cloud Agent可観測性アクセスアシスタントSkillを使用してください:https://skillhub.cn/skills/tencentcloud-cls-agent-obs現在のプロジェクトをTencent Cloud Agent可観測性に接続してください。アクセス方式:Langfuse地域:ap-guangzhou(実際の地域に置き換えてください)
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
CLS_ENDPOINTを個別に設定する必要はありません。EndpointはCLS_DEFAULT_REGIONから自動的に組み立てられます。リージョン | パブリックエンドポイント | プライベートエンドポイント |
広州 | 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 |
https://{CLS_DEFAULT_REGION}.cls.tencentcs.com/v1/tracesです。npm install @langfuse/tracing @langfuse/otel @langfuse/openai \\@opentelemetry/sdk-node \\@opentelemetry/exporter-trace-otlp-http \\dotenv
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();});
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();
pip install langfuse opentelemetry-sdk opentelemetry-exporter-otlp python-dotenv
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)
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に基づいてサンプリングするかどうかを決定します。 | 分散トレース環境において、トレース全体でサンプリングの一貫性を確保します。 |
npm install @opentelemetry/sdk-trace-base
import {ParentBasedSampler,TraceIdRatioBasedSampler,} from "@opentelemetry/sdk-trace-base";export const sdk = new NodeSDK({sampler: new ParentBasedSampler({root: new TraceIdRatioBasedSampler(0.1),}),// 他の設定は変更しません。});
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")}))
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", # ソースリージョン識別子},)
url: `http://${region}.cls.tencentcs.com/v1/traces`,
OTLPSpanExporter(endpoint=f"http://{region}.cls.tencentcs.com/v1/traces",insecure=True, # テスト環境のみ# ...)

* | 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
resource、scope、spanなどの情報はOpenTelemetry標準プロトコル構造に従って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で割ってマイクロ秒に変換しないでください。そうしないと、処理時間は実際の値の1000分の1として表示されます。flush()またはshutdown()を実行し、最後の一批のSpanが未報告のままになるのを防ぐ必要があります。フィードバック