Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Langfuse SDK best practices, patterns, and idiomatic usage. Use when learning Langfuse SDK patterns, implementing proper tracing, or following best practices for LLM observability. Trigger with phrases like "langfuse patterns", "langfuse best practices", "langfuse SDK guide", "how to use langfuse", "langfuse idioms".
.claude/skills/jeremylongshore-langfuse-sdk-patterns/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-01 | ✗→✓ | ▲ Improved | -15% | 0% |
| case-02 | ✗→✓ | ▲ Improved | 2% | 0% |
| case-03 | ✗→✓ | ▲ Improved | 89% | 0% |
| case-07 | ✗→✓ | ▲ Improved | -35% | 0% |
| case-08 | ✗→✓ | ▲ Improved | 90% | 0% |
Production-quality patterns for the Langfuse SDK: singleton clients, the observe wrapper, startActiveObservation for nested traces, session tracking, graceful shutdown, and error-safe tracing.
langfuse-install-auth setup@langfuse/tracing, @langfuse/otel, @opentelemetry/sdk-nodetypescript// src/lib/langfuse.ts -- single file, import everywhere import { LangfuseClient } from "@langfuse/client"; import { LangfuseSpanProcessor } from "@langfuse/otel"; import { NodeSDK } from "@opentelemetry/sdk-node"; // Singleton client for prompts, datasets, scores let client: LangfuseClient | null = null; export function getLangfuseClient(): LangfuseClient { if (!client) { client = new LangfuseClient(); } return client; } // One-time OTel setup (call at app entry point) let sdk: NodeSDK | null = null; export function initTracing(): NodeSDK { if (!sdk) { sdk = new NodeSDK({ spanProcessors: [new LangfuseSpanProcessor()], }); sdk.start(); // Graceful shutdown on process exit const shutdown = async () => { await sdk?.shutdown(); process.exit(0); }; process.on("SIGTERM", shutdown); process.on("SIGINT", shutdown); } return sdk; }
Legacy v3 singleton:
typescriptimport { Langfuse } from "langfuse"; let instance: Langfuse | null = null; export function getLangfuse(): Langfuse { if (!instance) { instance = new Langfuse({ flushAt: 15, flushInterval: 10000, }); process.on("beforeExit", () => instance?.shutdownAsync()); } return instance; }
observe Wrapper for Existing FunctionsThe observe wrapper is the most ergonomic way to add tracing. It wraps any function and auto-creates a span.
typescriptimport { observe, updateActiveObservation } from "@langfuse/tracing"; // Wrap existing functions -- no internal changes needed const fetchUserProfile = observe(async (userId: string) => { updateActiveObservation({ input: { userId } }); const profile = await db.users.findById(userId); updateActiveObservation({ output: { found: !!profile } }); return profile; }); // Mark LLM calls as generations const summarize = observe( { name: "summarize-text", asType: "generation" }, async (text: string) => { updateActiveObservation({ model: "gpt-4o-mini", input: text }); const result = await openai.chat.completions.create({ model: "gpt-4o-mini", messages: [{ role: "user", content: `Summarize: ${text}` }], }); const output = result.choices[0].message.content; updateActiveObservation({ output, usage: { promptTokens: result.usage?.prompt_tokens, completionTokens: result.usage?.completion_tokens, }, }); return output; } ); // When called inside another observed function, spans auto-nest const pipeline = observe(async (userId: string) => { const profile = await fetchUserProfile(userId); const summary = await summarize(profile.bio); return { profile, summary }; });
startActiveObservation for Inline ControlUse when you need fine-grained control over observation lifecycle within a function:
typescriptimport { startActiveObservation, updateActiveObservation } from "@langfuse/tracing"; async function processOrder(orderId: string) { return await startActiveObservation("process-order", async () => { updateActiveObservation({ input: { orderId } }); // Nested spans are automatic const validated = await startActiveObservation("validate", async () => { const result = await validateOrder(orderId); updateActiveObservation({ output: { valid: result.valid } }); return result; }); if (!validated.valid) { updateActiveObservation({ output: { error: "validation failed" } }); return { success: false }; } // Generation span for LLM call const description = await startActiveObservation( { name: "generate-confirmation", asType: "generation" }, async () => { updateActiveObservation({ model: "gpt-4o-mini" }); const result = await generateConfirmation(orderId); updateActiveObservation({ output: result }); return result; } ); updateActiveObservation({ output: { success: true } }); return { success: true, description }; }); }
Link traces across conversation turns for user-level analytics:
typescript// v4+: Set session/user via observation metadata await startActiveObservation("chat-turn", async () => { updateActiveObservation({ metadata: { sessionId: "session-abc-123", userId: "user-456", }, }); // All nested observations inherit this context await handleUserMessage(message); }); // v3: Set directly on trace const trace = langfuse.trace({ name: "chat-turn", sessionId: "session-abc-123", // Groups traces into a session userId: "user-456", // Links to user analytics input: { message }, });
Never let tracing failures break your application:
typescriptimport { observe, updateActiveObservation } from "@langfuse/tracing"; const safeObserve = <T extends (...args: any[]) => Promise<any>>( name: string, fn: T ): T => { return (async (...args: Parameters<T>) => { try { return await observe({ name }, async () => { updateActiveObservation({ input: args }); const result = await fn(...args); updateActiveObservation({ output: result }); return result; })(); } catch (tracingError) { // If tracing fails, still run the function console.warn(`Tracing error in ${name}:`, tracingError); return fn(...args); } }) as T; }; // Usage -- function works even if Langfuse is down const processRequest = safeObserve("process-request", async (input: string) => { return await callLLM(input); });
typescript// Always use try/finally to ensure .end() is called const span = trace.span({ name: "risky-operation", input: data }); try { const result = await riskyOperation(data); span.end({ output: result }); return result; } catch (error) { span.end({ level: "ERROR", statusMessage: String(error) }); throw error; }
| Anti-Pattern | Problem | Correct Pattern | |-------------|---------|-----------------| | new Langfuse() per request | Memory leaks, duplicate traces | Singleton client | | Awaiting flush in hot path | Adds latency to every request | Background flush, shutdown handler | | Logging full request bodies | Trace payloads too large | Truncate/summarize inputs | | Missing .end() on spans (v3) | Spans show "in progress" forever | Use try/finally or observe wrapper | | Hardcoding API keys | Security risk | Environment variables only |
For OpenAI/LangChain tracing examples, see langfuse-core-workflow-a.
| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-01 | fail→pass | 34,999 | 15,194 | -57% | 1 | 1 | 0% | 4,797 | 4,076 | -15% | 0 | 0 | — |
case-02 | fail→pass | 25,244 | 14,587 | -42% | 1 | 1 | 0% | 3,923 | 4,006 | +2% | 0 | 0 | — |
case-03 | fail→pass | 23,066 | 26,260 | +14% | 1 | 1 | 0% | 3,248 | 6,129 | +89% | 0 | 0 | — |
case-04 | pass→pass | 18,518 | 13,148 | -29% | 1 | 1 | 0% | 2,251 | 3,429 | +52% | 0 | 0 | — |
case-05 | pass→pass | 17,190 | 10,523 | -39% | 1 | 1 | 0% | 2,169 | 2,816 | +30% | 0 | 0 | — |
case-06 | pass→pass | 17,740 | 14,453 | -19% | 1 | 1 | 0% | 2,274 | 3,712 | +63% | 0 | 0 | — |
case-07 | fail→pass | 29,687 | 10,051 | -66% | 1 | 1 | 0% | 4,569 | 2,967 | -35% | 0 | 0 | — |
case-08 | fail→pass | 16,571 | 14,969 | -10% | 1 | 1 | 0% | 2,052 | 3,898 | +90% | 0 | 0 | — |
case-09 | pass→pass | 15,504 | 13,412 | -13% | 1 | 1 | 0% | 1,704 | 3,183 | +87% | 0 | 0 | — |
case-10 | fail→pass | 20,684 | 11,254 | -46% | 1 | 1 | 0% | 2,052 | 2,874 | +40% | 0 | 0 | — |
case-11 | fail→fail | 24,664 | 14,801 | -40% | 1 | 1 | 0% | 2,868 | 3,666 | +28% | 0 | 0 | — |
case-12 | pass→pass | 10,301 | 4,496 | -56% | 1 | 1 | 0% | 1,347 | 2,573 | +91% | 0 | 0 | — |
case-13 | pass→pass | 20,769 | 17,323 | -17% | 1 | 1 | 0% | 2,352 | 3,645 | +55% | 0 | 0 | — |
case-14 | pass→pass | 17,495 | 12,484 | -29% | 1 | 1 | 0% | 2,427 | 3,793 | +56% | 0 | 0 | — |
case-15 | fail→pass | 15,411 | 6,271 | -59% | 1 | 1 | 0% | 1,719 | 2,852 | +66% | 0 | 0 | — |
case-16 | pass→pass | 17,441 | 17,467 | +0% | 1 | 1 | 0% | 2,067 | 3,824 | +85% | 0 | 0 | — |
case-17 | fail→pass | 6,983 | 3,783 | -46% | 1 | 1 | 0% | 1,278 | 2,410 | +89% | 0 | 0 | — |
case-18 | fail→pass | 15,113 | 7,246 | -52% | 1 | 1 | 0% | 1,931 | 3,413 | +77% | 0 | 0 | — |
case-19 | pass→pass | 16,315 | 10,532 | -35% | 1 | 1 | 0% | 1,522 | 2,950 | +94% | 0 | 0 | — |
case-20 | fail→fail | 17,874 | 14,079 | -21% | 1 | 1 | 0% | 1,907 | 3,747 | +96% | 0 | 0 | — |
case-21 | pass→pass | 23,141 | 23,058 | -0% | 1 | 1 | 0% | 2,851 | 4,880 | +71% | 0 | 0 | — |
case-22 | pass→pass | 15,444 | 5,097 | -67% | 1 | 1 | 0% | 1,871 | 2,676 | +43% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 22 cases were attempted. The headline lift of +41 percentage points is the difference between those two pass rates over the 22 comparable cases.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
Other measured skills in the registry, with their headline benchmark lift.