Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions docs-site/static/search-index.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion docs/api/classes/ExporterSpanProcessor.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ Nothing.

#### Description

Copies the propagated Langfuse trace attributes (user, session, trace name, tags, metadata) from the parent context onto the new span and remembers it until it ends.
Copies the propagated Langfuse trace attributes (user, session, trace name, tags, metadata) from the parent context onto the new span, marks it for input and output redaction when a `setLangfuseContext` scope asked for `redactIO`, and remembers it until it ends.

#### Implementation of

Expand Down
2 changes: 1 addition & 1 deletion docs/api/functions/setLangfuseContext.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ Whatever `fn` returns.

## Description

Runs `fn` with trace attributes propagated to every span it creates. `conversationId` and `requestId` become metadata; empty values are dropped. `prompt` adds the trace tag `prompt:<name>@<version>` (`@fallback` for a fallback, no suffix without a version) and `promptName`, `promptVersion` and `promptLabel` metadata, and links generations to the prompt version unless it is a fallback; it replaces an enclosing prompt's tag, metadata and link. Metadata values of up to 200 characters once stringified are on every observation; longer values and arrays are recorded in full on the trace only, written by the trace root.
Runs `fn` with trace attributes propagated to every span it creates. `conversationId` and `requestId` become metadata; empty values are dropped. `prompt` adds the trace tag `prompt:<name>@<version>` (`@fallback` for a fallback, no suffix without a version) and `promptName`, `promptVersion` and `promptLabel` metadata, and links generations to the prompt version unless it is a fallback; it replaces an enclosing prompt's tag, metadata and link. `redactIO: true` leaves input and output out of the Langfuse export for every observation started inside, nested scopes included; `false` cannot undo it. Metadata values of up to 200 characters once stringified are on every observation; longer values and arrays are recorded in full on the trace only, written by the trace root.

## Example

Expand Down
8 changes: 8 additions & 0 deletions docs/api/type-aliases/NeurolinkTraceContext.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,11 @@ Name of the root observation of this `generate` or `stream` call; not propagated
> `optional` **prompt?**: [`LangfusePromptRef`](LangfusePromptRef.md)

Langfuse prompt the call ran with, such as a `getLangfusePrompt` result; recorded as a `prompt:` trace tag and `promptName`, `promptVersion` and `promptLabel` metadata, replacing an enclosing prompt's tag and metadata.

---

### redactIO?

> `optional` **redactIO?**: `boolean`

`true` leaves input and output out of what is sent to Langfuse for every observation started in this scope, nested scopes included, as the exporter's `redactIO` does for all traces. `false` cannot undo an enclosing scope's or the exporter's `redactIO`.
24 changes: 22 additions & 2 deletions docs/features/observability.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ await neurolink.generate({
| `requestId` | Metadata key `requestId` |
| `metadata` | Metadata; values up to 200 characters are on every observation, longer values and arrays are recorded in full on the trace only |
| `observationName` | Name of the root observation of this call; default `generate` or `stream`; not propagated to child observations or used as the trace name |
| `redactIO` | `true` leaves this call's input and output out of what is sent to Langfuse; see [Redacting a call or scope](#redacting-a-call-or-scope) |

### setLangfuseContext

Expand All @@ -143,7 +144,7 @@ const result = await setLangfuseContext(
);
```

`setLangfuseContext(params: NeurolinkTraceContext, fn)` returns whatever `fn` returns. It is a thin wrapper over Langfuse's `propagateAttributes`.
`setLangfuseContext(params: NeurolinkTraceContext, fn)` returns whatever `fn` returns. It is a thin wrapper over Langfuse's `propagateAttributes`. It takes the fields in the table above except `observationName`, plus `prompt`.

### Langfuse prompts

Expand Down Expand Up @@ -239,10 +240,29 @@ const neurolink = new NeuroLink({

`mask` and `redactIO` act on what NeuroLink sends to Langfuse, and on nothing else. They cover the trace and observation input and output (`langfuse.observation.input`, `langfuse.observation.output`, `langfuse.trace.input`, `langfuse.trace.output`); `redactIO: true` leaves those out of the request, and `mask` rewrites them instead. `mask` also runs on trace and observation metadata, whether or not the metadata is an object. If it throws, the value is replaced by `<fully masked>`.

Everything else goes to Langfuse as it was recorded: the status message, `exception.message`, `error.message`, a tool's `tool.error.message` and a provider retry's `retry.error`, tool-call attributes, the `proxy.body` attribute of proxy body events, event attributes, and the prompt and completion attributes another library's GenAI instrumentation writes on spans that are exported with NeuroLink's. The policy does not reach any other sink either: an exporter you register with `registerExporter`, the spans NeuroLink sends to `OTEL_EXPORTER_OTLP_ENDPOINT`, and `getSpans()` receive the values as they were recorded. If one of them must not see content, take it out where it is recorded (`NEUROLINK_RECORD_INPUTS=false`) or in that sink's own processing.
Everything else goes to Langfuse as it was recorded: the status message, `exception.message`, `error.message`, a tool's `tool.error.message` and a provider retry's `retry.error`, tool-call attributes, the `proxy.body` attribute of proxy body events, event attributes, and the prompt and completion attributes another library's GenAI instrumentation writes on spans that are exported with NeuroLink's. The policy does not reach any other sink either: an exporter you register with `registerExporter`, the spans NeuroLink sends to `OTEL_EXPORTER_OTLP_ENDPOINT`, and `getSpans()` receive the values as they were recorded. If one of them must not see content, take it out in that sink's own processing. `NEUROLINK_RECORD_INPUTS=false` keeps the inputs NeuroLink records (prompts, messages, tool arguments) out of the spans Langfuse, `registerExporter` exporters and `OTEL_EXPORTER_OTLP_ENDPOINT` receive. It does not filter the prompt attributes another library's instrumentation writes, or the stream records `getSpans()` returns, which still carry the prompt; output and error text are recorded either way.

NeuroLink adds no credential masking of its own to error text. A failed call's status message, `error.message`, `tool.error.message`, `retry.error` and exception text are recorded as the provider returned them, in every sink, as the released build did, so an error that echoes a key reaches the sinks with the key. Input, output and tool arguments and results keep the credential masking they always had. To keep a credential out of error text, filter it in a custom exporter or keep it out of the provider's error.

### Redacting a call or scope

The exporter's `redactIO` applies to every trace. To leave input and output out of some calls only, such as those that carry end-user content, pass `redactIO: true` in a call's `context`, or wrap the code in `setLangfuseContext`:

```typescript
await neurolink.generate({
input: { text: shopperMessage },
context: { redactIO: true },
});

await setLangfuseContext({ traceName: "storefront-chat", redactIO: true }, () =>
neurolink.generate({ input: { text: shopperMessage } }),
);
```

Every observation started inside the call or scope, nested scopes included, is sent to Langfuse without input and output. Observations started outside it keep theirs, including spans that were already open when it began, such as a trace root your code created, so a `context.redactIO` on a nested `generate` covers that call only. It covers the same attributes as the exporter's `redactIO`, and `redactIO: false` cannot undo an enclosing scope's or the exporter's `redactIO`. The scope is applied by NeuroLink's span processor, so it works with the exporter pipeline (`createExporterSpanProcessor`) and not with a `LangfuseSpanProcessor` you add yourself.

Spans started inside carry the attribute `neurolink.langfuse.redact_io: true`. The Langfuse request drops it along with the input and output; an exporter registered with `registerExporter` and the spans sent to `OTEL_EXPORTER_OTLP_ENDPOINT` receive it with the content as recorded, so a sink of your own can redact the same spans. The records `getSpans()` returns are built separately and do not carry it.

## Langfuse exporter behaviour

- **Endpoint.** `POST {baseUrl}/api/public/otel/v1/traces` as OTLP/HTTP JSON. Requests are cut at 500 spans or 3.5 MB.
Expand Down
3 changes: 3 additions & 0 deletions src/lib/constants/langfuse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ export const CONTENT_KEYS = new Set([
"langfuse.trace.output",
]);

/** @description Span attribute marking a span started inside a `setLangfuseContext({ redactIO: true })` scope; the Langfuse exporter leaves its input and output out and does not send the marker. */
export const REDACT_IO_ATTRIBUTE = "neurolink.langfuse.redact_io";

/** @description Attribute prefixes whose values are metadata entries. */
export const METADATA_PREFIXES = [
"langfuse.observation.metadata.",
Expand Down
3 changes: 3 additions & 0 deletions src/lib/constants/telemetry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ export const TRACE_METADATA_CONTEXT_KEY = "neurolink.trace.metadata";
/** @description Name of the OpenTelemetry context key that carries the trace tag of the prompt `setLangfuseContext` was last given. */
export const PROMPT_TAG_CONTEXT_KEY = "neurolink.trace.promptTag";

/** @description Name of the OpenTelemetry context key set when an enclosing `setLangfuseContext` asked for `redactIO`. */
export const REDACT_IO_CONTEXT_KEY = "neurolink.trace.redactIO";

/** @description Log prefix for NeuroLink's OpenTelemetry setup. */
export const OTEL_LOG_PREFIX = "[OpenTelemetry]";

Expand Down
1 change: 1 addition & 0 deletions src/lib/neurolink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1490,6 +1490,7 @@ export class NeuroLink {
? (ctx.metadata as Record<string, JsonValue>)
: undefined,
...(isPromptRef(ctx.prompt) && { prompt: ctx.prompt }),
...(Boolean(ctx.redactIO) && { redactIO: true }),
},
callback,
);
Expand Down
14 changes: 12 additions & 2 deletions src/lib/observability/exporterSpanProcessor.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
import { getPropagatedAttributesFromContext } from "@langfuse/core";
import { type Context, SpanStatusCode } from "@opentelemetry/api";
import {
type Context,
createContextKey,
SpanStatusCode,
} from "@opentelemetry/api";
import type {
ReadableSpan,
Span,
SpanProcessor as OtelSpanProcessor,
} from "@opentelemetry/sdk-trace-base";
import { REDACT_IO_ATTRIBUTE } from "../constants/langfuse.js";
import {
INTERNAL_SPAN_ATTRIBUTE,
MAX_REMEMBERED_SPANS,
PROXY_TRACER_SCOPE,
REDACT_IO_CONTEXT_KEY,
} from "../constants/telemetry.js";
import type {
ExporterSpanProcessorOptions,
Expand All @@ -24,6 +30,7 @@ import { getExporterRegistry } from "./exporterRegistry.js";
const LANGFUSE_OBSERVATION_TYPE = "langfuse.observation.type";
const GEN_AI_OBSERVATION_TYPE = "gen_ai.observation.type";
const GEN_AI_OPERATION = "gen_ai.operation.name";
const REDACT_IO_KEY = createContextKey(REDACT_IO_CONTEXT_KEY);

const OBSERVATION_SPAN_TYPES: Record<string, SpanType> = {
agent: SpanType.AGENT_RUN,
Expand Down Expand Up @@ -170,13 +177,16 @@ export class ExporterSpanProcessor implements OtelSpanProcessor {
) {}

/**
* @description Copies the propagated Langfuse trace attributes (user, session, trace name, tags, metadata) from the parent context onto the new span and remembers it until it ends.
* @description Copies the propagated Langfuse trace attributes (user, session, trace name, tags, metadata) from the parent context onto the new span, marks it for input and output redaction when a `setLangfuseContext` scope asked for `redactIO`, and remembers it until it ends.
* @param span {Span} - Span that just started.
* @param parentContext {Context} - Context the span was started in.
* @returns {void} Nothing.
*/
onStart(span: Span, parentContext: Context): void {
try {
if (parentContext.getValue(REDACT_IO_KEY) === true) {
span.setAttribute(REDACT_IO_ATTRIBUTE, true);
}
span.setAttributes(getPropagatedAttributesFromContext(parentContext));
this.open.set(span.spanContext().spanId, span);
this.hold(parentIdOf(span));
Expand Down
7 changes: 5 additions & 2 deletions src/lib/observability/langfuseMasking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
CONTENT_KEYS,
FULLY_MASKED,
METADATA_PREFIXES,
REDACT_IO_ATTRIBUTE,
} from "../constants/langfuse.js";
import type {
JsonValue,
Expand Down Expand Up @@ -32,7 +33,7 @@ function maskValue(
}

/**
* @description Applies the Langfuse exporter's policy to a span's attributes as they are sent to Langfuse: fills environment and release when the span has none, removes input and output when `redactIO` is set, and masks input, output and metadata when a mask is configured. Nothing else is touched: other attributes, events and the status message go to Langfuse as they are, and no other exporter sees the policy.
* @description Applies the Langfuse exporter's policy to a span's attributes as they are sent to Langfuse: fills environment and release when the span has none, removes input and output when `redactIO` is set or the span was started in a `setLangfuseContext({ redactIO: true })` scope, masks input, output and metadata when a mask is configured, and drops the `neurolink.langfuse.redact_io` marker. Nothing else is touched: other attributes, events and the status message go to Langfuse as they are, and no other exporter sees the policy.
* @param attributes {SpanAttributes} - Attributes of the span being exported.
* @param policy {LangfuseAttributePolicy} - Environment, release, redaction and mask settings.
* @returns {SpanAttributes} A new attribute record; the input is not modified.
Expand All @@ -46,9 +47,11 @@ export function protectAttributes(
...(policy.release && { "langfuse.release": policy.release }),
...attributes,
};
const redactIO = policy.redactIO || attributes[REDACT_IO_ATTRIBUTE] === true;
delete result[REDACT_IO_ATTRIBUTE];
for (const key of Object.keys(result)) {
if (CONTENT_KEYS.has(key)) {
if (policy.redactIO) {
if (redactIO) {
delete result[key];
} else if (policy.mask) {
result[key] = maskValue(result[key], policy.mask);
Expand Down
10 changes: 8 additions & 2 deletions src/lib/services/server/ai/observability/instrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
import {
OTEL_LOG_PREFIX,
PROMPT_TAG_CONTEXT_KEY,
REDACT_IO_CONTEXT_KEY,
TRACE_METADATA_CONTEXT_KEY,
} from "../../../../constants/telemetry.js";
import { getExporterRegistry } from "../../../../observability/exporterRegistry.js";
Expand Down Expand Up @@ -76,6 +77,7 @@ const MAX_PROPAGATED_CHARS = 200;
const LANGFUSE_EXPORTER_NAME = "langfuse";
const TRACE_METADATA_KEY = createContextKey(TRACE_METADATA_CONTEXT_KEY);
const PROMPT_TAG_KEY = createContextKey(PROMPT_TAG_CONTEXT_KEY);
const REDACT_IO_KEY = createContextKey(REDACT_IO_CONTEXT_KEY);
const CONTEXT_PROBE_KEY = createContextKey("neurolink.context-manager-probe");
// `false`, `0`, `off` or `no` skips the flush at process exit; the released build had none.
const EXIT_FLUSH_SWITCH = "NEUROLINK_TELEMETRY_EXIT_FLUSH";
Expand Down Expand Up @@ -629,7 +631,7 @@ const promptTagOf = ({
};

/**
* @description Runs `fn` with trace attributes propagated to every span it creates. `conversationId` and `requestId` become metadata; empty values are dropped. `prompt` adds the trace tag `prompt:<name>@<version>` (`@fallback` for a fallback, no suffix without a version) and `promptName`, `promptVersion` and `promptLabel` metadata, and links generations to the prompt version unless it is a fallback; it replaces an enclosing prompt's tag, metadata and link. Metadata values of up to 200 characters once stringified are on every observation; longer values and arrays are recorded in full on the trace only, written by the trace root.
* @description Runs `fn` with trace attributes propagated to every span it creates. `conversationId` and `requestId` become metadata; empty values are dropped. `prompt` adds the trace tag `prompt:<name>@<version>` (`@fallback` for a fallback, no suffix without a version) and `promptName`, `promptVersion` and `promptLabel` metadata, and links generations to the prompt version unless it is a fallback; it replaces an enclosing prompt's tag, metadata and link. `redactIO: true` leaves input and output out of the Langfuse export for every observation started inside, nested scopes included; `false` cannot undo it. Metadata values of up to 200 characters once stringified are on every observation; longer values and arrays are recorded in full on the trace only, written by the trace root.
* @param params {NeurolinkTraceContext} - User, session, trace name, tags, metadata and prompt for the trace.
* @param fn {() => T} - Work to run inside the propagated context.
* @returns {T} Whatever `fn` returns.
Expand Down Expand Up @@ -671,7 +673,11 @@ export function setLangfuseContext<T>(
...traceMetadataFromContext(scoped),
...full,
});
return context.with(withMetadata, () =>
// Only `true` is stored, so an inner `redactIO: false` never clears an outer scope's redaction
const scope = params.redactIO
? withMetadata.setValue(REDACT_IO_KEY, true)
: withMetadata;
return context.with(scope, () =>
propagateAttributes(
{
userId: params.userId || undefined,
Expand Down
2 changes: 2 additions & 0 deletions src/lib/types/observability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ export type NeurolinkTraceContext = {
observationName?: string | null;
/** Langfuse prompt the call ran with, such as a `getLangfusePrompt` result; recorded as a `prompt:` trace tag and `promptName`, `promptVersion` and `promptLabel` metadata, replacing an enclosing prompt's tag and metadata. */
prompt?: LangfusePromptRef;
/** `true` leaves input and output out of what is sent to Langfuse for every observation started in this scope, nested scopes included, as the exporter's `redactIO` does for all traces. `false` cannot undo an enclosing scope's or the exporter's `redactIO`. */
redactIO?: boolean;
};

/**
Expand Down
Loading
Loading