Anthropic | Prompt Caching

Prompt önbelleğe alma, API çağrıları arasında sık kullanılan bağlamı önbelleğe almanıza olanak tanır, önbellek okumalarında maliyetleri %90'a kadar azaltır ve gecikmeyi iyileştirir. Önbelleğe alınan içerik bir cache_control parametresiyle işaretlenir ve önbellek TTL penceresi içinde istekler arasında yeniden kullanılır.

System Prompt Caching

Uzun bir sistem istemini her istekte yeniden işlemekten kaçınmak için önbelleğe alın. Sistem istemini otomatik olarak cache_control ile sarmalamak için SystemCacheControl'ü True olarak ayarlayın.


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

CacheControl'ü tek tek içerik bloklarında 'ephemeral' olarak ayarlayarak belirli içerik bloklarını (örneğin büyük belgeler veya bağlam) önbelleğe alın.


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

Her istekte yeniden işlemekten kaçınmak için araç tanımlarını önbelleğe alın. Bu, istekler arasında sabit kalan çok sayıda araç tanımınız olduğunda kullanışlıdır.


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

Özellikler

Fiyatlandırma