概述

此示例演示了如何通过 OpenLIT 使用 Langfuse 来追踪模型调用。

代码

import base64
import os

from agno.agent import Agent
from agno.models.openai import OpenAIChat
from agno.tools.duckduckgo import DuckDuckGoTools

LANGFUSE_AUTH = base64.b64encode(
    f"{os.getenv('LANGFUSE_PUBLIC_KEY')}:{os.getenv('LANGFUSE_SECRET_KEY')}".encode()
).decode()

os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = (
    "https://us.cloud.langfuse.com/api/public/otel"  # 🇺🇸 US data region
)
# os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"]="https://cloud.langfuse.com/api/public/otel" # 🇪🇺 EU data region
# os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"]="http://localhost:3000/api/public/otel" # 🏠 Local deployment (>= v3.22.0)

os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = f"Authorization=Basic {LANGFUSE_AUTH}"

from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor

trace_provider = TracerProvider()
trace_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter()))

# Sets the global default tracer provider
from opentelemetry import trace

trace.set_tracer_provider(trace_provider)

# Creates a tracer from the global tracer provider
tracer = trace.get_tracer(__name__)

import openlit

# Initialize OpenLIT instrumentation. The disable_batch flag is set to true to process traces immediately.
openlit.init(tracer=tracer, disable_batch=True)

agent = Agent(
    model=OpenAIChat(id="gpt-4o-mini"),
    tools=[DuckDuckGoTools()],
    markdown=True,
    debug_mode=True,
)

agent.print_response("What is currently trending on Twitter?")

使用方法

1

安装依赖

pip install agno openai langfuse openlit opentelemetry-sdk opentelemetry-exporter-otlp
2

设置环境变量

export LANGFUSE_PUBLIC_KEY=<你的公共密钥>
export LANGFUSE_SECRET_KEY=<你的密钥>
3

运行 Agent

python cookbook/observability/langfuse_via_openlit.py

注意事项

  • 数据区域: 根据需要调整 OTEL_EXPORTER_OTLP_ENDPOINT 以匹配您的数据区域或本地部署:
    • https://us.cloud.langfuse.com/api/public/otel 适用于美国区域
    • https://cloud.langfuse.com/api/public/otel 适用于欧盟区域
    • http://localhost:3000/api/public/otel 适用于本地部署