langfuse-observability
Set up comprehensive observability for Langfuse with metrics, dashboards, and alerts. Use when implementing monitoring for LLM operations, setting up dashboards, or configuring alerting for Langfuse integration health. Trigger with phrases like "langfuse monitoring", "langfuse metrics", "langfuse observability", "monitor langfuse", "langfuse alerts", "langfuse dashboard".
What this skill does
# Langfuse Observability
## Overview
Set up monitoring for your Langfuse integration: Prometheus metrics for trace/generation throughput, Grafana dashboards, alert rules, and integration with Langfuse's built-in analytics dashboards and Metrics API.
## Prerequisites
- Langfuse SDK integrated and producing traces
- For custom metrics: Prometheus + Grafana (or compatible stack)
- For Langfuse analytics: access to the Langfuse UI dashboard
## Instructions
### Step 1: Langfuse Built-In Dashboards
Langfuse provides pre-built dashboards in the UI at `https://cloud.langfuse.com` (or your self-hosted URL):
- **Overview**: Total traces, generations, scores, and errors
- **Cost Dashboard**: Token usage and costs over time, broken down by model, user, session
- **Latency Dashboard**: Response times across models and user segments
- **Custom Dashboards**: Build your own with the query engine (multi-level aggregations, filters by user/model/tag)
**Accessing via Metrics API:**
```typescript
import { LangfuseClient } from "@langfuse/client";
const langfuse = new LangfuseClient();
// Fetch aggregated metrics programmatically
const traces = await langfuse.api.traces.list({
fromTimestamp: new Date(Date.now() - 3600000).toISOString(), // Last hour
limit: 100,
});
console.log(`Traces in last hour: ${traces.data.length}`);
// Get observations with cost data
const observations = await langfuse.api.observations.list({
type: "GENERATION",
fromTimestamp: new Date(Date.now() - 86400000).toISOString(),
limit: 500,
});
const totalCost = observations.data.reduce(
(sum, obs) => sum + (obs.calculatedTotalCost || 0), 0
);
console.log(`Total cost (24h): $${totalCost.toFixed(4)}`);
```
### Step 2: Prometheus Metrics for Your App
Track the health of your Langfuse integration with custom Prometheus metrics:
```typescript
// src/lib/langfuse-metrics.ts
import { Counter, Histogram, Gauge, Registry } from "prom-client";
const registry = new Registry();
export const metrics = {
tracesCreated: new Counter({
name: "langfuse_traces_created_total",
help: "Total traces created",
labelNames: ["status"],
registers: [registry],
}),
generationDuration: new Histogram({
name: "langfuse_generation_duration_seconds",
help: "LLM generation latency",
labelNames: ["model"],
buckets: [0.1, 0.5, 1, 2, 5, 10, 30],
registers: [registry],
}),
tokensUsed: new Counter({
name: "langfuse_tokens_total",
help: "Total tokens used",
labelNames: ["model", "type"],
registers: [registry],
}),
costUsd: new Counter({
name: "langfuse_cost_usd_total",
help: "Total LLM cost in USD",
labelNames: ["model"],
registers: [registry],
}),
flushErrors: new Counter({
name: "langfuse_flush_errors_total",
help: "Total flush/export errors",
registers: [registry],
}),
};
export { registry };
```
```typescript
// src/lib/traced-llm.ts -- Instrumented LLM wrapper
import { observe, updateActiveObservation } from "@langfuse/tracing";
import { metrics } from "./langfuse-metrics";
import OpenAI from "openai";
const openai = new OpenAI();
export const tracedLLM = observe(
{ name: "llm-call", asType: "generation" },
async (model: string, messages: OpenAI.ChatCompletionMessageParam[]) => {
const start = Date.now();
updateActiveObservation({ model, input: messages });
try {
const response = await openai.chat.completions.create({ model, messages });
const duration = (Date.now() - start) / 1000;
metrics.generationDuration.observe({ model }, duration);
metrics.tracesCreated.inc({ status: "success" });
if (response.usage) {
metrics.tokensUsed.inc({ model, type: "prompt" }, response.usage.prompt_tokens);
metrics.tokensUsed.inc({ model, type: "completion" }, response.usage.completion_tokens);
}
updateActiveObservation({
output: response.choices[0].message.content,
usage: {
promptTokens: response.usage?.prompt_tokens,
completionTokens: response.usage?.completion_tokens,
},
});
return response.choices[0].message.content;
} catch (error) {
metrics.tracesCreated.inc({ status: "error" });
throw error;
}
}
);
```
### Step 3: Expose Metrics Endpoint
```typescript
// src/routes/metrics.ts
import { registry } from "../lib/langfuse-metrics";
app.get("/metrics", async (req, res) => {
res.set("Content-Type", registry.contentType);
res.end(await registry.metrics());
});
```
### Step 4: Prometheus Scrape Config
```yaml
# prometheus.yml
scrape_configs:
- job_name: "llm-app"
scrape_interval: 15s
static_configs:
- targets: ["llm-app:3000"]
```
### Step 5: Grafana Dashboard
```json
{
"panels": [
{
"title": "LLM Requests/min",
"type": "graph",
"targets": [{ "expr": "rate(langfuse_traces_created_total[5m]) * 60" }]
},
{
"title": "Generation Latency P95",
"type": "graph",
"targets": [{ "expr": "histogram_quantile(0.95, rate(langfuse_generation_duration_seconds_bucket[5m]))" }]
},
{
"title": "Cost/Hour",
"type": "stat",
"targets": [{ "expr": "rate(langfuse_cost_usd_total[1h]) * 3600" }]
},
{
"title": "Error Rate",
"type": "graph",
"targets": [{ "expr": "rate(langfuse_traces_created_total{status='error'}[5m]) / rate(langfuse_traces_created_total[5m])" }]
}
]
}
```
### Step 6: Alert Rules
```yaml
# alertmanager-rules.yml
groups:
- name: langfuse
rules:
- alert: HighLLMErrorRate
expr: rate(langfuse_traces_created_total{status="error"}[5m]) / rate(langfuse_traces_created_total[5m]) > 0.05
for: 5m
labels: { severity: critical }
annotations:
summary: "LLM error rate above 5%"
- alert: HighLLMLatency
expr: histogram_quantile(0.95, rate(langfuse_generation_duration_seconds_bucket[5m])) > 10
for: 5m
labels: { severity: warning }
annotations:
summary: "LLM P95 latency above 10s"
- alert: HighDailyCost
expr: rate(langfuse_cost_usd_total[1h]) * 24 > 100
for: 15m
labels: { severity: warning }
annotations:
summary: "Projected daily LLM cost exceeds $100"
```
## Key Metrics Reference
| Metric | Type | Purpose |
|--------|------|---------|
| `langfuse_traces_created_total` | Counter | LLM request throughput + error rate |
| `langfuse_generation_duration_seconds` | Histogram | Latency percentiles |
| `langfuse_tokens_total` | Counter | Token usage tracking |
| `langfuse_cost_usd_total` | Counter | Budget monitoring |
| `langfuse_flush_errors_total` | Counter | SDK health |
## Error Handling
| Issue | Cause | Solution |
|-------|-------|----------|
| Missing metrics | No instrumentation | Use the `tracedLLM` wrapper |
| High cardinality | Too many label values | Limit to model + status only |
| Alert storms | Thresholds too low | Start conservative, tune over time |
| Metrics endpoint slow | Large registry | Use summary instead of histogram for high-volume |
## Resources
- [Langfuse Metrics Overview](https://langfuse.com/docs/metrics/overview)
- [Custom Dashboards](https://langfuse.com/docs/metrics/features/custom-dashboards)
- [Metrics API](https://langfuse.com/docs/metrics/features/metrics-api)
- [Token & Cost Tracking](https://langfuse.com/docs/observability/features/token-and-cost-tracking)
Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.