Agent skill

Langfuse SDK Patterns

by jeremylongshore in jeremylongshore/tons-of-skills-marketplace

Langfuse SDK best practices, patterns, and idiomatic usage. An agent skill from jeremylongshore/tons-of-skills-marketplace.

MITAuto-check passedAI & LLM Engineering

Install Langfuse SDK Patterns

skills CLI
$ npx skills add jeremylongshore/tons-of-skills-marketplace --skill langfuse-sdk-patterns -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install jeremylongshore/tons-of-skills-marketplace langfuse-sdk-patterns --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/jeremylongshore/tons-of-skills-marketplace.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/.curated/langfuse-sdk-patterns .claude/skills/langfuse-sdk-patterns && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
langfuse-sdk-patterns
GitHub stars
2.8k
Token cost
~2.3k tokens
SKILL.md length
397 words
Files
2 (incl. references)
Skills in repo
3,342
Repo updated
First seen
Licence
MIT

At a glance

Langfuse SDK best practices, patterns, and idiomatic usage. An agent skill from jeremylongshore/tons-of-skills-marketplace.

  • Learning Langfuse SDK patterns
  • SKILL.md covers Overview, Prerequisites, Instructions and Anti-Patterns to Avoid, plus 5 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md
  • Implementing proper tracing

What it does

Langfuse SDK Patterns is an agent skill from jeremylongshore/tons-of-skills-marketplace. 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".

Its SKILL.md is about 2.3k tokens, which your agent loads only when the skill is triggered. The skill folder holds 2 other files, including reference files (for example `references/implementation.md`). Compatibility notes: Designed for Claude Code

It sits in AI & LLM Engineering, covering LLM observability. It works with Langfuse and OpenTelemetry. The repository describes itself as: Model-agnostic agent-skills platform with a harness-free canonical layer, verified adapters, and the ccpi package manager. Explore at tonsofskills.com. The licence is MIT.

When your agent uses it

  • Learning Langfuse SDK patterns
  • Implementing proper tracing
  • Following best practices for LLM observability
  • With phrases like langfuse patterns

Example prompts

  • “langfuse patterns”
  • “langfuse best practices”
  • “langfuse SDK guide”
  • “/langfuse-sdk-patterns”

Requirements

  • Python 3
  • Compatibility (from SKILL.md): Designed for Claude Code
  • Pre-approved tools (allowed-tools): Read, Write, Edit

What it can do on your machine

Read from SKILL.md and the folder at commit 80f86df. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read
    • Write
    • Edit

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are typescript).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Links to these hosts (documentation or services it may open):

    • langfuse.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

  • Compatibility

    Designed for Claude Code

    From compatibility in the SKILL.md frontmatter.

Context cost

Langfuse SDK Patterns loads about 2.3k tokens when it runs, and up to ~3.5k if it reads all its reference files. Until then it costs about 85 tokens; SKILL.md has 397 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~85
When it runs · the whole SKILL.md, loaded when a task matches
~2.3k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~3.5k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from jeremylongshore/tons-of-skills-marketplace at commit 80f86df, republished under its MIT licence (© jeremylongshore). 397 words, ~2,342 tokens.

Download SKILL.mdSave it as .claude/skills/langfuse-sdk-patterns/SKILL.md (or your agent's skills folder). This skill also uses 1 other file; get the full folder from 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
compatibility
Designed for Claude Code
version
1.17.0
license
MIT
author
Jeremy Longshore <jeremy@intentsolutions.io>
tags
saas, langfuse, observability, llm, tracing

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
typescript
// 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:

typescript
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.

typescript
import { 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 };
});
Pattern 3: startActiveObservation for Inline Control

Use when you need fine-grained control over observation lifecycle within a function:

typescript
import { 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 };
  });
}
Pattern 4: Session and User Tracking

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 },
});
Pattern 5: Error-Safe Tracing

Never let tracing failures break your application:

typescript
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) {
      // 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);
});
Pattern 6: Legacy v3 -- Always End Spans
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-Patterns to Avoid

Anti-PatternProblemCorrect Pattern
new Langfuse() per requestMemory leaks, duplicate tracesSingleton client
Awaiting flush in hot pathAdds latency to every requestBackground flush, shutdown handler
Logging full request bodiesTrace payloads too largeTruncate/summarize inputs
Missing .end() on spans (v3)Spans show "in progress" foreverUse try/finally or observe wrapper
Hardcoding API keysSecurity riskEnvironment variables only

Output

Use this skill to produce a small integration plan and implementation diff: one process-lifetime client, trace and observation names that describe the user operation, safe input/output capture, and a shutdown path that drains pending events. Record the SDK generation assumed by the code so a future upgrade does not mix v3 span APIs with the v4+ OpenTelemetry APIs.

Show full SKILL.md (148 more words)Show less

Error Handling

Treat observability as non-critical infrastructure. A tracing export failure must be logged with enough context to diagnose it, but it must not replace or mask the application result. Avoid retrying a failed user operation merely to emit telemetry; instead rely on the SDK queue and alert on sustained export failures. Confirm legacy spans are ended in a finally block so an exception does not leave a permanently in-progress trace.

Examples

For a request handler, create an active observation named checkout-request, attach a bounded summary of the request, call the business function once, then attach its result summary. On process shutdown, await the tracing SDK shutdown before closing the HTTP server. This gives one trace per request without adding an extra network call to the request's success path.

Resources

Next Steps

For OpenAI/LangChain tracing examples, see langfuse-core-workflow-a.

© jeremylongshore, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 1 other file (references) in skills/.curated/langfuse-sdk-patterns of jeremylongshore/tons-of-skills-marketplace.

  • SKILL.md
  • references/implementation.md

Open the folder on GitHubat commit 80f86df

Compare with similar skills

Langfuse SDK Patterns next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Langfuse SDK Patterns compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Langfuse SDK Patterns this skilljeremylongshore/tons-of-skills-marketplace2.8k—~2.3kAutomated safety check: PassMIT
Agentsop Observability Setupagentsope/SkillAlchemy466—~4.4kAutomated safety check: PassMIT
Olore Langfuse Latestolorehq/olore104—~1.2kAutomated safety check: PassMIT
Telemetry AnalyzerIBM/ibm-watsonx-orchestrate-adk178—~10kAutomated safety check: NotesMIT
Ak Dev New Tracing Provideryaalalabs/agent-kernel192—~3.5kAutomated safety check: PassApache-2.0
Backend Dev Guidelineslangfuse/langfuse36k—~1.9kAutomated safety check: PassCustom licence

Similar skills

  • Agentsop Observability Setup

    agentsope/SkillAlchemy

    Enhancement-overlay skill — the DECISION + WIRING layer for LM observability that the single-backend skills [[langsmith]], [[phoenix]], [[mlflow]] do NOT cover.

    466 GitHub stars~4.4k tokensUpdated yesterday
    AI & LLM EngineeringAuto-check passed
  • Local Langfuse documentation reference (latest). An agent skill from olorehq/olore.

    104 GitHub stars~1.2k tokensUpdated today
    AI & LLM EngineeringAuto-check passed
  • Telemetry Analyzer

    IBM/ibm-watsonx-orchestrate-adk

    Official

    A skill your agent uses when the user wants to analyze agent telemetry traces to find bugs and get fix recommendations — walks through exporting traces from a local or remote watsonx Orchestrate…

    178 GitHub stars~10k tokensUpdated 2 days ago
    DevelopmentAuto-check: notes
  • Ak Dev New Tracing Provider

    yaalalabs/agent-kernel

    Step-by-step guide for adding a new observability/tracing provider to Agent Kernel.

    192 GitHub stars~3.5k tokensUpdated today
    DevOps & CloudAuto-check passed
  • Backend Dev Guidelines

    langfuse/langfuse

    Build or review Langfuse backend code. An agent skill from langfuse/langfuse.

    36k GitHub stars~1.9k tokensUpdated today
    Backend & APIsAuto-check passed
  • Ag2 Telemetry

    ag2ai/build-with-ag2

    Add OpenTelemetry traces to an AG2 beta Agent via TelemetryMiddleware (autogen.beta.middleware.builtin).

    252 GitHub stars~1.9k tokensUpdated 1 mo ago
    DevOps & CloudAuto-check passed

More from jeremylongshore/tons-of-skills-marketplace

All 3,342 skills in this repo
  • Performing Security Code Review

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill enables AI assistant to conduct a security-focused code review using the security-agent plugin.

    2.8k GitHub starsUsed in 2 repos~1.3k tokens
    Auto-check: notes
  • Adapting Transfer Learning Models

    jeremylongshore/tons-of-skills-marketplace

    Build this skill automates the adaptation of pre-trained machine learning models using transfer learning techniques.

    2.8k GitHub stars~1.1k tokensUpdated yesterday
    Auto-check passed
  • Agent Context Loader

    jeremylongshore/tons-of-skills-marketplace

    Execute proactive auto-loading: automatically detects and loads agents.md files.

    2.8k GitHub stars~1.1k tokensUpdated yesterday
    Auto-check passed
  • Aggregating Performance Metrics

    jeremylongshore/tons-of-skills-marketplace

    Aggregate and centralize performance metrics from applications, systems, databases, caches, and services.

    2.8k GitHub stars~1.2k tokensUpdated yesterday
    Auto-check passed
  • Analyzing Capacity Planning

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill enables AI assistant to analyze capacity requirements and plan for future growth.

    2.8k GitHub stars~947 tokensUpdated yesterday
    Auto-check passed
  • Analyzing Database Indexes

    jeremylongshore/tons-of-skills-marketplace

    Process use when you need to work with database indexing. An agent skill from jeremylongshore/tons-of-skills-marketplace.

    2.8k GitHub stars~2k tokensUpdated yesterday
    Auto-check passed

Questions about Langfuse SDK Patterns

What does Langfuse SDK Patterns do?

Langfuse SDK best practices, patterns, and idiomatic usage. An agent skill from jeremylongshore/tons-of-skills-marketplace. Langfuse SDK Patterns is an agent skill from jeremylongshore/tons-of-skills-marketplace. Langfuse SDK best practices, patterns, and idiomatic usage.

When should I use Langfuse SDK Patterns?

Langfuse SDK Patterns fits situations like: learning Langfuse SDK patterns; implementing proper tracing; following best practices for LLM observability; with phrases like langfuse patterns.

How do I install Langfuse SDK Patterns in Claude Code?

Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill langfuse-sdk-patterns -a claude-code`. Or copy the skill folder (skills/.curated/langfuse-sdk-patterns in jeremylongshore/tons-of-skills-marketplace) into .claude/skills/langfuse-sdk-patterns in your project. Claude Code loads it when a task matches its description.

How do I install Langfuse SDK Patterns in Codex?

Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill langfuse-sdk-patterns -a codex`. Or copy the skill folder (skills/.curated/langfuse-sdk-patterns in jeremylongshore/tons-of-skills-marketplace) into .agents/skills/langfuse-sdk-patterns in your project. Codex loads it when a task matches its description.

Can I use Langfuse SDK Patterns in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill langfuse-sdk-patterns -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/langfuse-sdk-patterns, .gemini/skills/langfuse-sdk-patterns, .github/skills/langfuse-sdk-patterns and .opencode/skills/langfuse-sdk-patterns in your project.

What does Langfuse SDK Patterns need to run?

SKILL.md names no scripts, command-line tools or credentials: Langfuse SDK Patterns is instructions for the agent only. Our summary lists: Python 3. Its frontmatter pre-approves these tools: Read, Write, Edit. Compatibility (from SKILL.md): Designed for Claude Code.

Does Langfuse SDK Patterns access the network?

SKILL.md names 1 domain. As links in the text: langfuse.com. This is read from the text; nothing was executed.

Is Langfuse SDK Patterns safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Langfuse SDK Patterns use?

Langfuse SDK Patterns is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Langfuse SDK Patterns use?

About 2.3k tokens (SKILL.md is roughly 9.4k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 1.2k tokens, read only when the agent opens those files.

What are the alternatives to Langfuse SDK Patterns?

Skills that share tags, products or a category with Langfuse SDK Patterns: Agentsop Observability Setup (agentsope/SkillAlchemy, 466 stars), Olore Langfuse Latest (olorehq/olore, 104 stars), Telemetry Analyzer (IBM/ibm-watsonx-orchestrate-adk, 178 stars) and Ak Dev New Tracing Provider (yaalalabs/agent-kernel, 192 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Langfuse SDK Patterns?

jeremylongshore (a GitHub user) maintains it in jeremylongshore/tons-of-skills-marketplace, which has 2,825 GitHub stars. The repository holds 3,342 skills in this directory. The repository was last updated on October 9, 2026.

Source: jeremylongshore/tons-of-skills-marketplace on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.