Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(worker): add eval prompt cache key for open ai calls (#14742)

Ravi Kumar L5ffe8d3a543f
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.ts
index 8089914a0b..a55f4955b3 100644
--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts
+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts
@@ -298,6 +298,7 @@ type LLMCompletionParams = {
maxRetries?: number;
traceSinkParams?: TraceSinkParams;
shouldUseLangfuseAPIKey?: boolean;
+ promptCacheKey?: string;
};
type FetchLLMCompletionParams = LLMCompletionParams & {
@@ -350,6 +351,7 @@ export async function fetchLLMCompletion(
maxRetries,
traceSinkParams,
shouldUseLangfuseAPIKey = false,
+ promptCacheKey,
} = params;
const { baseURL, config } = llmConnection;
@@ -537,6 +539,7 @@ export async function fetchLLMCompletion(
},
useResponsesApi: openAIConfig.useResponsesApi,
modelKwargs: modelParams.providerOptions,
+ promptCacheKey,
timeout: timeoutMs,
});
} else if (modelParams.adapter === LLMAdapter.Azure) {
diff --git a/worker/src/__tests__/secureLlmFetch.test.ts b/worker/src/__tests__/secureLlmFetch.test.ts
index d14edb4a7e..b66e765179 100644
--- a/worker/src/__tests__/secureLlmFetch.test.ts
+++ b/worker/src/__tests__/secureLlmFetch.test.ts
@@ -155,6 +155,93 @@ describe("secure LLM fetch", () => {
},
);
+ test(
+ "OpenAI-compatible base URLs receive prompt cache keys in the request body",
+ { timeout: 30_000 },
+ async () => {
+ const server = await spinUp((_req, _body, res) => {
+ res.setHeader("content-type", "application/json");
+ res.end(OPENAI_RESPONSE_BODY);
+ });
+
+ await fetchLLMCompletion({
+ streaming: false,
+ messages: [
+ {
+ role: "user",
+ content: "What is 2+2? Answer only with the number.",
+ type: ChatMessageType.PublicAPICreated,
+ },
+ ],
+ modelParams: {
+ provider: "fireworks",
+ adapter: LLMAdapter.OpenAI,
+ model: "accounts/fireworks/models/kimi-k2-instruct",
+ temperature: 0,
+ max_tokens: 10,
+ },
+ llmConnection: {
+ secretKey: encrypt("fireworks-api-key"),
+ baseURL: `${server.url}/v1`,
+ },
+ promptCacheKey: "lf-eval-v1-cache-key",
+ });
+
+ expect(server.requests).toHaveLength(1);
+ const body = JSON.parse(server.requests[0].body);
+ expect(server.requests[0].url).toBe("/v1/chat/completions");
+ expect(body).toMatchObject({
+ model: "accounts/fireworks/models/kimi-k2-instruct",
+ prompt_cache_key: "lf-eval-v1-cache-key",
+ });
+ },
+ );
+
+ test(
+ "OpenAI Responses API requests receive prompt cache keys",
+ { timeout: 30_000 },
+ async () => {
+ const server = await spinUp((_req, _body, res) => {
+ res.setHeader("content-type", "application/json");
+ res.end(OPENAI_RESPONSES_BODY);
+ });
+
+ await fetchLLMCompletion({
+ streaming: false,
+ messages: [
+ {
+ role: "user",
+ content: "What is 2+2? Answer only with the number.",
+ type: ChatMessageType.PublicAPICreated,
+ },
+ ],
+ modelParams: {
+ provider: "openai",
+ adapter: LLMAdapter.OpenAI,
+ model: "gpt-4o-mini",
+ temperature: 0,
+ max_tokens: 10,
+ },
+ llmConnection: {
+ secretKey: encrypt("openai-api-key"),
+ baseURL: `${server.url}/v1`,
+ config: {
+ useResponsesApi: true,
+ },
+ },
+ promptCacheKey: "lf-eval-v1-cache-key",
+ });
+
+ expect(server.requests).toHaveLength(1);
+ const body = JSON.parse(server.requests[0].body);
+ expect(server.requests[0].url).toBe("/v1/responses");
+ expect(body).toMatchObject({
+ model: "gpt-4o-mini",
+ prompt_cache_key: "lf-eval-v1-cache-key",
+ });
+ },
+ );
+
test(
"OpenAI Responses API config routes through the responses endpoint",
{ timeout: 30_000 },
diff --git a/worker/src/features/evaluation/__tests__/evalExecutionDeps.test.ts b/worker/src/features/evaluation/__tests__/evalExecutionDeps.test.ts
index 9c78b53392..748fdd5676 100644
--- a/worker/src/features/evaluation/__tests__/evalExecutionDeps.test.ts
+++ b/worker/src/features/evaluation/__tests__/evalExecutionDeps.test.ts
@@ -81,6 +81,51 @@ describe("createProductionEvalExecutionDeps", () => {
);
});
+ it("passes the eval prompt cache key to OpenAI calls", async () => {
+ const deps = createProductionEvalExecutionDeps();
+
+ await deps.callLLM({
+ messages: [
+ {
+ role: "user",
+ type: "user",
+ content: "Judge this answer",
+ },
+ ],
+ modelConfig: {
+ provider: "openai",
+ model: "gpt-4.1",
+ apiKey: { adapter: "openai", secretKey: "secret" },
+ adapter: "openai" as any,
+ modelParams: {
+ providerOptions: {
+ seed: 7,
+ },
+ },
+ },
+ structuredOutputSchema: {} as any,
+ promptCacheKey: "lf-eval-v1-cache-key",
+ traceSinkParams: {
+ targetProjectId: "project-123",
+ traceId: "trace-123",
+ traceName: "Judge trace",
+ environment: "langfuse-llm-as-a-judge",
+ metadata: {},
+ },
+ });
+
+ expect(mockFetchLLMCompletion).toHaveBeenCalledWith(
+ expect.objectContaining({
+ promptCacheKey: "lf-eval-v1-cache-key",
+ modelParams: expect.objectContaining({
+ providerOptions: {
+ seed: 7,
+ },
+ }),
+ }),
+ );
+ });
+
it("records llmaj export volume using the schema's JSON Schema form", async () => {
const deps = createProductionEvalExecutionDeps();
diff --git a/worker/src/features/evaluation/evalExecutionDeps.ts b/worker/src/features/evaluation/evalExecutionDeps.ts
index d3a9d8b7b4..2fdbf8f34d 100644
--- a/worker/src/features/evaluation/evalExecutionDeps.ts
+++ b/worker/src/features/evaluation/evalExecutionDeps.ts
@@ -50,6 +50,7 @@ export interface LLMCallParams {
messages: ReturnType<typeof buildEvalMessages>;
modelConfig: Extract<ModelConfigResult, { valid: true }>["config"];
structuredOutputSchema: StructuredOutputSchema;
+ promptCacheKey?: string;
traceSinkParams: {
targetProjectId: string;
traceId: string;
@@ -235,8 +236,9 @@ export function createProductionEvalExecutionDeps(): EvalExecutionDeps {
provider: params.modelConfig.provider,
model: params.modelConfig.model,
adapter,
- ...params.modelConfig.modelParams,
+ ...(params.modelConfig.modelParams ?? {}),
},
+ promptCacheKey: params.promptCacheKey,
structuredOutputSchema: params.structuredOutputSchema,
maxRetries: 1,
traceSinkParams: {
diff --git a/worker/src/features/evaluation/evalRuntime.ts b/worker/src/features/evaluation/evalRuntime.ts
index 03bb984a9d..91375d57cc 100644
--- a/worker/src/features/evaluation/evalRuntime.ts
+++ b/worker/src/features/evaluation/evalRuntime.ts
@@ -1,3 +1,4 @@
+import { createHash } from "crypto";
import {
ChatMessageRole,
ChatMessageType,
@@ -11,6 +12,31 @@ export interface CompileEvalPromptParams {
variables: ExtractedVariable[];
}
+function sha256Base64Url(value: string) {
+ return createHash("sha256").update(value).digest("base64url");
+}
+
+export function buildEvalPromptCacheKey(params: {
+ projectId: string;
+ templateId: string;
+ templateVersion: number;
+ provider: string;
+ model: string;
+}): string {
+ // Versioned cache bucket for requests that share the same reusable evaluator
+ // prompt prefix on the same model endpoint. Per-run variables and output
+ // definitions are intentionally excluded to avoid fragmenting prompt caches.
+ const payload = [
+ params.projectId,
+ params.templateId,
+ String(params.templateVersion),
+ params.provider,
+ params.model,
+ ].join("\x00");
+
+ return `lf-eval-v1-${sha256Base64Url(payload)}`;
+}
+
export function compileEvalPrompt(params: CompileEvalPromptParams): string {
// Stringify extracted values here (LLM-judge's consumption boundary) so
// the upstream extractor can preserve original shapes for code-eval and
diff --git a/worker/src/features/evaluation/evalService.ts b/worker/src/features/evaluation/evalService.ts
index db989392e5..6dad837730 100644
--- a/worker/src/features/evaluation/evalService.ts
+++ b/worker/src/features/evaluation/evalService.ts
@@ -73,6 +73,7 @@ import {
compileEvalPrompt,
buildEvalMessages,
buildEvalExecutionMetadata,
+ buildEvalPromptCacheKey,
getEnvironmentFromVariables,
} from "./evalRuntime";
import {
@@ -857,6 +858,13 @@ export async function runLLMAsJudgeEvaluation({
// Prepare LLM call
const messages = buildEvalMessages(prompt);
+ const promptCacheKey = buildEvalPromptCacheKey({
+ projectId,
+ templateId: template.id,
+ templateVersion: template.version,
+ provider: modelConfig.config.provider,
+ model: modelConfig.config.model,
+ });
const executionTraceId = createW3CTraceId(jobExecutionId);
@@ -879,7 +887,7 @@ export async function runLLMAsJudgeEvaluation({
llmSpan.setAttribute("eval.model.name", modelConfig.config.model);
llmSpan.setAttribute(
"eval.model.adapter",
- modelConfig.config.adapter,
+ modelConfig.config.apiKey.adapter,
);
try {
@@ -888,6 +896,7 @@ export async function runLLMAsJudgeEvaluation({
modelConfig: modelConfig.config,
structuredOutputSchema:
compiledOutputDefinition.outputResultSchema,
+ promptCacheKey,
traceSinkParams: {
targetProjectId: projectId,
traceId: executionTraceId,
diff --git a/worker/src/features/evaluation/evaluationHelpers.test.ts b/worker/src/features/evaluation/evaluationHelpers.test.ts
index a83a418ec1..1b723f8dba 100644
--- a/worker/src/features/evaluation/evaluationHelpers.test.ts
+++ b/worker/src/features/evaluation/evaluationHelpers.test.ts
@@ -18,6 +18,7 @@ import { createDeterministicEvalScoreId } from "../../../../packages/shared/src/
import {
buildEvalExecutionMetadata,
buildEvalMessages,
+ buildEvalPromptCacheKey,
compileEvalPrompt,
getEnvironmentFromVariables,
} from "./evalRuntime";
@@ -25,6 +26,42 @@ import { buildEvalScoreWritePayloads } from "./evalScoreEvent";
import { buildEvalExecutionSpanAttributes } from "./evalSpanAttributes";
describe("evaluation helpers", () => {
+ describe("buildEvalPromptCacheKey", () => {
+ const baseParams = {
+ projectId: "project-123",
+ templateId: "template-123",
+ templateVersion: 1,
+ provider: "fireworks",
+ model: "accounts/fireworks/models/kimi-k2-instruct",
+ };
+
+ it("should build a deterministic versioned cache key", () => {
+ const firstKey = buildEvalPromptCacheKey(baseParams);
+ const secondKey = buildEvalPromptCacheKey({
+ model: baseParams.model,
+ provider: baseParams.provider,
+ templateVersion: baseParams.templateVersion,
+ templateId: baseParams.templateId,
+ projectId: baseParams.projectId,
+ });
+
+ expect(firstKey).toMatch(/^lf-eval-v1-[A-Za-z0-9_-]+$/);
+ expect(secondKey).toBe(firstKey);
+ });
+
+ it.each([
+ ["project", { projectId: "project-456" }],
+ ["template id", { templateId: "template-456" }],
+ ["template version", { templateVersion: 2 }],
+ ["provider", { provider: "openai" }],
+ ["model", { model: "gpt-4.1" }],
+ ])("should change when %s changes", (_field, override) => {
+ expect(buildEvalPromptCacheKey({ ...baseParams, ...override })).not.toBe(
+ buildEvalPromptCacheKey(baseParams),
+ );
+ });
+ });
+
describe("compileEvalPrompt", () => {
it("should compile template with variables", () => {
const params = {