Skip to main content
langfuse-sdk-patterns 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".
跳到安装 Skills Marketplace 发现并探索由社区构建的 Agent Skills
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/jeremylongshore/claude-code-plugins-plus-skills --skill langfuse-sdk-patterns命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
下载 Zip 下载中... 同仓库更多 Skills Implement user sign-up and sign-in flows with Clerk.
Use when building authentication UI, customizing sign-in experience,
or implementing OAuth social login.
Trigger with phrases like "clerk sign-in", "clerk sign-up",
"clerk login flow", "clerk OAuth", "clerk social login".
Implement session management and middleware with Clerk.
Use when managing user sessions, configuring route protection,
or implementing token refresh and custom JWT templates.
Trigger with phrases like "clerk session", "clerk middleware",
"clerk route protection", "clerk token", "clerk JWT".
Configure enterprise SSO, role-based access control, and organization management.
Use when implementing SSO integration, configuring role-based permissions,
or setting up organization-level controls.
Trigger with phrases like "clerk SSO", "clerk RBAC",
"clerk enterprise", "clerk roles", "clerk permissions", "clerk organizations".
jeremylongshore
jeremylongshore/claude-code-plugins-plus-skills
打开 GitHub 仓库 name langfuse-sdk-patterns description 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".
allowed-tools Read, Write, Edit version 1.12.0 license MIT author Jeremy Longshore <jeremy@intentsolutions.io> tags ["saas","langfuse","observability","llm","tracing"] compatibility Designed for Claude Code, also compatible with Codex and OpenClaw
Langfuse SDK Patterns
Overview
Production-quality patterns for the Langfuse SDK: singleton clients, the observe wrapper, startActiveObservation for nested traces, session tracking, graceful shutdown, and error-safe tracing.
Prerequisites
Completed langfuse-install-auth setup
Understanding of async/await patterns
For v4+: @langfuse/tracing, @langfuse/otel, @opentelemetry/sdk-node
Instructions
Pattern 1: Singleton Client with Graceful Shutdown
import { LangfuseClient } from "@langfuse/client" ;
import { LangfuseSpanProcessor } from "@langfuse/otel" ;
import { NodeSDK } from "@opentelemetry/sdk-node" ;
let client : LangfuseClient | null = null ;
export function getLangfuseClient ( ): LangfuseClient {
if (!client) {
client = new LangfuseClient ();
}
return client;
}
let sdk : NodeSDK | null = null ;
export function initTracing ( ): {
(!sdk) {
sdk = ({
: [ ()],
});
sdk. ();
= ( ) => {
sdk?. ();
process. ( );
};
process. ( , shutdown);
process. ( , shutdown);
}
sdk;
}
NodeSDK
if
new
NodeSDK
spanProcessors
new
LangfuseSpanProcessor
start
const
shutdown
async
await
shutdown
exit
0
on
"SIGTERM"
on
"SIGINT"
return
import { 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;
}
Pattern 2: observe Wrapper for Existing Functions The observe wrapper is the most ergonomic way to add tracing. It wraps any function and auto-creates a span.
import { observe, updateActiveObservation } from "@langfuse/tracing" ;
const fetchUserProfile = observe (async (userId : string ) => {
updateActiveObservation ({ input : { userId } });
const profile = await db.users .findById (userId);
updateActiveObservation ({ output : { found : !!profile } });
return profile;
});
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;
}
);
const pipeline = observe (async (userId : string ) => {
const profile = await fetchUserProfile (userId);
const summary = await summarize (profile.bio );
return { profile, summary };
});
Pattern 3: startActiveObservation for Inline Control Use when you need fine-grained control over observation lifecycle within a function:
import { startActiveObservation, updateActiveObservation } from "@langfuse/tracing" ;
async function processOrder (orderId : string ) {
return await startActiveObservation ("process-order" , async () => {
updateActiveObservation ({ input : { orderId } });
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 };
}
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 };
});
}
Pattern 4: Session and User Tracking Link traces across conversation turns for user-level analytics:
await startActiveObservation ("chat-turn" , async () => {
updateActiveObservation ({
metadata : {
sessionId : "session-abc-123" ,
userId : "user-456" ,
},
});
await handleUserMessage (message);
});
const trace = langfuse.trace ({
name : "chat-turn" ,
sessionId : "session-abc-123" ,
userId : "user-456" ,
input : { message },
});
Pattern 5: Error-Safe Tracing Never let tracing failures break your application:
import { 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) {
console .warn (`Tracing error in ${name} :` , tracingError);
return fn (...args);
}
}) as T;
};
const processRequest = safeObserve ("process-request" , async (input : string ) => {
return await callLLM (input);
});
Pattern 6: Legacy v3 -- Always End Spans
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-Patterns to Avoid Anti-Pattern Problem Correct Pattern new Langfuse() per requestMemory 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
Resources
Next Steps For OpenAI/LangChain tracing examples, see langfuse-core-workflow-a.