Prompt Caching
Prompt caching on Anthropic lets you cache individual messages in your request for repeat use. With caching, you can free up your tokens to include more context in your prompt, and also deliver responses significantly faster and cheaper.
Portkey makes Anthropic's prompt caching work on our OpenAI-compliant universal API.
Just pass Anthropic's anthropic-beta
header in your request, and set the cache_control
param in your respective message body:
import Portkey from 'portkey-ai'
const portkey = new Portkey({
apiKey: "PORTKEY_API_KEY", // defaults to process.env["PORTKEY_API_KEY"]
virtualKey: "VIRTUAL_KEY" // Your Anthropic Virtual Key
anthropicBeta: "prompt-caching-2024-07-31"
})
const chatCompletion = await portkey.chat.completions.create({
messages: [
{ "role": 'system', "content": [
{
"type":"text","text":"You are a helpful assistant"
},
{
"type":"text","text":"<TEXT_TO_CACHE>",
"cache_control": {"type": "ephemeral"}
}
]},
{ "role": 'user', "content": 'Summarize the above story for me in 20 words' }
],
model: 'claude-3-5-sonnet-20240620',
max_tokens: 250 // Required field for Anthropic
});
console.log(chatCompletion.choices[0].message.content);
For more, refer to Anthropic's prompt caching documentation here.
Seeing Cache Results in Portkey
Portkey automatically calculate the correct pricing for your prompt caching requests & responses based on Anthropic's calculations here:

In the individual log for any request, you can also see the exact status of your request and verify if it was cached, or delivered from cache with two usage
parameters:
cache_creation_input_tokens
: Number of tokens written to the cache when creating a new entry.cache_read_input_tokens
: Number of tokens retrieved from the cache for this request.

Last updated
Was this helpful?