ai icon indicating copy to clipboard operation
ai copied to clipboard

Anthropic Caching is not working with generateObject

Open technoligest opened this issue 1 year ago • 10 comments

Description

From the AI SDK docs,

The cache creation input tokens are then returned in the providerMetadata object for generateText and generateObject

However, the for generateObject specifically, the only supported mode is tool-calling mode. With this mode, every call will have a different tool based on the schema, which breaks down caching completely.

From the Anthropic Caching docs:

Prompt caching references the entire prompt - tools, system, and messages (in that order) up to and including the block designated with cache_control.

Honestly I would've been happy with the docs saying it's not supported so I can look for alternatives, but this took a huge amount of debugging to figure out as the tool output is not clear without looking at the request object.

Code example

function runObject(schema) {
  const result = await generateText({
    model: anthropic('claude-3-5-sonnet-20240620'),
    messages: [
        {
          role: 'system',
          content: '<HUGE MESSAGE 2K tokent> Cached system message part',
          providerOptions: {
            anthropic: { cacheControl: { type: 'ephemeral' } },
          },
        },
        {
          role: 'system',
          content: 'Uncached system message part',
        },
        {
          role: 'user',
          content: 'User prompt',
        },
      ],
    });
}

// first call
runObject(z.object({name: z.string()}))

// should be a cache hit, but is not
runObjet(z.object({company: z.string()}))

AI provider

@ai-sdk/anthropic

Additional context

No response

technoligest avatar Mar 16 '25 01:03 technoligest

i came here looking for why my system prompts were not caching (i am using streamtext tho).

noted that you are sending cacheControl instead of the snake case cache_control. is it meant to match the anthropic casing?

seannetlife avatar Mar 25 '25 04:03 seannetlife

i came here looking for why my system prompts were not caching (i am using streamtext tho).

noted that you are sending cacheControl instead of the snake case cache_control. is it meant to match the anthropic casing?

@seannetlife if you look at the docs, you can see it is not snake_case if you're using the ai sdk

technoligest avatar Mar 25 '25 17:03 technoligest

i came here looking for why my system prompts were not caching (i am using streamtext tho).

noted that you are sending cacheControl instead of the snake case cache_control. is it meant to match the anthropic casing?

Came here for same reason. I'm sending proper headers with long system prompt and getting Provider Metadata { anthropic: { cacheCreationInputTokens: 0, cacheReadInputTokens: 0 } }

Did you figure it out?

neoromantic avatar Mar 27 '25 20:03 neoromantic

I'm running into some similar issues - with streamText as well as generateObject - and here are my observations:

  • It works sometimes - I've gotten generateObject calls to successfully cache.
  • Looking at the actual result.request.body content that's sent to anthropic, the cache_control parameter is not being passed to anthropic in some cases even when it's set.
  • In particular, I've noticed it work at the beginning of a conversation thread, and then not work on the same message after more messages are added on.

My guess is that there are some cases that trigger some extra processing that loses the cache control parameter.

The most minimal example I've been able to come up with involves sending a message with role 'data' - these messages seem to be ignored and not passed on, but the presence of one in the request still breaks cache control on OTHER messages.

const messages = [
      {
        role: 'user',
        content: 'Please process this message',
        providerOptions: {
          anthropic: { cacheControl: { type: 'ephemeral' } },
        },
      },
    ];

const generateResult = await generateText({
      model: anthropic('claude-3-7-sonnet-20250219');,
      messages: messages,
 });

successfully sends the following to Anthropic:

{
  role: 'user',
  content: [
    {
      type: 'text',
      text: 'Please process this message',
      cache_control: [Object]
    }
  ]
}

However this:

const messages = [
      {
        role: 'user',
        content: 'Please process this message',
        providerOptions: {
          anthropic: { cacheControl: { type: 'ephemeral' } },
        },
      },
      {
        role: 'data',
        content: 'some data',
      },
    ];

 const generateResult = await generateText({
      model: anthropic('claude-3-7-sonnet-20250219');,
      messages: messages,
});

Still sends only the first message, but without the cache_control parameter:

{
  role: 'user',
  content: [ { type: 'text', text: 'Please process this message' } ]
}

This also includes system prompts - as far as I can tell, whatever is breaking it seems to remove all cache_control parameters from all messages. It's not only the data messages that are an issue - I've seen it happen with tool results too, or possibly when passing in two sequential messages with the same role (which seems to trigger logic to combine them into one message with an array of content).

carlymr avatar Mar 27 '25 23:03 carlymr

Update, I filed an issue for what I think is the root cause of my issue (and a broader issue) here: https://github.com/vercel/ai/issues/5473

As a workaround, I was able to successfully get caching working by manually calling convertToCoreMessages on all messages coming in from the UI before passing them into streamText (/etc.) e.g.:

generateText({
  model: anthropic('claude-3-7-sonnet-20250219');,
  messages:  [
  {
    role: 'system',
    content: orchestratorPrompt,
    providerOptions: {
      anthropic: { cacheControl: { type: 'ephemeral' } },
    },
  } as CoreMessage,
  ...convertToCoreMessages(messages), // convert messages coming from the UI
];

(For my case above, convertToCoreMessage just drops data messages).

I am not sure if this is the cause of the OP issue here though, since I don't see anything in that example that would trigger this case.

carlymr avatar Apr 01 '25 18:04 carlymr

Thanks @carlymr! This workaround helped me cache a large system prompt. 🙏

disposableraft avatar Apr 02 '25 21:04 disposableraft

Worked for me as well! Thank you, so simple!

neoromantic avatar Apr 03 '25 16:04 neoromantic

I personally find Anthropic's caching docs inscrutable.

For me the tools, system prompt and all but one of the user messages are the same across repeated invocations – so it is important to cache everything but the last message.

If this fits your case, the following works for AI SDK @ 6:

const { output } = generateText({
  model: myAnthropicModel,
  output: Object.object({ schema }),
  providerOptions: {
    anthropic: { structuredOutputMode: "jsonTool" },
  },
  messages: [
    {
      role: "system",
      content: systemPrompt,
    },
    {
      role: "user",
      content: userPrompt,
      providerOptions: {
        anthropic: { cacheControl: { type: "ephemeral" } },
      },
    },
    {
      role: "user",
      content: `And now a short word from our user: ${userMessage}`,
    },
  ],
});

A few notes:

  1. Using jsonTool means that the AI SDK will inject a tool into its call to Anthropic
  2. If your schema varies across calls, express it in a more "relaxed" way and perform strict validation on your client. Retry strict validation failures by retrying your call to the LLM with your original prompts and the errors encountered.
  3. You don't need to put Anthropic cache control directives in your tools and/or system prompt to cache them ... provided they don't change between calls. Multiple breakpoints are an optimization for partial cache invalidation, not a requirement for full caching.
  4. If your tools change across calls AND you're using jsonTool output mode, you're a bit hosed unless you drop down to overriding the fetch implementation of your Anthropic provider to inject the cache control directive into your tools 🙈 (no easy way to add the cache directive to the AI SDK injected tools)

johnboxall avatar Jan 09 '26 23:01 johnboxall

Marking this as closed for now - if you face any regression or have a similar problem after migrating to the latest AI SDK version, please feel free to open a new issue (with possible reproduction)

aayush-kapoor avatar Jan 22 '26 21:01 aayush-kapoor

Identify issue type

Identified as Documentation
Confidence: Medium

Rationale

The core request is to clarify an undocumented limitation of Anthropic prompt caching with generateObject and varying schemas. The described cache miss follows from the generated tool changing, rather than clearly demonstrating broken caching behavior.

Evidence

  • The reported cache miss occurs when each generateObject call uses a different schema, causing the SDK-injected Anthropic tool—and therefore the cached prompt prefix—to change.
  • The quoted SDK documentation mentions returning cache token metadata for generateObject but does not explain this tool-calling limitation.
  • The reporter explicitly says documentation stating that this scenario is unsupported would have avoided the debugging.
  • A later comment confirms caching can work when tools and prompts remain stable, while changing injected tools prevents this caching pattern; separate cache_control-loss behavior was filed as issue #5473.

lgrammel avatar Jul 22 '26 15:07 lgrammel