🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(evals): prevent recursion through OpenRouter Broadcast (#15669)
Hassieb Pakzadef06b05a2313
diff --git a/packages/shared/src/server/llm/ai-sdk/providers/openai.ts b/packages/shared/src/server/llm/ai-sdk/providers/openai.tsindex 649fe49143..fce954fbb3 100644--- a/packages/shared/src/server/llm/ai-sdk/providers/openai.ts+++ b/packages/shared/src/server/llm/ai-sdk/providers/openai.ts@@ -2,6 +2,7 @@ import { createOpenAI } from "@ai-sdk/openai";import { createOpenAICompatible } from "@ai-sdk/openai-compatible";import type { LanguageModel } from "ai";+import { parseOutboundUrl } from "../../../outbound-url/validation";import { processOpenAIBaseURL } from "../../utils";import type { TranslatedProviderOptions } from "./types";import { isPlainObject } from "./utils";@@ -72,6 +73,22 @@ export function isOpenAICompatibleEndpoint(}}+export function isOpenRouterEndpoint(+ baseURL: string | null | undefined,+): baseURL is string {+ if (!baseURL) return false;++ try {+ const url = parseOutboundUrl(baseURL.replace("{model}", "model"));+ if (!["http:", "https:"].includes(url.protocol)) return false;++ const hostname = url.hostname.replace(/\.$/, "");+ return hostname === "openrouter.ai" || hostname.endsWith(".openrouter.ai");+ } catch {+ return false;+ }+}+/*** Translation of Langfuse `modelParams.providerOptions` to AI SDK OpenAI* provider options.diff --git a/packages/shared/src/server/llm/ai-sdk/requestShape.test.ts b/packages/shared/src/server/llm/ai-sdk/requestShape.test.tsindex 94def06971..109ceaee4c 100644--- a/packages/shared/src/server/llm/ai-sdk/requestShape.test.ts+++ b/packages/shared/src/server/llm/ai-sdk/requestShape.test.ts@@ -7,6 +7,7 @@ import {ChatMessageType,LLMAdapter,type ModelParams,+ type TraceSinkParams,} from "../types";import {createLLMOutput,@@ -20,6 +21,12 @@ vi.mock("../secureLlmFetch", () => ({createSecureLlmFetch: () => globalThis.fetch,}));+// Request-shape tests only need the trace context as an input to provider+// request construction. Internal telemetry publishing is covered separately.+vi.mock("./telemetry", () => ({+ createAiSdkTelemetryCapture: () => undefined,+}));+// The Vertex provider exchanges service-account credentials for an OAuth// token via google-auth-library before issuing the model request; both the// provider and our vertex builder resolve to the same library copy, so this@@ -171,6 +178,7 @@ async function runCompletion(params: {llmConnectionConfig?: Record<string, string | boolean>;output?: ReturnType<typeof createLLMOutput>;response: unknown;+ trace?: TraceSinkParams;}) {const { calls, fetch } = createCaptureFetch(params.response);vi.stubGlobal("fetch", fetch);@@ -189,6 +197,7 @@ async function runCompletion(params: {}),timeout: 10_000,output: params.output,+ trace: params.trace,});expect(calls).toHaveLength(1);@@ -201,6 +210,13 @@ afterEach(() => {});describe("AI SDK request shapes", () => {+ const internalTrace: TraceSinkParams = {+ targetProjectId: "project-1",+ traceId: "1".repeat(32),+ traceName: "Execute evaluator: helpfulness",+ environment: "langfuse-llm-as-a-judge",+ };+it("OpenAI chat completions: default URL, bearer auth, translated body params", async () => {const { result, request } = await runCompletion({modelParams: {@@ -284,6 +300,75 @@ describe("AI SDK request shapes", () => {expect(request.body.thinkingLevel).toBe("high");});+ it.each([+ {+ baseURL: "https://openrouter.ai/api/v1",+ providerOptions: undefined,+ expectedTrace: { environment: "langfuse-llm-as-a-judge" },+ },+ {+ baseURL: "https://openrouter.ai./api/v1",+ providerOptions: undefined,+ expectedTrace: { environment: "langfuse-llm-as-a-judge" },+ },+ {+ baseURL: "https://eu.openrouter.ai/api/v1",+ providerOptions: {+ trace: {+ environment: "customer-environment",+ feature: "support-agent",+ },+ },+ expectedTrace: {+ environment: "langfuse-llm-as-a-judge",+ feature: "support-agent",+ },+ },+ ])(+ "OpenRouter: propagates system-owned internal provenance and preserves trace metadata for $baseURL",+ async ({ baseURL, providerOptions, expectedTrace }) => {+ const { request } = await runCompletion({+ modelParams: {+ provider: "openrouter",+ adapter: LLMAdapter.OpenAI,+ model: "openai/gpt-4o-mini",+ providerOptions,+ },+ apiKey: "openrouter-key",+ baseURL,+ trace: internalTrace,+ response: OPENAI_CHAT_RESPONSE,+ });++ expect(request.body.trace).toEqual(expectedTrace);+ },+ );++ it("other OpenAI-compatible endpoints keep customer trace metadata unchanged", async () => {+ const { request } = await runCompletion({+ modelParams: {+ provider: "custom",+ adapter: LLMAdapter.OpenAI,+ model: "custom-model",+ providerOptions: {+ trace: {+ environment: "customer-environment",+ feature: "support-agent",+ },+ },+ },+ apiKey: "custom-key",+ baseURL: "https://openrouter.ai.example.com/v1",+ trace: internalTrace,+ response: OPENAI_CHAT_RESPONSE,+ });++ expect(request.body.trace).toEqual({+ environment: "customer-environment",+ feature: "support-agent",+ });+ });+it("OpenAI-compatible chat completions: preserves JSON schema response_format", async () => {const { result, request } = await runCompletion({modelParams: {diff --git a/packages/shared/src/server/llm/llmText.ts b/packages/shared/src/server/llm/llmText.tsindex e813775aac..55937c4bc2 100644--- a/packages/shared/src/server/llm/llmText.ts+++ b/packages/shared/src/server/llm/llmText.ts@@ -31,6 +31,7 @@ import { translateBedrockProviderOptions } from "./ai-sdk/providers/bedrock";import { translateGoogleProviderOptions } from "./ai-sdk/providers/google";import {isOpenAICompatibleEndpoint,+ isOpenRouterEndpoint,translateOpenAIProviderOptions,} from "./ai-sdk/providers/openai";import type {@@ -289,6 +290,14 @@ async function prepareLLMTextCall<});recordAiSdkExecution({ model: options.model, modelConfig });+ const providerOptions = addOpenRouterInternalTraceProvenance({+ model: options.model,+ baseURL: options.connection.baseURL,+ apiMode: modelConfig.openAIApiMode,+ providerOptions: options.providerOptions,+ trace: options.trace,+ });+const apiKey = decrypt(options.connection.secretKey);const extraHeaders = decryptAndParseExtraHeaders(options.connection.extraHeaders,@@ -339,7 +348,7 @@ async function prepareLLMTextCall<temperature: options.temperature,topP: options.topP,reasoning: options.reasoning,- providerOptions: options.providerOptions,+ providerOptions,maxRetries: options.maxRetries,timeout,abortSignal: options.abortSignal,@@ -351,6 +360,47 @@ async function prepareLLMTextCall<};}+function addOpenRouterInternalTraceProvenance(params: {+ model: LLMModelRef;+ baseURL?: string | null;+ apiMode?: "responses" | "chat-completions";+ providerOptions?: ProviderOptions;+ trace?: TraceSinkParams;+}): ProviderOptions | undefined {+ if (+ params.model.adapter !== LLMAdapter.OpenAI ||+ params.apiMode !== "chat-completions" ||+ !params.trace ||+ !isOpenRouterEndpoint(params.baseURL)+ ) {+ return params.providerOptions;+ }++ const openAIOptions = params.providerOptions?.openai ?? {};+ const existingTrace = isJsonObject(openAIOptions.trace)+ ? openAIOptions.trace+ : {};++ return {+ ...params.providerOptions,+ openai: {+ ...openAIOptions,+ trace: {+ ...existingTrace,+ // This marker controls evaluator recursion prevention and must remain+ // system-owned even when the caller supplies other Broadcast metadata.+ environment: params.trace.environment,+ },+ },+ };+}++function isJsonObject(+ value: JSONValue | undefined,+): value is Record<string, JSONValue> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}+const rejectRemoteMediaDownloads: Experimental_DownloadFunction = async (downloads,) => {diff --git a/worker/src/__tests__/evalService.test.ts b/worker/src/__tests__/evalService.test.tsindex aca8a413d8..505592f163 100644--- a/worker/src/__tests__/evalService.test.ts+++ b/worker/src/__tests__/evalService.test.ts@@ -3175,55 +3175,58 @@ Respond with JSON: {"score": <number>, "reasoning": "<explanation>"}`;});describe("internal trace environment filtering", () => {- test("does not create eval jobs for trace-upsert with LLMJudge environment", async () => {- const { projectId } = await createOrgProjectAndApiKey();- const traceId = randomUUID();-- // Create trace with LLMJudge environment- await upsertTrace({- id: traceId,- project_id: projectId,- environment: LangfuseInternalTraceEnvironment.LLMJudge,- timestamp: convertDateToClickhouseDateTime(new Date()),- created_at: convertDateToClickhouseDateTime(new Date()),- updated_at: convertDateToClickhouseDateTime(new Date()),- });+ test.each([LangfuseInternalTraceEnvironment.LLMJudge, "llm-as-a-judge"])(+ "does not create eval jobs for trace-upsert with %s environment",+ async (environment) => {+ const { projectId } = await createOrgProjectAndApiKey();+ const traceId = randomUUID();- // Create an active eval configuration- await prisma.jobConfiguration.create({- data: {- id: randomUUID(),- projectId,- filter: JSON.parse("[]"),- jobType: "EVAL",- delay: 0,- sampling: new Decimal("1"),- targetObject: EvalTargetObject.TRACE,- scoreName: "score",- variableMapping: JSON.parse("[]"),- },- });+ await upsertTrace({+ id: traceId,+ project_id: projectId,+ environment,+ timestamp: convertDateToClickhouseDateTime(new Date()),+ created_at: convertDateToClickhouseDateTime(new Date()),+ updated_at: convertDateToClickhouseDateTime(new Date()),+ });- const payload = {- projectId,- traceId,- traceEnvironment: LangfuseInternalTraceEnvironment.LLMJudge,- };+ // Create an active eval configuration+ await prisma.jobConfiguration.create({+ data: {+ id: randomUUID(),+ projectId,+ filter: JSON.parse("[]"),+ jobType: "EVAL",+ delay: 0,+ sampling: new Decimal("1"),+ targetObject: EvalTargetObject.TRACE,+ scoreName: "score",+ variableMapping: JSON.parse("[]"),+ },+ });- // Attempt to create eval jobs- await createEvalJobs({- sourceEventType: "trace-upsert",- event: payload,- jobTimestamp,- });+ const payload = {+ projectId,+ traceId,+ traceEnvironment: environment,+ };++ // Attempt to create eval jobs+ await createEvalJobs({+ sourceEventType: "trace-upsert",+ event: payload,+ jobTimestamp,+ });- // Verify no eval jobs were created- const jobs = await prisma.jobExecution.findMany({- where: { projectId },- });+ // Verify no eval jobs were created+ const jobs = await prisma.jobExecution.findMany({+ where: { projectId },+ });- expect(jobs.length).toBe(0);- }, 10_000);+ expect(jobs.length).toBe(0);+ },+ 10_000,+ );test("does not create eval jobs for trace-upsert with PromptExperiments environment", async () => {const { projectId } = await createOrgProjectAndApiKey();diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.tsindex f902197439..f973baa858 100644--- a/worker/src/features/evaluation/evalService.ts+++ b/worker/src/features/evaluation/evalService.ts@@ -80,7 +80,10 @@ import {completeEvalExecution,type EvalExecutionResult,} from "./evalCompletion";-import { isEvalTargetEnvironmentAllowed } from "./isEvalTargetEnvironmentAllowed";+import {+ isEvalTargetEnvironmentAllowed,+ isInternalEvalEnvironment,+} from "./isEvalTargetEnvironmentAllowed";import {type EvalExecutionDeps,createProductionEvalExecutionDeps,@@ -235,20 +238,19 @@ export const createEvalJobs = async ({// Without this safeguard: user trace → eval → eval trace → another eval → infinite loop//// IMPLEMENTATION:- // - Block ALL traces with environment starting with "langfuse-" when coming from trace-upsert queue+ // - Block internal environments and their public-ingestion aliases when coming from trace-upsert queue// - This excludes traces from prompt experiments that come via dataset-run-item-upsert queue// - Internal traces (e.g., eval executions) use LangfuseInternalTraceEnvironment enum values//- // DUAL SAFEGUARD:+ // DEFENSE IN DEPTH:// - This check prevents eval job CREATION for internal traces- // - The shared LLM runtime enforces that internal traces MUST use the- // "langfuse-" prefix+ // - Eval executors repeat the same environment check before execution//// See: packages/shared/src/server/llm (enforcement)// See: packages/shared/src/server/llm/types.ts (LangfuseInternalTraceEnvironment enum)if (sourceEventType === "trace-upsert" &&- event.traceEnvironment?.startsWith("langfuse")+ isInternalEvalEnvironment(event.traceEnvironment)) {logger.debug("Skipping eval job creation for internal Langfuse trace", {traceId: event.traceId,diff --git a/worker/src/features/evaluation/isEvalTargetEnvironmentAllowed.test.ts b/worker/src/features/evaluation/isEvalTargetEnvironmentAllowed.test.tsindex 98a7abf1ba..908d290bc7 100644--- a/worker/src/features/evaluation/isEvalTargetEnvironmentAllowed.test.ts+++ b/worker/src/features/evaluation/isEvalTargetEnvironmentAllowed.test.ts@@ -16,6 +16,7 @@ describe("isEvalTargetEnvironmentAllowed", () => {it("blocks eval-on-eval targets across all internal environments", () => {for (const environment of ["langfuse-llm-as-a-judge",+ "llm-as-a-judge","langfuse-code-eval","langfuse-natural-language-filter","langfuse-in-app-agent",diff --git a/worker/src/features/evaluation/isEvalTargetEnvironmentAllowed.ts b/worker/src/features/evaluation/isEvalTargetEnvironmentAllowed.tsindex f82eed4bd4..42ddd939fa 100644--- a/worker/src/features/evaluation/isEvalTargetEnvironmentAllowed.ts+++ b/worker/src/features/evaluation/isEvalTargetEnvironmentAllowed.ts@@ -1,13 +1,27 @@import { LangfuseInternalTraceEnvironment } from "@langfuse/shared/src/server";+// Public ingestion strips the reserved `langfuse-` prefix from environments+// originating outside Langfuse, including OpenRouter Broadcast callbacks.+const PUBLIC_LLM_JUDGE_ENVIRONMENT = "llm-as-a-judge";++export function isInternalEvalEnvironment(+ environment: string | null | undefined,+): boolean {+ return (+ environment?.startsWith("langfuse") === true ||+ environment === PUBLIC_LLM_JUDGE_ENVIRONMENT+ );+}+/*** Final, fail-closed loop safeguard at eval EXECUTION time.** Internal Langfuse executions (LLM-as-a-judge, code evals, natural-language- * filters) write their telemetry into reserved `langfuse-*` environments. An- * eval whose TARGET lives in such an environment is an eval-of-an-eval: it- * would spawn another internal execution, whose telemetry could be evaluated- * again — an infinite loop with per-cycle LLM cost.+ * filters) write their telemetry into reserved `langfuse-*` environments.+ * Public ingestion may store a recognized alias without that prefix. An eval+ * whose TARGET lives in either form is an eval-of-an-eval: it would spawn+ * another internal execution, whose telemetry could be evaluated again — an+ * infinite loop with per-cycle LLM cost.** Scheduling-time guards exist per entry point (trace-upsert in* createEvalJobs, the OTel queue's observation-eval guard), but every new@@ -26,7 +40,7 @@ import { LangfuseInternalTraceEnvironment } from "@langfuse/shared/src/server";export function isEvalTargetEnvironmentAllowed(environment: string | null | undefined,): boolean {- if (!environment?.startsWith("langfuse")) {+ if (!isInternalEvalEnvironment(environment)) {return true;}diff --git a/worker/src/features/evaluation/observationEval/__tests__/isObservationAllowedForQueuedObservationEvals.test.ts b/worker/src/features/evaluation/observationEval/__tests__/isObservationAllowedForQueuedObservationEvals.test.tsindex 49526689fd..aeda09b4e9 100644--- a/worker/src/features/evaluation/observationEval/__tests__/isObservationAllowedForQueuedObservationEvals.test.ts+++ b/worker/src/features/evaluation/observationEval/__tests__/isObservationAllowedForQueuedObservationEvals.test.ts@@ -23,18 +23,21 @@ describe("isObservationAllowedForQueuedObservationEvals", () => {).toBe(true);});- it("blocks LLM-as-a-judge observations to prevent eval-on-eval recursion", () => {- // LLM-as-a-judge executions publish their telemetry through the OTel- // ingestion pipeline; scheduling evals on those observations would spawn- // evals of evals indefinitely.- expect(- isObservationAllowedForQueuedObservationEvals({- environment: "langfuse-llm-as-a-judge",- span_id: ROOT_SPAN_ID,- experiment_item_root_span_id: ROOT_SPAN_ID,- }),- ).toBe(false);- });+ it.each(["langfuse-llm-as-a-judge", "llm-as-a-judge"])(+ "blocks %s observations to prevent eval-on-eval recursion",+ (environment) => {+ // LLM-as-a-judge executions publish their telemetry through the OTel+ // ingestion pipeline; scheduling evals on those observations would spawn+ // evals of evals indefinitely.+ expect(+ isObservationAllowedForQueuedObservationEvals({+ environment,+ span_id: ROOT_SPAN_ID,+ experiment_item_root_span_id: ROOT_SPAN_ID,+ }),+ ).toBe(false);+ },+ );it("blocks other internal langfuse environments", () => {for (const environment of [diff --git a/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts b/worker/src/features/evaluation/observationEval/scheduleObservationEvals.tsindex e41067a1ea..c74d89b3e5 100644--- a/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts+++ b/worker/src/features/evaluation/observationEval/scheduleObservationEvals.ts@@ -18,6 +18,7 @@ import {mapEventEvalFilterColumnIdToField,} from "@langfuse/shared";import { createW3CTraceId } from "../../utils";+import { isInternalEvalEnvironment } from "../isEvalTargetEnvironmentAllowed";interface ScheduleObservationEvalsParams {observation: ObservationForEval;@@ -30,7 +31,8 @@ interface ScheduleObservationEvalsParams {* Whether queue-driven (asynchronous OTel ingestion) observation-eval* scheduling is allowed for an observation.*- * Internal Langfuse environments are excluded: LLM-as-a-judge executions+ * Internal Langfuse environments and public-ingestion aliases are excluded:+ * LLM-as-a-judge executions* publish their own telemetry through the OTel ingestion pipeline* (shared AI SDK LLM runtime), and scheduling evals on eval* observations would recurse indefinitely — the observation-eval counterpart@@ -51,7 +53,7 @@ export function isObservationAllowedForQueuedObservationEvals("environment" | "span_id" | "experiment_item_root_span_id">,): boolean {- if (!observation.environment?.startsWith("langfuse")) {+ if (!isInternalEvalEnvironment(observation.environment)) {return true;}