Anthropic | Prompt Caching

Prompt caching allows you to cache frequently used context between API calls, reducing costs by up to 90% on cache reads and improving latency. Cached content is marked with a cache_control parameter and is reused across requests within the cache TTL window.

System Prompt Caching

Cache a long system prompt to avoid re-processing it on every request. Set SystemCacheControl to True to automatically wrap the system prompt with cache_control.


Anthropic := TsgcHTTP_API_Anthropic.Create(nil);
Anthropic.AnthropicOptions.ApiKey := 'API_KEY';

oRequest := TsgcAnthropicClass_Request_Messages.Create;
Try
  oRequest.Model := 'claude-sonnet-4-20250514';
  oRequest.MaxTokens := 4096;
  oRequest.System := 'You are an expert legal assistant... (long system prompt)';
  oRequest.SystemCacheControl := True;  // Enable caching for system prompt

  oMessage := TsgcAnthropicClass_Request_Message.Create;
  oMessage.Role := 'user';
  oMessage.Content := 'Analyze this contract clause.';
  oMessages := oRequest.Messages;
  SetLength(oMessages, 1);
  oMessages[0] := oMessage;
  oRequest.Messages := oMessages;

  oResponse := Anthropic.CreateMessage(oRequest);
  Try
    // Check cache usage in response
    WriteLn('Cache created: ' +
      IntToStr(oResponse.Usage.CacheCreationInputTokens));
    WriteLn('Cache read: ' +
      IntToStr(oResponse.Usage.CacheReadInputTokens));
    WriteLn(oResponse.Content[0].Text);
  Finally
    oResponse.Free;
  End;
Finally
  oMessage.Free;
  oRequest.Free;
End;

Content Block Caching

Cache specific content blocks (e.g. large documents or context) by setting CacheControl to 'ephemeral' on individual content blocks.


oBlock := TsgcAnthropicClass_Request_Content_Block.Create;
oBlock.ContentType := 'text';
oBlock.Text := '(large reference text to cache)';
oBlock.CacheControl := 'ephemeral';  // Mark for caching

Tool Definition Caching

Cache tool definitions to avoid re-processing them on every request. This is useful when you have many tool definitions that remain constant across requests.


oTool := TsgcAnthropicClass_Request_Tool.Create;
oTool.Name := 'search_database';
oTool.Description := 'Search the database for records.';
oTool.InputSchema := '{"type":"object","properties":{"query":{"type":"string"}}}';
oTool.CacheControl := 'ephemeral';  // Cache this tool definition

Properties

Pricing