MCPcopy Index your code
hub / github.com/coder/mux / addCacheControlToLastContentPart

Function addCacheControlToLastContentPart

src/common/utils/ai/cacheStrategy.ts:52–83  ·  view source on GitHub ↗

* Add providerOptions to the last content part of a message. * The SDK requires providerOptions on content parts, not on the message itself. * * For system messages with string content, we use message-level providerOptions * (which the SDK handles correctly). For user/assistant messages with arr

(
  msg: ModelMessage,
  cacheTtl?: AnthropicCacheTtl | null
)

Source from the content-addressed store, hash-verified

50 * content, we add providerOptions to the last content part.
51 */
52function addCacheControlToLastContentPart(
53 msg: ModelMessage,
54 cacheTtl?: AnthropicCacheTtl | null
55): ModelMessage {
56 const cacheOpts = cacheTtl ? anthropicCacheControl(cacheTtl) : ANTHROPIC_CACHE_CONTROL;
57 const content = msg.content;
58
59 // String content (typically system messages): use message-level providerOptions
60 // The SDK correctly translates this for system messages
61 if (typeof content === "string") {
62 return {
63 ...msg,
64 providerOptions: cacheOpts,
65 };
66 }
67
68 // Array content: add providerOptions to the last part
69 // Use type assertion since we're adding providerOptions which is valid but not in base types
70 if (Array.isArray(content) && content.length > 0) {
71 const lastIndex = content.length - 1;
72 const newContent = content.map((part, i) =>
73 i === lastIndex ? { ...part, providerOptions: cacheOpts } : part
74 );
75 // Type assertion needed: ModelMessage types are strict unions but providerOptions
76 // on content parts is valid per SDK docs
77 const result = { ...msg, content: newContent };
78 return result as ModelMessage;
79 }
80
81 // Empty or unexpected content: return as-is
82 return msg;
83}
84
85/**
86 * Apply cache control to messages for Anthropic models.

Callers 1

applyCacheControlFunction · 0.85

Calls 1

anthropicCacheControlFunction · 0.85

Tested by

no test coverage detected