Guard message caching when strategy is "none"

Skip addCacheControlToLastTwoUserMessages when cachingStrategy is "none"
so requests truly have no caching markers. Updates test to verify.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Nate 2026-02-28 16:33:28 -08:00
parent 29f4c21e7a
commit f5f9ccbb16
2 changed files with 11 additions and 9 deletions

View file

@ -83,12 +83,14 @@ describe("AnthropicApi", () => {
}
});
it("still caches user messages even when caching strategy is none", () => {
const body = new AnthropicApi({
it("does not cache user messages when caching strategy is none", () => {
const api = new AnthropicApi({
provider: "anthropic",
apiKey: "test-key",
cachingStrategy: "none",
})._convertToCleanAnthropicBody({
});
const result = (api as any)._convertBody({
model: "claude-sonnet-4-20250514",
messages: [
{ role: "user", content: "Hello" },
@ -97,17 +99,14 @@ describe("AnthropicApi", () => {
],
});
const result = CACHING_STRATEGIES["none"](body);
addCacheControlToLastTwoUserMessages(result.messages);
// User message caching is applied regardless of strategy
// No cache_control should be added when strategy is "none"
const lastUserMsg = result.messages[2];
expect(lastUserMsg.role).toBe("user");
if (Array.isArray(lastUserMsg.content)) {
const textPart = lastUserMsg.content.find(
(p: any) => p.type === "text",
);
expect((textPart as any)?.cache_control).toEqual({ type: "ephemeral" });
expect((textPart as any)?.cache_control).toBeUndefined();
}
});
});

View file

@ -77,7 +77,10 @@ export class AnthropicApi implements BaseLlmApi {
const result = cachingStrategy(cleanBody);
// Step 3: Cache last two user messages for conversation turn caching
addCacheControlToLastTwoUserMessages(result.messages);
// Skip when caching is disabled
if ((this.config.cachingStrategy ?? "systemAndTools") !== "none") {
addCacheControlToLastTwoUserMessages(result.messages);
}
return result;
}