ai-sdk-provider: Prompt caching for Anthropic is not working even with the new options

We have tried adding the following in three different versions:

providerOptions: {
                    openrouter: {
                        // cache_control also works
                        // cache_control: { type: 'ephemeral' }
                        cacheControl: { type: 'ephemeral' },
                    },
                },
                experimental_providerMetadata: {
                    openrouter: {
                        // cache_control also works
                        // cache_control: { type: 'ephemeral' }
                        cacheControl: { type: 'ephemeral' },
                    },
                },
                // @ts-ignore
                providerMetadata: {
                    openrouter: {
                        // cache_control also works
                        // cache_control: { type: 'ephemeral' }
                        cacheControl: { type: 'ephemeral' },
                    },
                },

and added directly at the message level as well as individual parts. The caching with open router is not working at all.

We added a hack to override the fetch implementation and overriding the body but even then only the system prompt caching works.

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 2
  • Comments: 23 (5 by maintainers)

Most upvoted comments

@mjp0 We did actually manage to get it working by creating a custom fetch instance middleware and passing it to the init method of Open Router. We are now now managing all the caching options ourselves as the options being passed to the SDK do not work at all. Its working with all the pieces glued together right now but obviously the moment we can move out of OpenRouter, we will. Pathetic support!

I think I have an idea of what’s going on. @gsabran @rajatady @shtse8 what version is your ai package in package.json?

It appears if I swap to an older version, providerOptions will not be passed down. However when upgraded to the latest version, it’s properly passed down.

Here’s an e2e test to demonstrate the API call : https://github.com/OpenRouterTeam/ai-sdk-provider/pull/67/files

Also added a peerDependency to the package.json to enforce the version required

@mjp0 We did actually manage to get it working by creating a custom fetch instance middleware and passing it to the init method of Open Router. We are now now managing all the caching options ourselves as the options being passed to the SDK do not work at all. Its working with all the pieces glued together right now but obviously the moment we can move out of OpenRouter, we will. Pathetic support!

Great to hear @rajatady! Are you open to sharing a code snippet?

fetch: (input, init) => {
      if (!init?.body) return fetch(input, init);
      
        const body = JSON.parse(init.body as string);
        
        if (body?.messages) {
          for (const message of body.messages) {
            if (typeof message.content === "string") {
              message.content = [{
                type: "text",
                text: message.content,
                cache_control: { type: "ephemeral" }
              }];
            } else if (Array.isArray(message.content)) {
              for (const item of message.content) {
                if (item && typeof item === "object") {
                  item.cache_control = { type: "ephemeral" };
                }
              }
            }
          }
          
          init.body = JSON.stringify(body);
        }
      
      return fetch(input, init);
    }

Will try with a large system prompt on my end to see if we can reproduce.

It seems that the issue happens for he following:

[ Large system (w. cache), user]

[ Large user (w. cache), ]

Are there any other cases?

I can confirm I’m getting the same issue. My system prompt is ~4500 tokens.

On Openrouter’s Activity page, this is always : "usage_cache": null,.

  streamText({
    model: openrouter("anthropic/claude-3.7-sonnet"),
    messages: [
      {
        role: "system",
        content: systemPrompt,
        providerMetadata: {
          openrouter: {
            cacheControl: { type: "ephemeral" },
          },
        },
        experimental_providerMetadata: {
          openrouter: {
            cacheControl: { type: "ephemeral" },
          },
        },
        providerOptions: {
          openrouter: {
            cacheControl: { type: "ephemeral" },
          },
        },
      },
      ...messages,
    ],
  });

In case it can help, I’m already passing extraBody to the openrouter() instance.

export function openrouter(
  model: OpenRouterModel,
  options?: OpenRouterOptions,
): LanguageModelV1 {
  const defaultOptions: OpenRouterOptions = {
    isOnline: false,
    sort: "price",
    maxResults: 3,
  };

  const provider = createOpenRouter({
    apiKey: env.OPENROUTER_API_KEY,
    extraBody: {
      provider: {
        sort: options?.sort || defaultOptions?.sort,
      },
      ...((options?.isOnline || defaultOptions?.isOnline) && {
        plugins: [
          {
            id: "web",
            max_results: options?.maxResults || defaultOptions?.maxResults,
          },
        ],
      }),
    },
  });

  return provider(model);
}

Versions :

    "@openrouter/ai-sdk-provider": "^0.4.5",
    "@ai-sdk/react": "^1.2.9",
    "ai": "^4.3.6",