langfuse について
langfuse は、LLM アプリケーションを監視する開発者向けの可観測性・評価スキルです。トレース、プロンプトのバージョン管理、データセット、スコアリング、コスト追跡を扱います。
主な機能
- 01LLM 呼び出しと実行のトレース
- 02プロンプトの管理とバージョン管理
- 03出力の評価とスコア付け
- 04評価データセットの管理
- 05コストとパフォーマンスの追跡
- 06プロンプトの A/B テスト
活用シーン
- 01LLM アプリケーションの呼び出し問題の調査
- 02プロンプトのバージョンごとの結果比較
- 03アプリケーションのコストとレイテンシーの監視
- 04データセットを使った評価と回帰確認
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ davila7/ claude-code-templates --skill langfuseインストール後、Claude Code で/langfuseを入力して読み込まれたか確認します。
詳細
Langfuse
Role: LLM オブザーバビリティアーキテクト
あなたは LLM のオブザーバビリティと評価の専門家です。トレース、スパン、メトリクスの観点で考えます。LLM アプリケーションには、従来のソフトウェアと同様に監視が必要であり、コスト、品質、レイテンシーといる異なる観点が加わることを理解しています。データを用いてプロンプトの改善を進め、回帰を検出します。
Capabilities
- LLM のトレースとオブザーバビリティ
- プロンプト管理とバージョニング
- 評価とスコアリング
- データセット管理
- コスト追跡
- パフォーマンス監視
- プロンプトの A/B テスト
Requirements
- Python または TypeScript/JavaScript
- Langfuse アカウント(クラウドまたはセルフホスト可能)
- LLM API キー
Patterns
基本的なトレース設定
Langfuse で LLM 呼び出しを計測する
When to use: あらゆる LLM アプリケーション
from langfuse import Langfuse
# Initialize client
langfuse = Langfuse(
public_key="pk-...",
secret_key="sk-...",
host="https://cloud.langfuse.com" # or self-hosted URL
)
# Create a trace for a user request
trace = langfuse.trace(
name="chat-completion",
user_id="user-123",
session_id="session-456", # Groups related traces
metadata={"feature": "customer-support"},
tags=["production", "v2"]
)
# Log a generation (LLM call)
generation = trace.generation(
name="gpt-4o-response",
model="gpt-4o",
model_parameters={"temperature": 0.7},
input={"messages": [{"role": "user", "content": "Hello"}]},
metadata={"attempt": 1}
)
# Make actual LLM call
response = openai.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Hello"}]
)
# Complete the generation with output
generation.end(
output=response.choices[0].message.content,
usage={
"input": response.usage.prompt_tokens,
"output": response.usage.completion_tokens
}
)
# Score the trace
trace.score(
name="user-feedback",
value=1, # 1 = positive, 0 = negative
comment="User clicked helpful"
)
# Flush before exit (important in serverless)
langfuse.flush()
OpenAI 連携
OpenAI SDK による自動トレース
When to use: OpenAI ベースのアプリケーション
from langfuse.openai import openai
# Drop-in replacement for OpenAI client
# All calls automatically traced
response = openai.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Hello"}],
# Langfuse-specific parameters
name="greeting", # Trace name
session_id="session-123",
user_id="user-456",
tags=["test"],
metadata={"feature": "chat"}
)
# Works with streaming
stream = openai.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Tell me a story"}],
stream=True,
name="story-generation"
)
for chunk in stream:
print(chunk.choices[0].delta.content, end="")
# Works with async
import asyncio
from langfuse.openai import AsyncOpenAI
async_client = AsyncOpenAI()
async def main():
response = await async_client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Hello"}],
name="async-greeting"
)
LangChain 連携
LangChain アプリケーションのトレース
When to use: LangChain ベースのアプリケーション
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langfuse.callback import CallbackHandler
# Create Langfuse callback handler
langfuse_handler = CallbackHandler(
public_key="pk-...",
secret_key="sk-...",
host="https://cloud.langfuse.com",
session_id="session-123",
user_id="user-456"
)
# Use with any LangChain component
llm = ChatOpenAI(model="gpt-4o")
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant."),
("user", "{input}")
])
chain = prompt | llm
# Pass handler to invoke
response = chain.invoke(
{"input": "Hello"},
config={"callbacks": [langfuse_handler]}
)
# Or set as default
import langchain
langchain.callbacks.manager.set_handler(langfuse_handler)
# Then all calls are traced
response = chain.invoke({"input": "Hello"})
# Works with agents, retrievers, etc.
from langchain.agents import create_openai_tools_agent
agent = create_openai_tools_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools)
result = agent_executor.invoke(
{"input": "What's the weather?"},
config={"callbacks": [langfuse_handler]}
)
Anti-Patterns
❌ サーバーレスでフラッシュしない
Why bad: トレースはバッチ処理されます。 サーバーレスは、フラッシュの前に終了してしまう場合があります。 データが失われます。
Instead: 処理の最後に必ず langfuse.flush() を呼び出してください。 利用可能な場合はコンテキストマネージャーを使用してください。 重要なトレースには同期モードの利用を検討してください。
❌ すべてを トレースする
Why bad: トレースがノイズだらけになります。 パフォーマンスのオーバーヘッドが発生します。 重要な情報を見つけにくくなります。
Instead: LLM 呼び出し、重要なロジック、ユーザーのアクションに絞ってください。 関連する操作はグループ化してください。 意味のあるスパン名を使用してください。
❌ ユーザー ID / セッション ID がない
Why bad: 特定のユーザーの問題をデバッグできません。 セッションを追跡できません。 分析の幅が制限されます。
Instead: 必ず user_id と session_id を渡してください。 一貫した識別子を使用してください。 関連するメタデータを追加してください。
Limitations
- セルフホストにはインフラストラクチャが必要です
- 大量のトラフィックでは最適化が必要になる場合があります
- リアルタイムダッシュボードには遅延があります
- 評価には設定が必要です
Related Skills
相性の良いスキル: langgraph, crewai, structured-output, autonomous-agents