diff --git a/docs-site/static/search-index.json b/docs-site/static/search-index.json index 11d885bed7..dde09533f0 100644 --- a/docs-site/static/search-index.json +++ b/docs-site/static/search-index.json @@ -3521,6 +3521,7 @@ {"objectID":"304f3b3f1d3d11c91945e49e4ae3f60d2b9a826b87a3948f18fd137a16b38c45","title":"Disable or override","url":"/docs/features/observability#disable-or-override","content":"Every field is optional. publicKey, secretKey, baseUrl, environment and release fall back to the variables above; the others have the defaults below. The type is NeurolinkLangfuseConfig.\n\n| Field | Meaning |\n| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| enabled | false turns Langfuse off although keys are set (from untyped config, the strings \"false\", \"0\", \"off\" and \"no\" do too); any other value, or leaving it out, leaves it on.","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Disable or override","lvl3":""}}, {"objectID":"d5c2e109ca689299bbc1e1068341dfd6ba1294b1ee3c11cebe6489977865892e","title":"Per-call context","url":"/docs/features/observability#per-call-context","content":"Pass context on generate, stream and decide. The values are attached to every span the call creates, including tool calls and fallback attempts, so one call is one trace.\n\n| Field | Recorded as |\n| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |\n| userId | Trace user |\n| sessionId | Trace session |\n| tags | Trace tags |\n| traceName | Trace name |\n| conversationId | Metadata key conversationId |\n| requestId | Metadata key requestId |\n| metadata | Metadata; values up to 200 characters are on every observation, longer values and arrays are recorded in full on the trace only |\n| observationName | Name of the root observation of this call; default generate or stream; not propagated to child observations or used as the trace name |","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Per-call context","lvl3":""}}, {"objectID":"d262ba0787c1b57c76e303845fc9c6f447a3a2f747a880270f15c61fcc1863bb","title":"setLangfuseContext","url":"/docs/features/observability#setlangfusecontext","content":"Wrap your own code to attach the same attributes to everything inside it, including spans you create yourself.\n\nsetLangfuseContext(params: NeurolinkTraceContext, fn) returns whatever fn returns. It is a thin wrapper over Langfuse's propagateAttributes.","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"setLangfuseContext","lvl3":""}}, +{"objectID":"ebe52665a13e8e28856b65cd1d82bb2709538cb3fdd9b2ab6e54cd7061a8fb0d","title":"Langfuse prompts","url":"/docs/features/observability#langfuse-prompts","content":"getLangfusePrompt(name, options) fetches a text prompt from Langfuse Prompt Management with the keys and host tracing uses (observability.langfuse, then LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, LANGFUSE_BASE_URL). Pass the result as prompt to setLangfuseContext and Langfuse links the generations inside to that prompt version.\n\n| Option | Default | Effect |\n| ------------ | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| label | production | Deployment label to fetch |\n| fallback | required | Text returned when the prompt cannot be fetched as a text prompt |\n| cacheTtlMs | 60000 | How long a prompt is served from the cache before it is refreshed in the background; the call that fetches an entry sets it for every caller of that name and label |\n| timeoutMs | 2000 | How long one fetch waits for Langfuse |\n\nIt never throws. Prompts are cached per project, host, name and label, up to 500 entries (the least recently fetched is dropped first), and each call gets its own copy; concurrent callers share one request, and an expired entry is returned at once while it refreshes.","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Langfuse prompts","lvl3":""}}, {"objectID":"542eff7388511fe18f61b3de966dff32a0a0ccfa5c95df170298790e0233739d","title":"Naming","url":"/docs/features/observability#naming","content":"The observations below (generate, stream, decide, attempts, steps and tools) carry no product name in their span names, attribute keys or metadata keys. Names never carry per-execution values: the model and provider are fields, the step number is metadata. The product name remains in the plain spans listed under Other spans and in the proxy root's neurolink.user_id, neurolink.session_id and neurolink.conversation_id attributes.\n\n| Observation | Name | Langfuse type | Parent |\n| -------------------------- | ------------------------------------- | ------------- | ---------------------- |\n| generate / stream call | generate / stream | agent | none (trace root) |\n| Fallback attempt | generate.attempt / stream.attempt | span | root |\n| Agent loop step | step (step_index metadata) | span | the attempt span |\n| One model request | generate / stream | generation | its step |\n| Tool execution | the tool's name, e.g. get_weather | tool | the step that ran it |\n| decide | decide | generation | caller or root |\n\nA model request is named after the API the caller used (NeuroLink.generate or provider.generate gives generate, NeuroLink.stream or provider.stream gives stream). Its model is the observation's model field (the model the provider reported, falling back to the requested one) and the provider id is the provider metadata key.\n\nThe trace name is context.traceName when given, otherwise the operation name (generate, stream). An outer setLangfuseContext takes precedence over per-call context for user, session and trace name.\n\nEmbeddings, transcribe, TTS and media tracing are not yet recorded. The root also sets trace-level input and output; a generate or stream nested inside another turn does not.","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Naming","lvl3":""}}, {"objectID":"bec7707961c02d5123e4dceed9e13f5f5311e2f47783dd81fc290b467f50ff7a","title":"Other spans","url":"/docs/features/observability#other-spans","content":"Spans from the RAG, workflow, file, memory, context and evaluation code are exported as plain span records with their name, timing, status and their own attributes. They keep their neurolink.* names: neurolink.rag.search, neurolink.rag.rerank, neurolink.rag.chunk, neurolink.workflow.* (run, run.streaming, response.condition, judge.score, ensemble.execute, layers.execute), neurolink.file.process, neurolink.file.video.process, neurolink.context.compact, neurolink.memory.summarize and neurolink.evaluation.ragas.","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Other spans","lvl3":""}}, {"objectID":"ceb0e84f71b6a9deb6a57e236efa009236e933eb892ad569d59e36ba873292f3","title":"Steps and chat format","url":"/docs/features/observability#steps-and-chat-format","content":"Each iteration of the agent loop gets one step span with its one-based index in the step_index metadata. It parents that iteration's generation and the tool observations the model requested in it, so a multi-tool turn reads as step 1 (call, tools), step 2 (call, tools), and so on.\n\nGeneration input is a chat message array with the system message first. Generation output is an assistant message array: content, plus reasoning and tool_calls ({ id, type: \"function\", function: { name, arguments } }) when present. Langfuse renders both as a conversation.\n\nGeneration details:\nUsage includes input, output, total, cache read, cache creation and reasoning tokens, whatever naming the provider uses.\nCost is computed from NeuroLink's pricing table and recorded as costDetails.total.\nModel parameters are temperature, max tokens, top-p and thinking level.\nTime to first token is recorded as the generation's completion start time for streams.\nLevel is WARNING for a length or content-filter finish, an aborted call, an early break out of a stream, or an empty output, and ERROR when the call throws.\nStreams end their spans when the stream finishes, is abandoned or is aborted.","hierarchy":{"lvl0":"Features","lvl1":"Observability Guide","lvl2":"Steps and chat format","lvl3":""}}, diff --git a/docs/api/README.md b/docs/api/README.md index 07326665ac..2f1bfa9270 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -1969,6 +1969,9 @@ console.log(result.content); - [AiMetricInstruments](type-aliases/AiMetricInstruments.md) - [ObservabilityConfig](type-aliases/ObservabilityConfig.md) - [NeurolinkTraceContext](type-aliases/NeurolinkTraceContext.md) +- [LangfusePromptRef](type-aliases/LangfusePromptRef.md) +- [LangfusePromptOptions](type-aliases/LangfusePromptOptions.md) +- [LangfusePrompt](type-aliases/LangfusePrompt.md) - [RetryPolicy](type-aliases/RetryPolicy.md) - [Sampler](type-aliases/Sampler.md) - [SpanProcessor](type-aliases/SpanProcessor.md) @@ -4117,6 +4120,7 @@ console.log(result.content); - [isOpenTelemetryInitialized](functions/isOpenTelemetryInitialized.md) - [getLangfuseHealthStatus](functions/getLangfuseHealthStatus.md) - [setLangfuseContext](functions/setLangfuseContext.md) +- [getLangfusePrompt](functions/getLangfusePrompt.md) - [createSkillStore](functions/createSkillStore.md) - [createSkillTools](functions/createSkillTools.md) - [isStandardRecord](functions/isStandardRecord.md) diff --git a/docs/api/functions/getLangfusePrompt.md b/docs/api/functions/getLangfusePrompt.md new file mode 100644 index 0000000000..2370b67d8e --- /dev/null +++ b/docs/api/functions/getLangfusePrompt.md @@ -0,0 +1,44 @@ +[**NeuroLink API Reference**](../README.md) + +--- + +[NeuroLink API Reference](../README.md) / getLangfusePrompt + +# Function: getLangfusePrompt() + +> **getLangfusePrompt**(`name`, `options`): `Promise`\<[`LangfusePrompt`](../type-aliases/LangfusePrompt.md)\> + +## Parameters + +### name + +`string` + +{string} - Prompt name in Langfuse. + +### options + +[`LangfusePromptOptions`](../type-aliases/LangfusePromptOptions.md) + +{LangfusePromptOptions} - Label, fallback text, cache TTL and request timeout. + +## Returns + +`Promise`\<[`LangfusePrompt`](../type-aliases/LangfusePrompt.md)\> + +The prompt, or `{ name, text: fallback, label, isFallback: true }`; never rejects. + +## 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. + +## Example + +```ts +const prompt = await getLangfusePrompt("support-agent", { + fallback: "You are a helpful agent.", +}); +await setLangfuseContext({ prompt }, () => + neurolink.generate({ input: { text: "hi" }, systemPrompt: prompt.text }), +); +``` diff --git a/docs/api/functions/setLangfuseContext.md b/docs/api/functions/setLangfuseContext.md index eee9a2b28a..5b0511edef 100644 --- a/docs/api/functions/setLangfuseContext.md +++ b/docs/api/functions/setLangfuseContext.md @@ -20,7 +20,7 @@ [`NeurolinkTraceContext`](../type-aliases/NeurolinkTraceContext.md) -{NeurolinkTraceContext} - User, session, trace name, tags and metadata for the trace. +{NeurolinkTraceContext} - User, session, trace name, tags, metadata and prompt for the trace. ### fn @@ -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. 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:@` (`@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. ## Example diff --git a/docs/api/type-aliases/LangfusePrompt.md b/docs/api/type-aliases/LangfusePrompt.md new file mode 100644 index 0000000000..6ce52621e4 --- /dev/null +++ b/docs/api/type-aliases/LangfusePrompt.md @@ -0,0 +1,25 @@ +[**NeuroLink API Reference**](../README.md) + +--- + +[NeuroLink API Reference](../README.md) / LangfusePrompt + +# Type Alias: LangfusePrompt + +> **LangfusePrompt** = [`LangfusePromptRef`](LangfusePromptRef.md) & `object` + +## Type Declaration + +### text + +> **text**: `string` + +Prompt text to send to the model. + +### isFallback + +> **isFallback**: `boolean` + +## Description + +A text prompt resolved by `getLangfusePrompt`. `isFallback` is `true` when `text` is the caller's fallback, which carries no `version`. diff --git a/docs/api/type-aliases/LangfusePromptOptions.md b/docs/api/type-aliases/LangfusePromptOptions.md new file mode 100644 index 0000000000..ee948750aa --- /dev/null +++ b/docs/api/type-aliases/LangfusePromptOptions.md @@ -0,0 +1,45 @@ +[**NeuroLink API Reference**](../README.md) + +--- + +[NeuroLink API Reference](../README.md) / LangfusePromptOptions + +# Type Alias: LangfusePromptOptions + +> **LangfusePromptOptions** = `object` + +## Description + +Options for `getLangfusePrompt`. + +## Properties + +### label? + +> `optional` **label?**: `string` + +Deployment label to fetch; Langfuse serves `production` when omitted. + +--- + +### fallback + +> **fallback**: `string` + +Text returned when the prompt cannot be fetched as a text prompt. + +--- + +### cacheTtlMs? + +> `optional` **cacheTtlMs?**: `number` + +Milliseconds before a cached prompt is refreshed in the background; defaults to 60000. The call that fetches an entry sets it for every caller of that name and label. + +--- + +### timeoutMs? + +> `optional` **timeoutMs?**: `number` + +Milliseconds a fetch, body included, waits for Langfuse; defaults to 2000. diff --git a/docs/api/type-aliases/LangfusePromptRef.md b/docs/api/type-aliases/LangfusePromptRef.md new file mode 100644 index 0000000000..5321d26b53 --- /dev/null +++ b/docs/api/type-aliases/LangfusePromptRef.md @@ -0,0 +1,45 @@ +[**NeuroLink API Reference**](../README.md) + +--- + +[NeuroLink API Reference](../README.md) / LangfusePromptRef + +# Type Alias: LangfusePromptRef + +> **LangfusePromptRef** = `object` + +## Description + +A Langfuse prompt version a trace was produced with. Generations are linked to it when it has a `version` and is not a fallback. + +## Properties + +### name + +> **name**: `string` + +Prompt name in Langfuse. + +--- + +### version? + +> `optional` **version?**: `number` + +Prompt version; generations are linked only when it is set. + +--- + +### label? + +> `optional` **label?**: `string` + +Deployment label the version was fetched by. + +--- + +### isFallback? + +> `optional` **isFallback?**: `boolean` + +Whether the prompt text is a local fallback rather than a Langfuse version. diff --git a/docs/api/type-aliases/NeurolinkTraceContext.md b/docs/api/type-aliases/NeurolinkTraceContext.md index e58adb6e22..348320ccb3 100644 --- a/docs/api/type-aliases/NeurolinkTraceContext.md +++ b/docs/api/type-aliases/NeurolinkTraceContext.md @@ -75,3 +75,11 @@ Trace metadata; values up to 200 characters once stringified are on every observ > `optional` **observationName?**: `string` \| `null` Name of the root observation of this `generate` or `stream` call; not propagated to child observations and not the trace name. + +--- + +### prompt? + +> `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. diff --git a/docs/features/observability.md b/docs/features/observability.md index 456b7c76e1..0d95cba2ec 100644 --- a/docs/features/observability.md +++ b/docs/features/observability.md @@ -145,6 +145,43 @@ const result = await setLangfuseContext( `setLangfuseContext(params: NeurolinkTraceContext, fn)` returns whatever `fn` returns. It is a thin wrapper over Langfuse's `propagateAttributes`. +### Langfuse prompts + +`getLangfusePrompt(name, options)` fetches a text prompt from Langfuse Prompt Management with the keys and host tracing uses (`observability.langfuse`, then `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_SECRET_KEY`, `LANGFUSE_BASE_URL`). Pass the result as `prompt` to `setLangfuseContext` and Langfuse links the generations inside to that prompt version. + +```typescript +import { + NeuroLink, + ensureTelemetry, + getLangfusePrompt, + setLangfuseContext, +} from "@juspay/neurolink"; + +ensureTelemetry(); +const neurolink = new NeuroLink(); +const prompt = await getLangfusePrompt("support-agent", { + label: "production", + fallback: "You are a helpful support agent.", +}); + +await setLangfuseContext({ prompt }, () => + neurolink.generate({ input: { text: "Hello" }, systemPrompt: prompt.text }), +); +``` + +| Option | Default | Effect | +| ------------ | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `label` | `production` | Deployment label to fetch | +| `fallback` | required | Text returned when the prompt cannot be fetched as a text prompt | +| `cacheTtlMs` | `60000` | How long a prompt is served from the cache before it is refreshed in the background; the call that fetches an entry sets it for every caller of that name and label | +| `timeoutMs` | `2000` | How long one fetch waits for Langfuse | + +It never throws. Prompts are cached per project, host, name and label, up to 500 entries (the least recently fetched is dropped first), and each call gets its own copy; concurrent callers share one request, and an expired entry is returned at once while it refreshes. Without keys, or when the fetch fails, times out, finds no prompt, or finds a chat or malformed prompt, it returns `{ name, text: fallback, label, isFallback: true }` (with a warning unless the keys are missing; a Langfuse error response is logged by status code only) and does not retry until `cacheTtlMs` has passed; a prompt fetched earlier stays in use. + +`text` is the prompt exactly as stored: `{{variable}}` placeholders are not filled in, so substitute them before sending the text to a model. The fetch does not depend on whether tracing is on: it uses the keys tracing started with, or the `LANGFUSE_*` variables, even with `langfuse: false` or `LANGFUSE_ENABLED=false`, so an application with its own switch for Langfuse checks it before calling. + +With `prompt` set, `setLangfuseContext` also adds the trace tag `prompt:@` (`prompt:@fallback` for a fallback) and the metadata `promptName`, `promptVersion` and `promptLabel`. A fallback is tagged but never linked. A per-call `context: { prompt }` on `generate` or `stream` does the same. A `prompt` replaces the link, the `prompt:` tag and the `prompt*` metadata of an enclosing `setLangfuseContext`, so the spans of a fallback inside a managed-prompt scope link to nothing and carry no outer tag, version or label; spans that ran in the outer scope keep the outer tag on the trace. A span already running when the inner scope opens takes the inner tag and metadata. Context set before tracing starts is dropped, so call `ensureTelemetry()` (or make a traced call) first. + ## What is recorded ### Naming diff --git a/src/lib/constants/langfuse.ts b/src/lib/constants/langfuse.ts index 0dec2d35ce..4797253e70 100644 --- a/src/lib/constants/langfuse.ts +++ b/src/lib/constants/langfuse.ts @@ -9,6 +9,22 @@ export const HEALTH_PATH = "/api/public/health"; /** @description Langfuse Cloud base URL used when none is configured. */ export const DEFAULT_BASE_URL = "https://cloud.langfuse.com"; +/** @description Milliseconds a fetched Langfuse prompt is served from the cache before it is refreshed in the background. */ +export const DEFAULT_PROMPT_CACHE_TTL_MS = 60_000; + +/** @description Milliseconds a Langfuse prompt fetch waits before the fallback is used. */ +export const DEFAULT_PROMPT_TIMEOUT_MS = 2_000; + +/** @description Prompt cache entries kept per process; the least recently fetched is evicted beyond it. */ +export const MAX_CACHED_PROMPTS = 500; + +/** @description Trace metadata keys `setLangfuseContext` writes for a prompt; an inner prompt drops the inherited ones. */ +export const PROMPT_METADATA_KEYS = new Set([ + "promptName", + "promptVersion", + "promptLabel", +]); + /** @description Spans buffered before an automatic flush. */ export const DEFAULT_FLUSH_AT = 15; diff --git a/src/lib/constants/telemetry.ts b/src/lib/constants/telemetry.ts index 75622279f1..53b6f80395 100644 --- a/src/lib/constants/telemetry.ts +++ b/src/lib/constants/telemetry.ts @@ -36,6 +36,9 @@ export const TRUNCATION_NOTE_ALLOWANCE_CHARS = 48; /** @description Name of the OpenTelemetry context key that carries a trace's full metadata. */ 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 Log prefix for NeuroLink's OpenTelemetry setup. */ export const OTEL_LOG_PREFIX = "[OpenTelemetry]"; diff --git a/src/lib/index.ts b/src/lib/index.ts index 415516db42..95a0be93f4 100644 --- a/src/lib/index.ts +++ b/src/lib/index.ts @@ -385,6 +385,7 @@ import { ensureTelemetry, flushOpenTelemetry, getLangfuseHealthStatus, + getLangfusePrompt, isOpenTelemetryInitialized, setLangfuseContext, shutdownOpenTelemetry, @@ -395,6 +396,7 @@ export { shutdownOpenTelemetry, flushOpenTelemetry, getLangfuseHealthStatus, + getLangfusePrompt, setLangfuseContext, isOpenTelemetryInitialized, }; diff --git a/src/lib/neurolink.ts b/src/lib/neurolink.ts index cedd393dc7..33ff2194ee 100644 --- a/src/lib/neurolink.ts +++ b/src/lib/neurolink.ts @@ -132,6 +132,7 @@ import type { MCPEnhancementsConfig, NeuroLinkAuthConfig, NeurolinkConstructorConfig, + LangfusePromptRef, ChatMessage, ConversationMemoryConfig, ConversationSeedMessage, @@ -549,7 +550,7 @@ import { transformToolsToExpectedFormat, } from "./utils/transformationUtils.js"; import { toToolExecutionRecords } from "./core/toolExecutionRecorder.js"; -import { isNonNullObject } from "./utils/typeUtils.js"; +import { isNonNullObject, isObject } from "./utils/typeUtils.js"; import { getWorkflow } from "./workflow/core/workflowRegistry.js"; import { runWorkflow } from "./workflow/core/workflowRunner.js"; import { ModelPool, classifyProviderError } from "./routing/index.js"; @@ -1459,6 +1460,14 @@ export class NeuroLink { const outer = getPropagatedAttributesFromContext(context.active()); const unset = (key: string, value: JsonValue): string | undefined => typeof value === "string" && !outer[key] ? value : undefined; + const isPromptRef = ( + value: JsonValue, + ): value is JsonObject & LangfusePromptRef => + isObject(value) && + typeof value.name === "string" && + Number.isInteger(value.version ?? 0) && + typeof (value.label ?? "") === "string" && + typeof (value.isFallback ?? false) === "boolean"; return await setLangfuseContext( { userId: unset(LangfuseOtelSpanAttributes.TRACE_USER_ID, ctx.userId), @@ -1480,6 +1489,7 @@ export class NeuroLink { ctx.metadata && typeof ctx.metadata === "object" ? (ctx.metadata as Record) : undefined, + ...(isPromptRef(ctx.prompt) && { prompt: ctx.prompt }), }, callback, ); diff --git a/src/lib/services/server/ai/observability/instrumentation.ts b/src/lib/services/server/ai/observability/instrumentation.ts index 0589aa0733..744bde3818 100644 --- a/src/lib/services/server/ai/observability/instrumentation.ts +++ b/src/lib/services/server/ai/observability/instrumentation.ts @@ -1,3 +1,8 @@ +import { + LangfuseAPIClient, + LangfuseAPIError, + LangfuseOtelContextKeys, +} from "@langfuse/core"; import { propagateAttributes, setLangfuseTracerProvider, @@ -23,9 +28,17 @@ import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION, } from "@opentelemetry/semantic-conventions"; -import { DEFAULT_FLUSH_BUDGET_MS } from "../../../../constants/langfuse.js"; +import { + DEFAULT_BASE_URL, + DEFAULT_FLUSH_BUDGET_MS, + DEFAULT_PROMPT_CACHE_TTL_MS, + DEFAULT_PROMPT_TIMEOUT_MS, + MAX_CACHED_PROMPTS, + PROMPT_METADATA_KEYS, +} from "../../../../constants/langfuse.js"; import { OTEL_LOG_PREFIX, + PROMPT_TAG_CONTEXT_KEY, TRACE_METADATA_CONTEXT_KEY, } from "../../../../constants/telemetry.js"; import { getExporterRegistry } from "../../../../observability/exporterRegistry.js"; @@ -37,6 +50,9 @@ import { registerTelemetryStarter, } from "../../../../telemetry/telemetryStarter.js"; import type { + LangfusePrompt, + LangfusePromptOptions, + LangfusePromptRef, NeurolinkTraceContext, ObservabilityConfig, OtlpConnections, @@ -59,6 +75,7 @@ import { 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 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"; @@ -83,6 +100,11 @@ let terminationLogged = false; let unconfiguredLogged = false; let missingKeysLogged = false; let holders = 0; +const promptCache = new Map< + string, + { prompt?: LangfusePrompt; expiresAt: number } +>(); +const promptRefreshes = new Map>(); function differingConfigFields( first: ObservabilityConfig | undefined, @@ -556,9 +578,59 @@ export function traceMetadataFromContext( : {}; } +const withoutPrompt = (metadata: object): Record => + Object.fromEntries( + Object.entries(metadata).filter(([key]) => !PROMPT_METADATA_KEYS.has(key)), + ); + +const promptScope = (active: Context, prompt?: LangfusePromptRef): Context => { + if (!prompt) { + return active; + } + const inherited = active.getValue(LangfuseOtelContextKeys.metadata); + const tags = active.getValue(LangfuseOtelContextKeys.tags); + const outerTag = active.getValue(PROMPT_TAG_KEY); + const cleared = active + .deleteValue(LangfuseOtelContextKeys.promptName) + .deleteValue(LangfuseOtelContextKeys.promptVersion) + .setValue( + LangfuseOtelContextKeys.metadata, + withoutPrompt( + inherited && typeof inherited === "object" ? inherited : {}, + ), + ) + .setValue( + TRACE_METADATA_KEY, + withoutPrompt(traceMetadataFromContext(active)), + ) + .setValue( + LangfuseOtelContextKeys.tags, + Array.isArray(tags) ? tags.filter((tag) => tag !== outerTag) : [], + ) + .setValue(PROMPT_TAG_KEY, promptTagOf(prompt)); + return !prompt.isFallback && Number.isInteger(prompt.version) + ? cleared + .setValue(LangfuseOtelContextKeys.promptName, prompt.name) + .setValue(LangfuseOtelContextKeys.promptVersion, prompt.version) + : cleared; +}; + +const promptTagOf = ({ + name, + version, + isFallback, +}: LangfusePromptRef): string => { + if (isFallback) { + return `prompt:${name}@fallback`; + } + return typeof version === "number" + ? `prompt:${name}@${version}` + : `prompt:${name}`; +}; + /** - * @description Runs `fn` with trace attributes propagated to every span it creates. `conversationId` and `requestId` become metadata; empty values are dropped. 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 and metadata for the trace. + * @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:@` (`@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. + * @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 @@ -568,12 +640,18 @@ export function setLangfuseContext( params: NeurolinkTraceContext, fn: () => T, ): T { + const { prompt } = params; const full: Record = {}; const propagated: Record = {}; for (const [key, value] of Object.entries({ ...params.metadata, conversationId: params.conversationId, requestId: params.requestId, + ...(prompt && { + promptName: prompt.name, + promptVersion: prompt.version, + promptLabel: prompt.label, + }), })) { if (value === undefined || value === null || value === "") { continue; @@ -584,10 +662,13 @@ export function setLangfuseContext( propagated[key] = text; } } - const tags = params.tags?.filter((tag) => tag.length > 0); - const active = context.active(); - const withMetadata = active.setValue(TRACE_METADATA_KEY, { - ...traceMetadataFromContext(active), + const tags = [ + ...(params.tags ?? []), + ...(prompt ? [promptTagOf(prompt)] : []), + ].filter((tag) => tag.length > 0); + const scoped = promptScope(context.active(), prompt); + const withMetadata = scoped.setValue(TRACE_METADATA_KEY, { + ...traceMetadataFromContext(scoped), ...full, }); return context.with(withMetadata, () => @@ -596,10 +677,125 @@ export function setLangfuseContext( userId: params.userId || undefined, sessionId: params.sessionId || undefined, traceName: params.traceName || undefined, - ...(tags && tags.length > 0 && { tags }), + ...(tags.length > 0 && { tags }), ...(Object.keys(propagated).length > 0 && { metadata: propagated }), }, fn, ), ); } + +const cachePrompt = ( + key: string, + cacheTtlMs: number, + prompt?: LangfusePrompt, +): void => { + promptCache.delete(key); + promptCache.set(key, { prompt, expiresAt: Date.now() + cacheTtlMs }); + if (promptCache.size > MAX_CACHED_PROMPTS) { + const [oldest] = promptCache.keys(); + promptCache.delete(oldest); + } +}; + +const refreshPrompt = async ( + key: string, + client: LangfuseAPIClient, + name: string, + { + label, + cacheTtlMs = DEFAULT_PROMPT_CACHE_TTL_MS, + timeoutMs = DEFAULT_PROMPT_TIMEOUT_MS, + }: LangfusePromptOptions, +): Promise => { + const previous = promptCache.get(key)?.prompt; + try { + const prompt = await client.prompts.get( + name, + { label }, + { + abortSignal: AbortSignal.timeout(timeoutMs), + timeoutInSeconds: timeoutMs / 1000, + maxRetries: 0, + }, + ); + if ( + prompt.type === "text" && + typeof prompt.prompt === "string" && + Number.isInteger(prompt.version) + ) { + cachePrompt(key, cacheTtlMs, { + name, + text: prompt.prompt, + version: prompt.version, + label, + isFallback: false, + }); + return; + } + logger.warn( + `${OTEL_LOG_PREFIX} Langfuse prompt "${name}" is not a text prompt; using the fallback`, + ); + } catch (error) { + logger.warn( + `${OTEL_LOG_PREFIX} Could not fetch Langfuse prompt "${name}"; using the fallback`, + error instanceof LangfuseAPIError && typeof error.statusCode === "number" + ? { status: error.statusCode } + : { error: error instanceof Error ? error.message : String(error) }, + ); + } + cachePrompt(key, cacheTtlMs, previous); +}; + +/** + * @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} 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 const getLangfusePrompt = async ( + name: string, + options: LangfusePromptOptions, +): Promise => { + const fallback: LangfusePrompt = { + name, + text: options.fallback, + label: options.label, + isFallback: true, + }; + const langfuse = + typeof startedConfig?.langfuse === "object" ? startedConfig.langfuse : {}; + const publicKey = langfuse.publicKey ?? process.env.LANGFUSE_PUBLIC_KEY; + const secretKey = langfuse.secretKey ?? process.env.LANGFUSE_SECRET_KEY; + if (!publicKey || !secretKey) { + return fallback; + } + const host = + langfuse.baseUrl || process.env.LANGFUSE_BASE_URL || DEFAULT_BASE_URL; + const key = JSON.stringify([publicKey, host, name, options.label]); + const cached = promptCache.get(key); + if (!cached || cached.expiresAt <= Date.now()) { + const refresh = + promptRefreshes.get(key) ?? + refreshPrompt( + key, + new LangfuseAPIClient({ + environment: "", + baseUrl: host, + username: publicKey, + password: secretKey, + }), + name, + options, + ).finally(() => promptRefreshes.delete(key)); + promptRefreshes.set(key, refresh); + if (!cached) { + await refresh; + } + } + const prompt = promptCache.get(key)?.prompt; + return prompt ? { ...prompt } : fallback; +}; diff --git a/src/lib/types/observability.ts b/src/lib/types/observability.ts index ca8d186f05..0b9ed96f0c 100644 --- a/src/lib/types/observability.ts +++ b/src/lib/types/observability.ts @@ -125,6 +125,45 @@ export type NeurolinkTraceContext = { metadata?: Record; /** Name of the root observation of this `generate` or `stream` call; not propagated to child observations and not the trace name. */ 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; +}; + +/** + * @description A Langfuse prompt version a trace was produced with. Generations are linked to it when it has a `version` and is not a fallback. + */ +export type LangfusePromptRef = { + /** Prompt name in Langfuse. */ + name: string; + /** Prompt version; generations are linked only when it is set. */ + version?: number; + /** Deployment label the version was fetched by. */ + label?: string; + /** Whether the prompt text is a local fallback rather than a Langfuse version. */ + isFallback?: boolean; +}; + +/** + * @description Options for `getLangfusePrompt`. + */ +export type LangfusePromptOptions = { + /** Deployment label to fetch; Langfuse serves `production` when omitted. */ + label?: string; + /** Text returned when the prompt cannot be fetched as a text prompt. */ + fallback: string; + /** Milliseconds before a cached prompt is refreshed in the background; defaults to 60000. The call that fetches an entry sets it for every caller of that name and label. */ + cacheTtlMs?: number; + /** Milliseconds a fetch, body included, waits for Langfuse; defaults to 2000. */ + timeoutMs?: number; +}; + +/** + * @description A text prompt resolved by `getLangfusePrompt`. `isFallback` is `true` when `text` is the caller's fallback, which carries no `version`. + */ +export type LangfusePrompt = LangfusePromptRef & { + /** Prompt text to send to the model. */ + text: string; + isFallback: boolean; }; // ============================================================================= diff --git a/test/continuous-test-suite-observability.ts b/test/continuous-test-suite-observability.ts index 4989d4eeed..ff5c1fe47b 100644 --- a/test/continuous-test-suite-observability.ts +++ b/test/continuous-test-suite-observability.ts @@ -38,11 +38,12 @@ import { assert, assertEqual, defineSuite, + delay, runCommand, tempDir, } from "./helpers/harness.js"; import { assertDistFresh } from "./helpers/distFreshness.js"; -import type { GenerateOptions } from "../dist/index.js"; +import type { GenerateOptions, LangfusePromptRef } from "../dist/index.js"; assertDistFresh(); @@ -83,6 +84,7 @@ const { AIProviderFactory, NeuroLink, getLangfuseHealthStatus, + getLangfusePrompt, jsonSchema, setLangfuseContext, } = await import("../dist/index.js"); @@ -531,6 +533,18 @@ async function startLangfuse(mode: OtlpMode = "ok"): Promise<{ answer(500, { message: "boom" }); return; } + if (req.url?.startsWith("/api/public/v2/prompts/")) { + answer(200, { + name: "owned-prompt", + version: 3, + type: "text", + prompt: "owned text", + labels: ["production"], + tags: [], + config: {}, + }); + return; + } spans.forEach((span) => sends.set(span.spanId, (sends.get(span.spanId) ?? 0) + 1), ); @@ -1650,6 +1664,524 @@ await test("shutting down another instance keeps this one exporting", async () = assertEqual(named(await exported(), "generate").length, 1); }); +section("langfuse prompts"); + +const startPrompts = async (): Promise<{ + baseUrl: string; + hits: Map; + authorizations: Set; + releaseFailures: () => void; + close: () => Promise; +}> => { + const hits = new Map(); + const authorizations = new Set(); + const held = new Set(); + const failures: ServerResponse[] = []; + const send = (res: ServerResponse, status: number, body: JsonBody): void => { + res.writeHead(status, { "content-type": "application/json" }); + res.end(JSON.stringify(body)); + }; + const notFound = { message: "Prompt not found" }; + const server = createServer((req, res) => { + const url = new URL(req.url ?? "", "http://127.0.0.1"); + const name = decodeURIComponent(url.pathname.split("/").pop() ?? ""); + const count = (hits.get(name) ?? 0) + 1; + hits.set(name, count); + authorizations.add(req.headers.authorization ?? ""); + const label = url.searchParams.get("label") ?? "production"; + const serve = (type: string, body: Json): void => + send(res, 200, { + name, + version: 6 + count, + labels: [label], + tags: [], + config: {}, + type, + prompt: body, + }); + const hold = (): void => { + held.add(res); + res.on("close", () => held.delete(res)); + }; + switch (name.split("-")[0]) { + case "hold": + hold(); + return; + case "stall": + res.writeHead(200, { "content-type": "application/json" }); + res.write("{"); + hold(); + return; + case "malformed": + serve("text", ["x"]); + return; + case "flaky": + if (count === 1) { + serve("text", "kept"); + return; + } + failures.push(res); + return; + case "reflect": + send(res, 401, { + message: "Unauthorized", + authorization: req.headers.authorization, + }); + return; + case "missing": + send(res, 404, notFound); + return; + case "chat": + serve("chat", [{ role: "system", content: "chat text" }]); + return; + default: + serve("text", `text for ${label}`); + } + }); + const port = await listen(server); + return { + baseUrl: `http://127.0.0.1:${port}`, + hits, + authorizations, + releaseFailures: () => + failures.splice(0).forEach((res) => send(res, 404, notFound)), + close: () => closeServer(server, held), + }; +}; + +const fallback = "fallback text"; + +const assertFallback = async ( + name: string, + options: { timeoutMs?: number } = {}, +): Promise => { + const prompt = await getLangfusePrompt(name, { fallback, ...options }); + assertEqual(prompt.name, name, "fallback name"); + assertEqual(prompt.text, fallback, "fallback text"); + assert(!("version" in prompt), "a fallback carries a version"); + assertEqual(prompt.isFallback, true, "not marked as a fallback"); +}; + +const prompts = await startPrompts(); +process.env.LANGFUSE_BASE_URL = prompts.baseUrl; + +await test("getLangfusePrompt fetches a text prompt by label with the environment keys", async () => { + const prompt = await getLangfusePrompt("text-fetch", { + label: "staging", + fallback, + }); + assertEqual(prompt.text, "text for staging", "prompt text"); + assertEqual(prompt.version, 7, "prompt version"); + assertEqual(prompt.label, "staging", "prompt label"); + assertEqual(prompt.isFallback, false, "fetched prompt marked as fallback"); + assert( + prompts.authorizations.has( + `Basic ${Buffer.from("pk-test:sk-test").toString("base64")}`, + ), + "the request did not authenticate with the environment keys", + ); +}); + +await test("a second call within the TTL makes no request", async () => { + const prompt = await getLangfusePrompt("text-fetch", { + label: "staging", + fallback, + }); + assertEqual(prompt.version, 7, "cached version"); + assertEqual(prompts.hits.get("text-fetch"), 1, "the cache was bypassed"); +}); + +await test("concurrent first calls share one request", async () => { + const [first, second] = await Promise.all([ + getLangfusePrompt("text-shared", { fallback }), + getLangfusePrompt("text-shared", { fallback }), + ]); + assertEqual(first.version, 7, "first caller version"); + assertEqual(second.version, 7, "second caller version"); + assertEqual(prompts.hits.get("text-shared"), 1, "callers did not share"); +}); + +await test("an expired prompt returns at once and refreshes once in the background", async () => { + const options = { fallback, cacheTtlMs: 50 }; + await getLangfusePrompt("text-stale", options); + await delay(80); + const stale = await getLangfusePrompt("text-stale", options); + assertEqual(stale.version, 7, "the stale prompt was not returned at once"); + for (let attempt = 0; attempt < 40; attempt++) { + const refreshed = await getLangfusePrompt("text-stale", options); + if (refreshed.version === 8) { + break; + } + await delay(10); + } + assertEqual(prompts.hits.get("text-stale"), 2, "refresh request count"); + assertEqual( + (await getLangfusePrompt("text-stale", options)).version, + 8, + "the refreshed prompt was not served", + ); +}); + +await test("a missing prompt returns the fallback and is not retried within the TTL", async () => { + await assertFallback("missing-prompt"); + await assertFallback("missing-prompt"); + assertEqual(prompts.hits.get("missing-prompt"), 1, "the failure was retried"); +}); + +await test("a chat prompt returns the fallback", async () => { + await assertFallback("chat-prompt"); +}); + +await test("a Langfuse that never answers returns the fallback within the timeout", async () => { + const started = Date.now(); + await assertFallback("hold-prompt", { timeoutMs: 200 }); + assert(Date.now() - started < 1_500, "the timeout was not honoured"); + assertEqual(prompts.hits.get("hold-prompt"), 1, "the request was retried"); +}); + +await test("a Langfuse that stalls the body returns the fallback within the timeout", async () => { + const started = Date.now(); + await assertFallback("stall-prompt", { timeoutMs: 200 }); + assert(Date.now() - started < 1_500, "the timeout stopped at the headers"); + assertEqual( + prompts.hits.get("stall-prompt"), + 1, + "the fixture was not reached", + ); +}); + +await test("a timed-out fetch does not hold the process open", async () => { + const started = Date.now(); + const result = await runCommand( + process.execPath, + [ + "--input-type=module", + "-e", + `import { getLangfusePrompt } from ${JSON.stringify( + pathToFileURL(join(process.cwd(), "dist/index.js")).href, + )}; +await getLangfusePrompt("hold-exit", { fallback: "f", timeoutMs: 200 });`, + ], + { + cwd: process.cwd(), + timeoutMs: 45_000, + env: { + PATH: process.env.PATH, + HOME: process.env.HOME, + DOTENV_CONFIG_PATH: "/dev/null", + LANGFUSE_PUBLIC_KEY: "pk-test", + LANGFUSE_SECRET_KEY: "sk-test", + LANGFUSE_BASE_URL: prompts.baseUrl, + }, + }, + ); + assertEqual(result.exitCode, 0, "child process failed"); + assert( + Date.now() - started < 15_000, + "the process stayed open after the timeout", + ); +}); + +await test("a text prompt with a malformed body returns the fallback", async () => { + await assertFallback("malformed-prompt"); +}); + +await test("a caller changing its options mid-fetch does not move the cache entry", async () => { + const options = { label: "first", fallback }; + const pending = getLangfusePrompt("text-label", options); + options.label = "second"; + const prompt = await pending; + assertEqual(prompt.label, "first", "returned label"); + assertEqual(prompt.text, "text for first", "returned text"); + const cached = await getLangfusePrompt("text-label", { + label: "first", + fallback, + }); + assertEqual(cached.text, "text for first", "cached text"); + assertEqual(prompts.hits.get("text-label"), 1, "the cache missed"); +}); + +await test("changing a returned prompt does not change the cache", async () => { + const first = await getLangfusePrompt("text-copy", { fallback }); + first.text = "rendered"; + const second = await getLangfusePrompt("text-copy", { fallback }); + assertEqual(second.text, "text for production", "the cache was mutated"); +}); + +await test("the cache drops the least recently fetched prompt beyond its bound", async () => { + for (let index = 0; index <= 500; index++) { + await getLangfusePrompt(`text-bound-${index}`, { fallback }); + } + await getLangfusePrompt("text-bound-0", { fallback }); + assertEqual(prompts.hits.get("text-bound-0"), 2, "the oldest entry stayed"); + await getLangfusePrompt("text-bound-500", { fallback }); + assertEqual(prompts.hits.get("text-bound-500"), 1, "a recent entry left"); +}); + +await test("a failed refresh keeps the last prompt even when it was evicted meanwhile", async () => { + const options = { fallback, cacheTtlMs: 1 }; + await getLangfusePrompt("flaky-evict", options); + await delay(5); + await getLangfusePrompt("flaky-evict", options); + await Promise.all( + Array.from({ length: 500 }, (_, index) => + getLangfusePrompt(`text-evict-${index}`, { fallback }), + ), + ); + prompts.releaseFailures(); + await delay(100); + const prompt = await getLangfusePrompt("flaky-evict", { fallback }); + assertEqual(prompt.text, "kept", "the last prompt was lost"); +}); + +const fallbackWarning = async (name: string): Promise => { + const warnings: string[] = []; + const warn = console.warn; + const debug = process.env.NEUROLINK_DEBUG; + console.warn = (...args: string[]) => { + warnings.push(args.join(" ")); + }; + process.env.NEUROLINK_DEBUG = "true"; + try { + await assertFallback(name); + } finally { + console.warn = warn; + if (debug === undefined) { + delete process.env.NEUROLINK_DEBUG; + } else { + process.env.NEUROLINK_DEBUG = debug; + } + } + const line = warnings.find((warning) => warning.includes(name)) ?? ""; + assert(line.length > 0, "no warning for the failed fetch"); + return line; +}; + +await test("a failed fetch logs the status code and never the response body", async () => { + const line = await fallbackWarning("reflect-prompt"); + assert(line.includes("401"), "the warning has no status code"); + assert(!line.includes("Basic "), "the warning carries the response body"); +}); + +await test("a refused connection logs why the fetch failed", async () => { + const closed = createServer(); + const port = await listen(closed); + await closeServer(closed, new Set()); + process.env.LANGFUSE_BASE_URL = `http://127.0.0.1:${port}`; + try { + const line = await fallbackWarning("refused-prompt"); + assert(line.includes("fetch failed"), "the warning gives no reason"); + } finally { + process.env.LANGFUSE_BASE_URL = prompts.baseUrl; + } +}); + +await test("without keys the fallback returns and no request is made", async () => { + delete process.env.LANGFUSE_PUBLIC_KEY; + try { + await assertFallback("text-nokeys"); + } finally { + process.env.LANGFUSE_PUBLIC_KEY = "pk-test"; + } + assert(!prompts.hits.has("text-nokeys"), "a request was made"); +}); + +const tagsOf = (span: ReadableSpan): string[] => { + const tags = span.attributes["langfuse.trace.tags"]; + return Array.isArray(tags) ? tags.map(String) : []; +}; + +const generationOf = (spans: ReadableSpan[]): ReadableSpan => { + const generations = ofType(spans, "generation"); + assertEqual(generations.length, 1, "expected exactly one generation"); + return generations[0]; +}; + +const perCallGeneration = async ( + prompt: LangfusePromptRef, +): Promise => { + clear(); + await nl.generate( + request("gpt-4o-mini", { context: { ...context, prompt } }), + ); + return generationOf(await exported()); +}; + +await test("setLangfuseContext links generations to the prompt version", async () => { + const prompt = await getLangfusePrompt("text-link", { + label: "production", + fallback, + }); + clear(); + await setLangfuseContext({ prompt }, () => + nl.generate(request("gpt-4o-mini")), + ); + const spans = await exported(); + const generation = generationOf(spans); + assertEqual( + generation.attributes["langfuse.observation.prompt.name"], + "text-link", + ); + assertEqual(generation.attributes["langfuse.observation.prompt.version"], 7); + const tags = tagsOf(generation); + assert(tags.includes("prompt:text-link@7"), "no prompt tag"); + assert(tags.includes(TAG), "the caller's tags were not kept"); + const root = only(spans, "generate"); + assertEqual( + root.attributes["langfuse.trace.metadata.promptName"], + "text-link", + ); + assertEqual(root.attributes["langfuse.trace.metadata.promptVersion"], "7"); + assertEqual( + root.attributes["langfuse.trace.metadata.promptLabel"], + "production", + ); +}); + +await test("a per-call context prompt links generations to the prompt version", async () => { + const prompt = await getLangfusePrompt("text-link", { + label: "production", + fallback, + }); + const generation = await perCallGeneration(prompt); + assertEqual(generation.attributes["langfuse.observation.prompt.version"], 7); + assert(tagsOf(generation).includes("prompt:text-link@7"), "no prompt tag"); +}); + +await test("a fallback prompt is tagged but never linked", async () => { + const prompt = await getLangfusePrompt("missing-link", { fallback }); + clear(); + await setLangfuseContext({ prompt }, () => + nl.generate(request("gpt-4o-mini")), + ); + for (const span of await everySpan()) { + assert( + !("langfuse.observation.prompt.name" in span.attributes), + `${span.name} links a fallback prompt`, + ); + } + const generation = generationOf(await exported()); + assert( + tagsOf(generation).includes("prompt:missing-link@fallback"), + "no fallback prompt tag", + ); +}); + +await test("a per-call prompt fetched without a label still links", async () => { + const prompt = await getLangfusePrompt("text-nolabel", { fallback }); + const generation = await perCallGeneration(prompt); + assertEqual(generation.attributes["langfuse.observation.prompt.version"], 7); + assert(tagsOf(generation).includes("prompt:text-nolabel@7"), "no prompt tag"); +}); + +await test("caller prompt metadata survives when no prompt is given", async () => { + clear(); + await setLangfuseContext({ metadata: { promptName: "mine" } }, () => + nl.generate(request("gpt-4o-mini")), + ); + assertEqual( + only(await exported(), "generate").attributes[ + "langfuse.trace.metadata.promptName" + ], + "mine", + ); +}); + +await test("a per-call prompt with a non-integer version is ignored", async () => { + const generation = await perCallGeneration({ + name: "fractional", + version: 1.5, + }); + assert( + !tagsOf(generation).includes("prompt:fractional@1.5"), + "an invalid version was tagged", + ); +}); + +await test("a prompt scope leaves the span already running untouched", async () => { + const prompt = await getLangfusePrompt("text-parent", { fallback }); + clear(); + hostProvider.getTracer("prompt-scope").startActiveSpan("running", (span) => { + setLangfuseContext({ prompt }, () => 0); + span.end(); + }); + assert( + !( + "langfuse.observation.prompt.name" in + only(await everySpan(), "running").attributes + ), + "the running span took the inner prompt link", + ); +}); + +await test("a fallback inside a managed-prompt scope drops the outer link", async () => { + const outer = await getLangfusePrompt("text-outer", { fallback }); + const inner = await getLangfusePrompt("missing-inner", { fallback }); + clear(); + await setLangfuseContext({ prompt: outer }, () => + setLangfuseContext({ prompt: inner }, () => + nl.generate(request("gpt-4o-mini")), + ), + ); + assert( + !( + "langfuse.observation.prompt.name" in + generationOf(await exported()).attributes + ), + "the generation kept the outer prompt link", + ); +}); + +await test("a prompt inside another prompt's scope replaces its metadata", async () => { + const outer = await getLangfusePrompt("text-outer", { + label: "production", + fallback, + }); + const inner = await getLangfusePrompt("missing-inner", { fallback }); + clear(); + await setLangfuseContext({ prompt: outer }, () => + setLangfuseContext({ prompt: inner }, () => + nl.generate(request("gpt-4o-mini")), + ), + ); + const spans = await exported(); + generationOf(spans); + for (const span of spans) { + assertEqual( + span.attributes["langfuse.trace.metadata.promptName"], + "missing-inner", + `${span.name} prompt name`, + ); + for (const key of ["promptVersion", "promptLabel"]) { + assert( + !(`langfuse.trace.metadata.${key}` in span.attributes), + `${span.name} kept the outer ${key}`, + ); + } + } +}); + +await test("a prompt inside another prompt's scope replaces its tag", async () => { + const outer = await getLangfusePrompt("text-outer", { fallback }); + const inner = await getLangfusePrompt("missing-inner", { fallback }); + clear(); + await setLangfuseContext({ prompt: outer, tags: ["caller"] }, () => + setLangfuseContext({ prompt: inner }, () => + nl.generate(request("gpt-4o-mini")), + ), + ); + const tags = tagsOf(generationOf(await exported())); + assert(tags.includes("prompt:missing-inner@fallback"), "no inner tag"); + assert(tags.includes("caller"), "the caller's tag was dropped"); + assert( + !tags.some((tag) => tag.startsWith("prompt:text-outer")), + "the outer prompt tag was kept", + ); +}); + +delete process.env.LANGFUSE_BASE_URL; +await prompts.close(); + section("owned provider"); const CHILD = join(tempDir("neurolink-obs-child-"), "child.mjs"); @@ -1875,7 +2407,7 @@ const SCENARIO = join(tempDir("neurolink-obs-scenario-"), "scenario.mjs"); writeFileSync( SCENARIO, ` -import { NeuroLink, AIProviderFactory, flushOpenTelemetry, jsonSchema, setLangfuseContext, shutdownOpenTelemetry } from ${JSON.stringify( +import { NeuroLink, AIProviderFactory, flushOpenTelemetry, getLangfusePrompt, jsonSchema, setLangfuseContext, shutdownOpenTelemetry } from ${JSON.stringify( pathToFileURL(join(process.cwd(), "dist/index.js")).href, )}; const env = process.env; @@ -1900,6 +2432,10 @@ if (scenario === "outer") { const turn = await nl.stream(call("tool-model", { disableTools: false, maxSteps: 3, tools: nesting, context: { ...context, metadata: { winner: "inner", perCall: url } } })); await drain(turn.stream); }); +} else if (scenario === "prompt") { + const prompt = await getLangfusePrompt("owned-prompt", { fallback: "fb" }); + if (prompt.isFallback || prompt.version !== 3) process.exit(3); + await setLangfuseContext({ prompt }, () => nl.generate(call("gpt-4o-mini"))); } else if (scenario === "named") { await nl.generate(call("gpt-4o-mini", { context: { ...context, traceName: "trace-x", observationName: "orchestrator-llm-generation" } })); await nl.generate(call("gpt-4o-mini")); @@ -2414,6 +2950,29 @@ await test("observationName renames the root agent observation only", async () = ); }); +await test("NeuroLink's own Langfuse exporter keeps the prompt link and fetches with the config keys", async () => { + const owned = await runScenario("prompt"); + assert( + owned.spans.some( + (span) => + kind(span) === "generation" && + span.attributes["langfuse.observation.prompt.name"] === + "owned-prompt" && + span.attributes["langfuse.observation.prompt.version"] === 3, + ), + "no generation carries the prompt link", + ); + assert( + owned.hits.some( + (hit) => + hit.path.startsWith("/api/public/v2/prompts/owned-prompt") && + hit.authorization === + `Basic ${Buffer.from("pk-i:sk-i").toString("base64")}`, + ), + "the prompt was not fetched from the config host with the config keys", + ); +}); + section("host provider"); const HOST = join(tempDir("neurolink-obs-host-"), "host.mjs");