langfuse-data-handling
Manage Langfuse data export, retention, and compliance requirements. Use when exporting trace data, configuring retention policies, or implementing data compliance for LLM observability. Trigger with phrases like "langfuse data export", "langfuse retention", "langfuse GDPR", "langfuse compliance", "export langfuse traces".
What this skill does
# Langfuse Data Handling
## Overview
Manage the Langfuse data lifecycle: export traces and scores via the API, configure retention policies, handle GDPR data subject requests, anonymize data for analytics, and maintain audit trails.
## Prerequisites
- `@langfuse/client` installed
- Langfuse API keys with appropriate permissions
- Understanding of your compliance requirements (GDPR, SOC2, HIPAA)
## Instructions
### Step 1: Export Trace Data via API
```typescript
import { LangfuseClient } from "@langfuse/client";
import { writeFileSync } from "fs";
const langfuse = new LangfuseClient();
async function exportTraces(options: {
fromDate: string;
toDate: string;
outputFile: string;
includeObservations?: boolean;
}) {
const allTraces: any[] = [];
let page = 1;
let hasMore = true;
while (hasMore) {
const result = await langfuse.api.traces.list({
fromTimestamp: options.fromDate,
toTimestamp: options.toDate,
limit: 100,
page,
});
for (const trace of result.data) {
const exportItem: any = {
id: trace.id,
name: trace.name,
timestamp: trace.timestamp,
userId: trace.userId,
sessionId: trace.sessionId,
metadata: trace.metadata,
tags: trace.tags,
};
if (options.includeObservations) {
const observations = await langfuse.api.observations.list({
traceId: trace.id,
});
exportItem.observations = observations.data;
}
allTraces.push(exportItem);
}
hasMore = result.data.length === 100;
page++;
// Rate limit respect
await new Promise((r) => setTimeout(r, 200));
}
writeFileSync(options.outputFile, JSON.stringify(allTraces, null, 2));
console.log(`Exported ${allTraces.length} traces to ${options.outputFile}`);
}
// Usage
await exportTraces({
fromDate: "2025-01-01T00:00:00Z",
toDate: "2025-01-31T23:59:59Z",
outputFile: "traces-january.json",
includeObservations: true,
});
```
### Step 2: Export Scores
```typescript
async function exportScores(fromDate: string, outputFile: string) {
const scores: any[] = [];
let page = 1;
let hasMore = true;
while (hasMore) {
const result = await langfuse.api.scores.list({
fromTimestamp: fromDate,
limit: 100,
page,
});
scores.push(...result.data);
hasMore = result.data.length === 100;
page++;
await new Promise((r) => setTimeout(r, 200));
}
writeFileSync(outputFile, JSON.stringify(scores, null, 2));
console.log(`Exported ${scores.length} scores to ${outputFile}`);
}
```
### Step 3: Data Retention Configuration
**Self-hosted: Set retention via environment variable:**
```yaml
# docker-compose.yml
services:
langfuse:
environment:
- LANGFUSE_RETENTION_DAYS=90
```
**Cloud: Programmatic cleanup of old data:**
```typescript
async function enforceRetention(maxAgeDays: number) {
const cutoff = new Date(Date.now() - maxAgeDays * 86400000).toISOString();
const oldTraces = await langfuse.api.traces.list({
toTimestamp: cutoff,
limit: 100,
});
console.log(`Found ${oldTraces.data.length} traces older than ${maxAgeDays} days`);
for (const trace of oldTraces.data) {
await langfuse.api.traces.delete(trace.id);
await new Promise((r) => setTimeout(r, 100)); // Rate limit
}
}
// Run as cron job
await enforceRetention(90);
```
### Step 4: GDPR Data Subject Requests
```typescript
// Handle "Right to Access" -- export all data for a user
async function handleAccessRequest(userId: string) {
const traces = await langfuse.api.traces.list({
userId,
limit: 1000,
});
const userData = {
userId,
exportDate: new Date().toISOString(),
traceCount: traces.data.length,
traces: traces.data.map((t) => ({
id: t.id,
name: t.name,
timestamp: t.timestamp,
input: t.input,
output: t.output,
metadata: t.metadata,
})),
};
writeFileSync(`gdpr-export-${userId}.json`, JSON.stringify(userData, null, 2));
return userData;
}
// Handle "Right to Erasure" -- delete all data for a user
async function handleDeletionRequest(userId: string) {
const traces = await langfuse.api.traces.list({
userId,
limit: 1000,
});
let deleted = 0;
for (const trace of traces.data) {
await langfuse.api.traces.delete(trace.id);
deleted++;
await new Promise((r) => setTimeout(r, 100));
}
console.log(`Deleted ${deleted} traces for user ${userId}`);
return { userId, tracesDeleted: deleted };
}
```
### Step 5: Data Anonymization for Analytics
```typescript
import crypto from "crypto";
function anonymizeTrace(trace: any): any {
return {
...trace,
userId: trace.userId ? crypto.createHash("sha256").update(trace.userId).digest("hex").slice(0, 16) : null,
sessionId: trace.sessionId ? crypto.createHash("sha256").update(trace.sessionId).digest("hex").slice(0, 16) : null,
input: "[REDACTED]",
output: "[REDACTED]",
metadata: {
model: trace.metadata?.model,
// Keep operational fields, remove PII
},
};
}
async function exportAnonymized(fromDate: string, outputFile: string) {
const traces = await langfuse.api.traces.list({
fromTimestamp: fromDate,
limit: 1000,
});
const anonymized = traces.data.map(anonymizeTrace);
writeFileSync(outputFile, JSON.stringify(anonymized, null, 2));
}
```
## Data Categories and Retention
| Category | Contains PII? | Default Retention | Compliance Note |
|----------|--------------|-------------------|-----------------|
| Traces (inputs/outputs) | Likely | 90 days | Scrub PII before tracing |
| Generations (LLM I/O) | Likely | 90 days | May contain user data |
| Scores | Rarely | 1 year | Typically safe to retain |
| Sessions | User ID linked | 90 days | Link to user data requests |
| Prompts | No | Indefinite | Template data only |
| Datasets | Maybe | Per use case | Review test data for PII |
## Error Handling
| Issue | Cause | Solution |
|-------|-------|----------|
| Export timeout | Too many traces | Reduce date range, use pagination |
| Missing user data | Different userId format | Verify exact userId used in traces |
| Deletion not immediate | Async processing | Allow time for propagation |
| Rate limited during export | Too many API calls | Add 200ms delay between pages |
## Resources
- [Langfuse Data Security](https://langfuse.com/docs/data-security-privacy)
- [Public API Reference](https://langfuse.com/docs/api)
- [API Reference (OpenAPI)](https://api.reference.langfuse.com/)
- [Self-Hosting Configuration](https://langfuse.com/self-hosting/configuration)
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.