프롬프트 캐싱을 사용하면 API 호출 간에 자주 사용되는 컨텍스트를 캐시하여 캐시 읽기 비용을 최대 90%까지 절감하고 지연 시간을 개선할 수 있습니다. 캐시된 콘텐츠는 cache_control 매개변수로 표시되며 캐시 TTL 윈도우 내의 요청 전반에서 재사용됩니다.
긴 시스템 프롬프트를 캐싱하여 모든 요청에서 다시 처리하는 것을 피하십시오. SystemCacheControl을 True로 설정하면 시스템 프롬프트가 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 블록에 CacheControl을 'ephemeral'로 설정하여 특정 content 블록(예: 큰 문서나 컨텍스트)을 캐시하십시오.
oBlock := TsgcAnthropicClass_Request_Content_Block.Create;
oBlock.ContentType := 'text';
oBlock.Text := '(large reference text to cache)';
oBlock.CacheControl := 'ephemeral'; // Mark for caching
모든 요청에서 도구 정의를 다시 처리하지 않도록 도구 정의를 캐시합니다. 요청 간에 일정하게 유지되는 도구 정의가 많은 경우 유용합니다.
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