@juspay/neurolink
Version:
The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002
74 lines (73 loc) • 8.81 kB
TypeScript
import { type Context } from "@opentelemetry/api";
import type { LangfusePrompt, LangfusePromptOptions, NeurolinkTraceContext, ObservabilityConfig, SpanContent } from "../../../../types/index.js";
/**
* @description Starts NeuroLink's tracing once per process, synchronously. Every span created through the shared tracers calls it first once this module is loaded, as the main, server and livekit entries do, so direct provider calls without a NeuroLink instance are traced too. Langfuse is enabled unless `config.langfuse` is `false` or has `enabled: false`, when `config.langfuse` is `true` or an options object, or when `LANGFUSE_PUBLIC_KEY` and `LANGFUSE_SECRET_KEY` are set and `LANGFUSE_ENABLED` is not `false`, `0`, `off` or `no`; an OTLP exporter is added when `OTEL_EXPORTER_OTLP_ENDPOINT` is set. When the host already registered a TracerProvider no provider is created and `OTEL_EXPORTER_OTLP_ENDPOINT` is ignored with a warning; the Langfuse exporter, if configured, is registered on the shared exporter registry and the host adds `createExporterSpanProcessor()` to its provider. The first call that finds tracing configured decides the setup and a later `config` is ignored, with a warning naming the options that differ from the first when it does differ; calls made before anything is configured start nothing, so a later config or environment can still start tracing, unless `langfuse: false` was passed. Langfuse enabled without both keys (in config or the environment) exports nothing to Langfuse, and a warning says so once. With `langfuse: true` or the environment alone that counts as not configured, so only an OTLP endpoint starts tracing; an options object starts tracing anyway, as it always did, so exporters registered on the shared registry receive the spans. Pending spans and metrics are flushed when the process runs out of work (`beforeExit`), within the same budget as `flushOpenTelemetry`, which an explicit `process.exit()` skips; `NEUROLINK_TELEMETRY_EXIT_FLUSH` set to `false`, `0`, `off` or `no` skips that flush too, and the process ends as soon as it has no work. After `shutdownOpenTelemetry` it does nothing.
* @param config {ObservabilityConfig | undefined} - Observability options, honoured only when this is the first call.
* @returns {void} Nothing; a failed setup is logged and recorded in `getLangfuseHealthStatus`.
*/
export declare function ensureTelemetry(config?: ObservabilityConfig): void;
/**
* @description Registers a holder of the process-wide telemetry and starts it if needed. Pair every call with `releaseTelemetry`.
* @param config {ObservabilityConfig | undefined} - Observability options forwarded to `ensureTelemetry`.
* @returns {void} Nothing.
*/
export declare function acquireTelemetry(config?: ObservabilityConfig): void;
/**
* @description Releases one holder registered by `acquireTelemetry` and flushes pending spans as `flushOpenTelemetry` does. The provider stays registered for the process so cached tracers keep working and later instances reuse it.
* @returns {Promise<void>} Resolves when pending spans are flushed.
* @throws {Error} When any provider fails to flush or does not finish within the flush budget.
*/
export declare function releaseTelemetry(): Promise<void>;
/**
* @description Exports pending spans and metrics from the providers NeuroLink owns and flushes its Langfuse exporter. A host provider is never flushed. The OTLP span and metric exports are waited for at most the flush budget (`observability.langfuse.flushBudgetMs`, default 3000 ms) and the Langfuse exporter within its own budget. A provider that fails to flush, or does not finish within the budget (a collector that cannot be reached, for one), is logged as a warning and makes the call reject once every provider has settled.
* @returns {Promise<void>} Resolves when every owned provider has flushed.
* @throws {Error} When any provider fails to flush or does not finish within the flush budget.
*/
export declare function flushOpenTelemetry(): Promise<void>;
/**
* @description Terminally shuts down the providers NeuroLink owns once no `acquireTelemetry` holder remains; while holders remain it only flushes, as `flushOpenTelemetry` does. Telemetry cannot be restarted in this process afterwards. A host provider is never shut down; with one, only NeuroLink's Langfuse exporter is shut down and unregistered. The OTLP exporters get the same budget as `flushOpenTelemetry`, and a failure of the shutdown itself is logged as a warning.
* @returns {Promise<void>} Resolves when telemetry is flushed or shut down, or the flush budget has run out.
* @throws {Error} When holders remain and the flush they get fails.
*/
export declare function shutdownOpenTelemetry(): Promise<void>;
/**
* @description Reports whether NeuroLink's tracing is active, either on its own provider or alongside a host provider.
* @returns {boolean} `true` once `ensureTelemetry` has set tracing up.
*/
export declare function isOpenTelemetryInitialized(): boolean;
/**
* @description Summarizes the Langfuse export state for health checks.
* @returns {{ isHealthy: boolean; initialized: boolean; hasProcessor: boolean; usingExternalProvider: boolean; error?: string }} `isHealthy` and `hasProcessor` are `true` only while a Langfuse exporter is registered, on NeuroLink's own provider or beside a host provider (where it still needs `createExporterSpanProcessor()` on the host provider to receive spans); `error` carries the message of a failed initialization.
*/
export declare function getLangfuseHealthStatus(): {
isHealthy: boolean;
initialized: boolean;
hasProcessor: boolean;
usingExternalProvider: boolean;
error?: string;
};
/**
* @description Reads the full trace metadata that `setLangfuseContext` stored on a context.
* @param ctx {Context} - Context to read, normally the active one.
* @returns {Record<string, SpanContent>} Metadata set by enclosing `setLangfuseContext` calls, inner keys winning; empty when none was set.
*/
export declare function traceMetadataFromContext(ctx: Context): Record<string, SpanContent>;
/**
* @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.
* @example
* await setLangfuseContext({ userId: "u1", sessionId: "s1" }, () => neurolink.generate({ input: { text: "hi" } }));
*/
export declare function setLangfuseContext<T>(params: NeurolinkTraceContext, fn: () => T): T;
/**
* @description Fetches a text prompt from Langfuse with the keys and host NeuroLink's tracing was started with, falling back to `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_SECRET_KEY` and `LANGFUSE_BASE_URL`. Prompts are cached per project, host, name and label: within `cacheTtlMs` no request is made, and an expired entry is returned at once while one background request refreshes it. Concurrent callers share one request. Missing keys, an error, a timeout, a missing prompt or a chat prompt return the fallback, after a warning for all but missing keys; a failed request is not repeated within `cacheTtlMs`, and a prompt fetched before stays in use. `text` is returned as stored, with `{{variable}}` placeholders not filled in. The fetch ignores `langfuse: false` and `LANGFUSE_ENABLED`, so a caller with its own switch checks it first.
* @param name {string} - Prompt name in Langfuse.
* @param options {LangfusePromptOptions} - Label, fallback text, cache TTL and request timeout.
* @returns {Promise<LangfusePrompt>} The prompt, or `{ name, text: fallback, label, isFallback: true }`; never rejects.
* @example
* const prompt = await getLangfusePrompt("support-agent", { fallback: "You are a helpful agent." });
* await setLangfuseContext({ prompt }, () => neurolink.generate({ input: { text: "hi" }, systemPrompt: prompt.text }));
*/
export declare const getLangfusePrompt: (name: string, options: LangfusePromptOptions) => Promise<LangfusePrompt>;