* 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 )
| 50 | * content, we add providerOptions to the last content part. |
| 51 | */ |
| 52 | function 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. |
no test coverage detected