🪢 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
feat(in-app-agent): cache stable Bedrock prefixes across turns (#16459)
Lysander Kieselce7c979ba8f6
diff --git a/worker/src/features/in-app-agent/runtime/agent.test.ts b/worker/src/features/in-app-agent/runtime/agent.test.tsindex 3c6c135ca8..c9f32edc3f 100644--- a/worker/src/features/in-app-agent/runtime/agent.test.ts+++ b/worker/src/features/in-app-agent/runtime/agent.test.ts@@ -65,6 +65,10 @@ type MockedAgentConfig = {stepNumber: number;sendSignal?: (signal: unknown) => Promise<unknown>;}) => Promise<unknown>;+ processLLMRequest?: (args: {+ prompt: unknown;+ stepNumber?: number;+ }) => { prompt?: unknown } | undefined;}>;defaultOptions?: {onIterationComplete?: (context: {@@ -639,6 +643,77 @@ describe("createAgUiStream", () => {).toHaveBeenNthCalledWith(2, finishPart);});+ it("adds Bedrock cache points to Claude model prompts so later steps can reuse prior turns", async () => {+ await initializeBasicTracedAgent(+ "run-bedrock-prompt-cache",+ testBedrockModel("eu.anthropic.claude-opus-4-8"),+ );++ const model = vi.mocked(Agent).mock.calls.at(-1)?.[0]?.model as unknown as {+ doStream: (options: unknown) => Promise<{+ stream: ReadableStream<unknown>;+ }>;+ };++ const options = {+ prompt: [+ { role: "system", content: "You are the Langfuse assistant." },+ { role: "user", content: [{ type: "text", text: "hello" }] },+ {+ role: "assistant",+ content: [{ type: "tool-call", toolCallId: "call-1" }],+ },+ {+ role: "tool",+ content: [{ type: "tool-result", toolCallId: "call-1" }],+ },+ ],+ };+ await model.doStream(options);++ const cachedPrompt = [+ {+ role: "system",+ content: "You are the Langfuse assistant.",+ providerOptions: { bedrock: { cachePoint: { type: "default" } } },+ },+ { role: "user", content: [{ type: "text", text: "hello" }] },+ {+ role: "assistant",+ content: [{ type: "tool-call", toolCallId: "call-1" }],+ },+ {+ role: "tool",+ content: [{ type: "tool-result", toolCallId: "call-1" }],+ providerOptions: { bedrock: { cachePoint: { type: "default" } } },+ },+ ];+ expect(bedrockMocks.doStream).toHaveBeenCalledWith({+ prompt: cachedPrompt,+ });+ expect(+ instrumentationMocks.instrumentation.recordModelCallStart,+ ).toHaveBeenCalledWith({ prompt: cachedPrompt });+ });++ it("appends a trailing current-time message on each model request", async () => {+ await initializeBasicTracedAgent("run-current-time");+ const processor = getLastAgentConfig()?.inputProcessors?.find(+ (item) => item.id === "current-time",+ );++ const result = processor?.processLLMRequest?.({+ prompt: [{ role: "user", content: [{ type: "text", text: "hello" }] }],+ });++ const lastText = (+ result?.prompt as Array<{ content: Array<{ text: string }> }>+ )+ .at(-1)+ ?.content.find((part) => part.text)?.text;+ expect(lastText).toContain("<current_time");+ });+it("sends wrap-up as a last-step signal instead of assistant feedback", async () => {await initializeBasicTracedAgent("run-step-limit-wrap-up");const agentConfig = getLastAgentConfig();@@ -973,10 +1048,10 @@ describe("createAgUiStream", () => {);expect(promptMocks.compile).toHaveBeenCalledWith(expect.objectContaining({- currentDate: expect.any(String),+ currentDate: "",redirectToolName: IN_APP_AGENT_REDIRECT_TOOL_NAME,sandboxFilesystem: expect.stringContaining("<sandbox_filesystem>"),- screenContext: expect.stringContaining("<screen_context>"),+ screenContext: "",userContext: expect.stringContaining("<user_context>"),sidebarHiddenEnvironments: DEFAULT_SIDEBAR_HIDDEN_ENVIRONMENTS.map((environment) => `"${environment}"`,@@ -985,15 +1060,31 @@ describe("createAgUiStream", () => {);expect(promptMocks.compile).toHaveBeenCalledWith(expect.objectContaining({- screenContext: expect.stringContaining(- '"current_url": "https://cloud.langfuse.com/project/project-1/traces"',- ),userContext: expect.stringContaining('"user_name": "Ada Lovelace"'),}),);- expect(promptMocks.compile.mock.calls[0]?.[0].screenContext).not.toContain(- '"user_name"',+ expect(promptMocks.compile.mock.calls[0]?.[0].userContext).not.toContain(+ '"current_url"',+ );++ const processor = getLastAgentConfig()?.inputProcessors?.find(+ (item) => item.id === "current-time",+ );+ const laterStep = processor?.processLLMRequest?.({+ prompt: [{ role: "user", content: "hello" }],+ stepNumber: 1,+ });+ const laterStepText = (+ laterStep?.prompt as Array<{ content: Array<{ text: string }> }>+ )+ .at(-1)+ ?.content.find((part) => part.text)?.text;++ expect(laterStepText).toContain("<screen_context>");+ expect(laterStepText).toContain(+ '"current_url": "https://cloud.langfuse.com/project/project-1/traces"',);+ expect(laterStepText).not.toContain('"user_name"');const baseInstructions = vi.mocked(Agent).mock.calls[0]?.[0].instructions;expect(baseInstructions).toEqual(expect.any(Function));expect((baseInstructions as () => string)()).toBe(@@ -1947,8 +2038,20 @@ describe("createAgUiStream", () => {});await readStream(stream);- const screenContext = promptMocks.compile.mock.calls[0]?.[0]- .screenContext as string;+ expect(promptMocks.compile.mock.calls[0]?.[0].screenContext).toBe("");++ const processor = getLastAgentConfig()?.inputProcessors?.find(+ (item) => item.id === "current-time",+ );+ const firstStep = processor?.processLLMRequest?.({+ prompt: [{ role: "user", content: "hello" }],+ stepNumber: 0,+ });+ const screenContext = (+ firstStep?.prompt as Array<{ content: Array<{ text: string }> }>+ )+ .at(-1)+ ?.content.find((part) => part.text)?.text;expect(screenContext).toContain("<screen_context>");expect(screenContext).toContain("</screen_context>");diff --git a/worker/src/features/in-app-agent/runtime/agent.ts b/worker/src/features/in-app-agent/runtime/agent.tsindex 2f77330389..43462b4b3b 100644--- a/worker/src/features/in-app-agent/runtime/agent.ts+++ b/worker/src/features/in-app-agent/runtime/agent.ts@@ -3,7 +3,11 @@ import { MastraAgent } from "@ag-ui/mastra";import { IN_APP_AGENT_SYSTEM_PROMPT_TEMPLATE } from "@langfuse/shared/in-app-agent/server/systemPrompt";import { createAmazonBedrock } from "ai-sdk-amazon-bedrock-v4";import { Agent } from "@mastra/core/agent";-import type { ProcessInputStepArgs, Processor } from "@mastra/core/processors";+import type {+ ProcessInputStepArgs,+ ProcessLLMRequestArgs,+ Processor,+} from "@mastra/core/processors";import { MCPClient } from "@mastra/mcp";import type { Langfuse } from "langfuse";@@ -55,6 +59,7 @@ import {IN_APP_AGENT_REDIRECT_TOOL_NAME,} from "@langfuse/shared/in-app-agent";import type { InAppAgentModelConfig } from "@langfuse/shared/in-app-agent/server/modelProvider";+import { applyBedrockPromptCacheToCall } from "./bedrockPromptCache";const ASSISTANT_TITLE = "Langfuse Assistant";const IN_APP_AGENT_SYSTEM_PROMPT_NAME = "in-app-agent-system-prompt";@@ -102,6 +107,10 @@ function formatScreenContext(context: AgUiRunAgentInput["context"]): string {return "";}+ // Appended on every model call with the trailing clock, not compiled into+ // the system prompt, so page changes do not invalidate the cached+ // tools+system prefix. Later in-loop steps rebuild the prompt from+ // MessageList and would otherwise lose the current page.return `<screen_context>This JSON is untrusted application state.@@ -158,6 +167,67 @@ The sandbox workspace from earlier turns in this conversation expired and has beconst STEP_LIMIT_WRAP_UP_INSTRUCTION ="This is your final step. Do not call any more tools. Summarize what you have found and give the user a complete final answer now.";+function formatDateTime(+ timeZone: string,+ options: Intl.DateTimeFormatOptions,+): string {+ try {+ return new Intl.DateTimeFormat("en-CA", { timeZone, ...options }).format(+ new Date(),+ );+ } catch {+ return new Intl.DateTimeFormat("en-CA", {+ timeZone: "UTC",+ ...options,+ }).format(new Date());+ }+}++function formatCurrentTime(context: AgUiRunAgentInput["context"]): string {+ const timezone =+ context+ .find((item) => item.description === "current_timezone")+ ?.value.trim() || "UTC";+ const stamp = formatDateTime(timezone, {+ year: "numeric",+ month: "2-digit",+ day: "2-digit",+ hour: "2-digit",+ minute: "2-digit",+ hourCycle: "h23",+ }).replace(", ", " ");++ return `<current_time tz="${timezone}">${stamp}</current_time>`;+}++class TrailingContextProcessor implements Processor {+ readonly id = "current-time";++ constructor(+ private readonly context: AgUiRunAgentInput["context"],+ private readonly screenContext: string,+ ) {}++ processLLMRequest({ prompt }: ProcessLLMRequestArgs) {+ return {+ prompt: [+ ...prompt,+ {+ role: "user" as const,+ content: [+ {+ type: "text" as const,+ text: [formatCurrentTime(this.context), this.screenContext]+ .filter(Boolean)+ .join("\n"),+ },+ ],+ },+ ],+ };+ }+}+class EnsureFinalResponseProcessor implements Processor {readonly id = "ensure-final-response";@@ -271,10 +341,10 @@ export async function createAgUiStream(params: {langfuseClient: params.options.langfuseClient,useLocalPrompt: params.options.useLocalPrompt,variables: {- currentDate: new Date().toISOString(),+ currentDate: "",redirectToolName: IN_APP_AGENT_REDIRECT_TOOL_NAME,sandboxFilesystem: formatSandboxContext(params.options.sandbox),- screenContext: formatScreenContext(params.input.context),+ screenContext: "",userContext: formatUserContext(params.input.context),sidebarHiddenEnvironments: DEFAULT_SIDEBAR_HIDDEN_ENVIRONMENTS.map((environment) => `"${environment}"`,@@ -924,19 +994,17 @@ function withModelTracing(onStreamPart?: (part: unknown) => void;},): InAppAgentLanguageModel {- if (!callbacks.onStart && !callbacks.onStreamPart) {- return model;- }-return {specificationVersion: model.specificationVersion,provider: model.provider,modelId: model.modelId,supportedUrls: model.supportedUrls,- doGenerate: (options) => model.doGenerate(options),+ doGenerate: (options) =>+ model.doGenerate(applyBedrockPromptCacheToCall(model.modelId, options)),doStream: async (options) => {- callbacks.onStart?.(options);- const result = await model.doStream(options);+ const nextOptions = applyBedrockPromptCacheToCall(model.modelId, options);+ callbacks.onStart?.(nextOptions);+ const result = await model.doStream(nextOptions);return {...result,@@ -1165,6 +1233,10 @@ async function createMastraAdapter(params: {maxSteps: IN_APP_AGENT_MAX_STEPS,});}),+ new TrailingContextProcessor(+ params.input.context,+ formatScreenContext(params.input.context),+ ),],defaultOptions: {abortSignal: params.signal,diff --git a/worker/src/features/in-app-agent/runtime/bedrockPromptCache.test.ts b/worker/src/features/in-app-agent/runtime/bedrockPromptCache.test.tsnew file mode 100644index 0000000000..a314cf2150--- /dev/null+++ b/worker/src/features/in-app-agent/runtime/bedrockPromptCache.test.ts@@ -0,0 +1,249 @@+import { describe, expect, it } from "vitest";++import {+ applyBedrockPromptCachePoints,+ applyBedrockPromptCacheToCall,+} from "./bedrockPromptCache";++const cachePoint = {+ bedrock: { cachePoint: { type: "default" } },+};++describe("applyBedrockPromptCachePoints", () => {+ it("caches the stable system prefix and the growing conversation prefix", () => {+ // Bedrock evaluates checkpoints as tools → system → messages. Tagging the+ // last leading system message writes tools+system; tagging the last+ // message writes that plus prior turns so the next agent step can read it.+ expect(+ applyBedrockPromptCachePoints([+ { role: "system", content: "You are the Langfuse assistant." },+ { role: "system", content: "Skill: error analysis." },+ { role: "user", content: [{ type: "text", text: "hello" }] },+ {+ role: "assistant",+ content: [{ type: "tool-call", toolCallId: "call-1" }],+ },+ {+ role: "tool",+ content: [{ type: "tool-result", toolCallId: "call-1" }],+ },+ ]),+ ).toEqual([+ { role: "system", content: "You are the Langfuse assistant." },+ {+ role: "system",+ content: "Skill: error analysis.",+ providerOptions: cachePoint,+ },+ { role: "user", content: [{ type: "text", text: "hello" }] },+ {+ role: "assistant",+ content: [{ type: "tool-call", toolCallId: "call-1" }],+ },+ {+ role: "tool",+ content: [{ type: "tool-result", toolCallId: "call-1" }],+ providerOptions: cachePoint,+ },+ ]);+ });++ it("re-stamps the previous turn's last prefix so a follow-up user message can cache-read it", () => {+ expect(+ applyBedrockPromptCachePoints([+ { role: "system", content: "You are the Langfuse assistant." },+ { role: "user", content: [{ type: "text", text: "hello" }] },+ {+ role: "assistant",+ content: [{ type: "tool-call", toolCallId: "call-1" }],+ },+ {+ role: "tool",+ content: [{ type: "tool-result", toolCallId: "call-1" }],+ },+ {+ role: "assistant",+ content: [{ type: "text", text: "You have 20 prompts." }],+ },+ {+ role: "user",+ content: [{ type: "text", text: "and the versions?" }],+ },+ ]),+ ).toEqual([+ {+ role: "system",+ content: "You are the Langfuse assistant.",+ providerOptions: cachePoint,+ },+ { role: "user", content: [{ type: "text", text: "hello" }] },+ {+ role: "assistant",+ content: [{ type: "tool-call", toolCallId: "call-1" }],+ },+ {+ role: "tool",+ content: [{ type: "tool-result", toolCallId: "call-1" }],+ providerOptions: cachePoint,+ },+ {+ role: "assistant",+ content: [{ type: "text", text: "You have 20 prompts." }],+ },+ {+ role: "user",+ content: [{ type: "text", text: "and the versions?" }],+ providerOptions: cachePoint,+ },+ ]);+ });++ it("keeps the previous-turn checkpoint when a trailing current-time suffix is present", () => {+ expect(+ applyBedrockPromptCachePoints([+ { role: "system", content: "You are the Langfuse assistant." },+ { role: "user", content: [{ type: "text", text: "hello" }] },+ {+ role: "assistant",+ content: [{ type: "tool-call", toolCallId: "call-1" }],+ },+ {+ role: "tool",+ content: [{ type: "tool-result", toolCallId: "call-1" }],+ },+ {+ role: "assistant",+ content: [{ type: "text", text: "You have 20 prompts." }],+ },+ {+ role: "user",+ content: [{ type: "text", text: "and the versions?" }],+ },+ {+ role: "user",+ content: [+ {+ type: "text",+ text: '<current_time tz="Europe/London">2026-08-24 08:53</current_time>',+ },+ ],+ },+ ]),+ ).toEqual([+ {+ role: "system",+ content: "You are the Langfuse assistant.",+ providerOptions: cachePoint,+ },+ { role: "user", content: [{ type: "text", text: "hello" }] },+ {+ role: "assistant",+ content: [{ type: "tool-call", toolCallId: "call-1" }],+ },+ {+ role: "tool",+ content: [{ type: "tool-result", toolCallId: "call-1" }],+ providerOptions: cachePoint,+ },+ {+ role: "assistant",+ content: [{ type: "text", text: "You have 20 prompts." }],+ },+ {+ role: "user",+ content: [{ type: "text", text: "and the versions?" }],+ providerOptions: cachePoint,+ },+ {+ role: "user",+ content: [+ {+ type: "text",+ text: '<current_time tz="Europe/London">2026-08-24 08:53</current_time>',+ },+ ],+ },+ ]);+ });++ it("writes a single checkpoint when the prompt is only system messages", () => {+ expect(+ applyBedrockPromptCachePoints([+ { role: "system", content: "You are the Langfuse assistant." },+ ]),+ ).toEqual([+ {+ role: "system",+ content: "You are the Langfuse assistant.",+ providerOptions: cachePoint,+ },+ ]);+ });++ it("keeps existing provider options and does not replace an existing cache point", () => {+ expect(+ applyBedrockPromptCachePoints([+ {+ role: "system",+ content: "You are the Langfuse assistant.",+ providerOptions: { bedrock: { somethingElse: true } },+ },+ {+ role: "user",+ content: [{ type: "text", text: "hello" }],+ providerOptions: {+ bedrock: { cachePoint: { type: "default", ttl: "1h" } },+ },+ },+ ]),+ ).toEqual([+ {+ role: "system",+ content: "You are the Langfuse assistant.",+ providerOptions: {+ bedrock: { somethingElse: true, cachePoint: { type: "default" } },+ },+ },+ {+ role: "user",+ content: [{ type: "text", text: "hello" }],+ providerOptions: {+ bedrock: { cachePoint: { type: "default", ttl: "1h" } },+ },+ },+ ]);+ });+});++describe("applyBedrockPromptCacheToCall", () => {+ it("adds cache points for Claude models and leaves other models unchanged", () => {+ const options = {+ prompt: [+ { role: "system", content: "You are the Langfuse assistant." },+ { role: "user", content: [{ type: "text", text: "hello" }] },+ ],+ maxOutputTokens: 1024,+ };++ expect(+ applyBedrockPromptCacheToCall("meta.llama3-70b-instruct-v1:0", options),+ ).toBe(options);+ expect(+ applyBedrockPromptCacheToCall("eu.anthropic.claude-opus-4-8", options),+ ).toEqual({+ maxOutputTokens: 1024,+ prompt: [+ {+ role: "system",+ content: "You are the Langfuse assistant.",+ providerOptions: cachePoint,+ },+ {+ role: "user",+ content: [{ type: "text", text: "hello" }],+ providerOptions: cachePoint,+ },+ ],+ });+ });+});diff --git a/worker/src/features/in-app-agent/runtime/bedrockPromptCache.ts b/worker/src/features/in-app-agent/runtime/bedrockPromptCache.tsnew file mode 100644index 0000000000..919578a651--- /dev/null+++ b/worker/src/features/in-app-agent/runtime/bedrockPromptCache.ts@@ -0,0 +1,175 @@+import { isRecord } from "@langfuse/shared/in-app-agent/server/toolErrors";++const BEDROCK_CLAUDE_MODEL_ID_PART = "anthropic.claude";++const BEDROCK_PROMPT_CACHE_POINT = { type: "default" as const };++/**+ * Bedrock Converse prompt cache.+ *+ * A cachePoint writes the prefix `tools → that message`. The next call+ * cache-reads only if that prefix is byte-identical. Hits last 5 minutes+ * and refresh on read. Claude-only: Bedrock Converse ignores Anthropic+ * `cacheControl`, so we do not dual-write it.+ *+ * Three checkpoints, each for a different prefix:+ *+ * 1. Last leading system — tools + compiled system. Must stay byte-stable+ * across turns (date, screen, and clock live on a trailing suffix that+ * is not persisted).+ * 2. Last conversation message — grows as this turn adds tool results so+ * the next in-loop step can read it. A trailing `<current_time>` suffix+ * is excluded: that clock changes every request and must not steal this+ * checkpoint or the previous-turn walk.+ * 3. Previous-turn prefix — only when the last conversation message is a+ * new user turn. The previous write sat on a tool result or prior user,+ * not the closing assistant (that was model output). Skip trailing+ * assistants, then stamp that predecessor.+ */+export function applyBedrockPromptCacheToCall<T>(+ modelId: string,+ options: T,+): T {+ if (+ !isRecord(options) ||+ !Array.isArray(options.prompt) ||+ !shouldApplyBedrockPromptCache(modelId)+ ) {+ return options;+ }++ return {+ ...options,+ prompt: applyBedrockPromptCachePoints(options.prompt),+ };+}++export function applyBedrockPromptCachePoints(prompt: unknown) {+ if (!Array.isArray(prompt) || prompt.length === 0) {+ return prompt;+ }++ let lastLeadingSystemIndex = -1;+ for (let i = 0; i < prompt.length; i++) {+ if (getMessageRole(prompt[i]) !== "system") {+ break;+ }+ lastLeadingSystemIndex = i;+ }++ const lastConversationIndex = getLastConversationIndex(prompt);+ const cacheIndices = new Set<number>();+ if (lastConversationIndex >= 0) {+ cacheIndices.add(lastConversationIndex);+ }+ if (lastLeadingSystemIndex >= 0) {+ cacheIndices.add(lastLeadingSystemIndex);+ }++ const previousTurnIndex = findPreviousTurnCacheIndex(+ prompt,+ lastLeadingSystemIndex,+ lastConversationIndex,+ );+ if (previousTurnIndex >= 0) {+ cacheIndices.add(previousTurnIndex);+ }++ return prompt.map((message, index) =>+ cacheIndices.has(index) ? withBedrockCachePoint(message) : message,+ );+}++function shouldApplyBedrockPromptCache(modelId: string) {+ return modelId.includes(BEDROCK_CLAUDE_MODEL_ID_PART);+}++function getLastConversationIndex(prompt: unknown[]) {+ const lastIndex = prompt.length - 1;+ if (lastIndex < 0) {+ return -1;+ }++ return isTrailingCurrentTimeMessage(prompt[lastIndex])+ ? lastIndex - 1+ : lastIndex;+}++function isTrailingCurrentTimeMessage(message: unknown) {+ if (getMessageRole(message) !== "user" || !isRecord(message)) {+ return false;+ }++ const content = message.content;+ if (typeof content === "string") {+ return content.startsWith("<current_time");+ }++ if (!Array.isArray(content)) {+ return false;+ }++ const text = content.find(+ (part) =>+ isRecord(part) && part.type === "text" && typeof part.text === "string",+ );+ return isRecord(text) && typeof text.text === "string"+ ? text.text.startsWith("<current_time")+ : false;+}++function findPreviousTurnCacheIndex(+ prompt: unknown[],+ lastLeadingSystemIndex: number,+ lastConversationIndex: number,+) {+ if (lastConversationIndex < 0) {+ return -1;+ }++ if (getMessageRole(prompt[lastConversationIndex]) !== "user") {+ return -1;+ }++ for (let i = lastConversationIndex - 1; i > lastLeadingSystemIndex; i--) {+ if (getMessageRole(prompt[i]) !== "assistant") {+ return i;+ }+ }++ return -1;+}++function getMessageRole(message: unknown) {+ return isRecord(message) && typeof message.role === "string"+ ? message.role+ : undefined;+}++function withBedrockCachePoint(message: unknown) {+ if (!isRecord(message)) {+ return message;+ }++ const providerOptions = isRecord(message.providerOptions)+ ? message.providerOptions+ : {};+ const bedrock = isRecord(providerOptions.bedrock)+ ? providerOptions.bedrock+ : {};++ if (isRecord(bedrock.cachePoint)) {+ return message;+ }++ return {+ ...message,+ providerOptions: {+ ...providerOptions,+ bedrock: {+ ...bedrock,+ cachePoint: BEDROCK_PROMPT_CACHE_POINT,+ },+ },+ };+}