pattern/observability/llm-observability
- Bun
- ClickHouse
- Langfuse
- Langfuse OTel processor
- Langfuse Worker
- Langfuse client
- Langfuse tracing
- OpenTelemetry SDK
- PostgreSQL
- Redis
- SeaweedFS
- TypeScript
- Docker
Cada uso de LLM vira trace no Langfuse: generation com modelo, parâmetros e tokens, e score de qualidade preso ao trace.
pattern/observability/llm-observability
Cenário
Triagem de PIX por LLM: resposta fora do contrato ("risk": "elevated") recebe score 0; o CPF nunca chega ao Langfuse.
Planta
Sequência4 passos — reproduza para seguir o fluxo
Como funciona
4passos
Cada uso de LLM vira trace no Langfuse com modelo, parâmetros, tokens e score de qualidade
Esconde cada passo: lembre antes de tocar para revelar.
LangfuseSpanProcessor com mask que troca o CPF em todo export
propagateAttributes herda conta (userId) e PIX (sessionId)
Chamada ao modelo = generation com tokens
Score 1 se risco e ação no contrato, senão 0; a demo lê o trace pela API
Trade-offs
O que se ganha, o que se paga
Vantagens
Resposta explicável: entrada, tokens, score
Score aponta regressão cedo
Custos
Seis serviços para operar ou custo de SaaS
Mede só o que o contrato define
Código
pattern/observability/llm-observability
6 arquivos./
src/
Executar com Docker
docker compose up -d --wait# sobe ClickHouse · Langfuse · PostgreSQL · Redisbun install# dependênciasbun run demo# roda o cenáriodocker compose down -vSaída: dois traces lidos de volta: low/approve com score 1 e elevated/block com score 0, ambos com 129 tokens e payer [CPF] (CPF mascarado).
UI: http://localhost:3000 (dev@local.test / local-dev-password). O primeiro boot roda as migrações.
Código
src/demo.ts// Demo: each PIX triaged by an LLM becomes one Langfuse trace — generation with model and tokens, plus a contract score — exported with the payer's CPF masked and read back from the public API.
import { LangfuseClient } from "@langfuse/client";
import { LangfuseSpanProcessor } from "@langfuse/otel";
import { propagateAttributes, startObservation } from "@langfuse/tracing";
import { NodeSDK } from "@opentelemetry/sdk-node";
// The keys match the LANGFUSE_INIT_* values of docker-compose.yml, so the stack boots provisioned.
const LANGFUSE = {
publicKey: Bun.env.LLM_OBSERVABILITY_LANGFUSE_PUBLIC_KEY ?? "pk-lf-local-demo",
secretKey: Bun.env.LLM_OBSERVABILITY_LANGFUSE_SECRET_KEY ?? "sk-lf-local-demo",
baseUrl: Bun.env.LLM_OBSERVABILITY_LANGFUSE_BASE_URL ?? "http://localhost:3000",
};
// Masking runs in the span processor, on everything exported: masking at each call site leaks whatever someone forgot.
const piiMask = (data: unknown): unknown => (typeof data === "string" ? data.replaceAll(/\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g, "[CPF]") : data !== null && typeof data === "object" ? JSON.parse(piiMask(JSON.stringify(data)) as string) : data);
const processor = new LangfuseSpanProcessor({ ...LANGFUSE, mask: ({ data }) => piiMask(data) });
const sdk = new NodeSDK({ spanProcessors: [processor] });
sdk.start();
const langfuse = new LangfuseClient(LANGFUSE);
type Transfer = { pixId: string; accountId: string; amountCents: number; payerDocument: string; disputesLast90Days: number };
// The contract the downstream code handles: anything else scores 0 and points at a model or prompt regression.
const VERDICT_RISKS = new Set(["low", "medium", "high"]);
const VERDICT_ACTIONS = new Set(["approve", "step_up_authentication", "hold_for_review"]);
// Stand-in for the LLM provider, deterministic so the output is stable; the second answer drifts off contract.
const modelChat = (transfer: Transfer) => {
const content = JSON.stringify(transfer.disputesLast90Days === 0 ? { risk: "low", action: "approve" } : { risk: "elevated", action: "block" });
return { content, usage: { input: 120, output: Math.ceil(content.length / 4) } };
};
// One PIX is one trace; account and PIX ride on every observation as userId and sessionId.
const transferTriage = (transfer: Transfer) =>
propagateAttributes({ userId: transfer.accountId, sessionId: transfer.pixId }, () => {
const trace = startObservation("pix-fraud-triage", { input: transfer });
const generation = trace.startObservation("fraud-verdict", { model: "fraud-triage-1", modelParameters: { temperature: 0 }, input: transfer }, { asType: "generation" });
const answer = modelChat(transfer);
generation.update({ output: answer.content, usageDetails: answer.usage }).end();
const verdict = JSON.parse(answer.content) as { risk: string; action: string };
const wellFormed = VERDICT_RISKS.has(verdict.risk) && VERDICT_ACTIONS.has(verdict.action);
langfuse.score.create({ traceId: trace.traceId, name: "verdict-contract", value: wellFormed ? 1 : 0 });
trace.update({ output: verdict }).end();
return trace.traceId;
});
const traceIds = [
transferTriage({ pixId: "PIX-9001", accountId: "0001-5", amountCents: 32_000, payerDocument: "123.456.789-09", disputesLast90Days: 0 }),
transferTriage({ pixId: "PIX-9003", accountId: "0003-1", amountCents: 45_000, payerDocument: "111.222.333-44", disputesLast90Days: 1 }),
];
await Promise.all([processor.forceFlush(), langfuse.score.flush()]);
await sdk.shutdown();
type TraceRead = { input: { payerDocument: string }; output: object; observations: { type: string; usageDetails: object }[]; scores: { value: number }[] };
// Langfuse ingests asynchronously: read until the trace has its generation and score.
const authorization = `Basic ${btoa(`${LANGFUSE.publicKey}:${LANGFUSE.secretKey}`)}`;
for (const traceId of traceIds) {
let trace: TraceRead | undefined;
while (!trace?.scores.length || !trace.observations.length) {
await Bun.sleep(500);
const response = await fetch(`${LANGFUSE.baseUrl}/api/public/traces/${traceId}`, { headers: { authorization } });
trace = response.ok ? ((await response.json()) as TraceRead) : undefined;
}
const generation = trace.observations.find((observation) => observation.type === "GENERATION");
console.log(` [LANGFUSE] ${JSON.stringify(trace.output)} tokens ${JSON.stringify(generation?.usageDetails)} score ${trace.scores[0]?.value} payer ${trace.input.payerDocument}`);
}
Nível
avançado
13/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
Langfuseobservabilidade de LLM
langfuse/langfuse:3:3000
Langfuse Workerobservabilidade de LLM
langfuse/langfuse-worker:3
PostgreSQLbanco relacional
postgres:16-alpine
ClickHousebanco colunar
clickhouse/clickhouse-server:24.3
Rediscache / estrutura de dados
redis:7-alpine
MinIOobject storage S3
bitnamilegacy/minio:2025.7.23
Variáveis de ambiente
Por que se relacionam
Teste rápido
Qual destes combina com LLM Observability?
Custo e latência medidos contra a meta. Abrir Métricas, SLI, SLO e SLA
Seu progresso
0/157 estudados
Fica salvo só neste navegador.