( systemPrompt: string, messages: Anthropic.Messages.MessageParam[], metadata?: ApiHandlerCreateMessageMetadata, )
| 111 | } |
| 112 | |
| 113 | override async *createMessage( |
| 114 | systemPrompt: string, |
| 115 | messages: Anthropic.Messages.MessageParam[], |
| 116 | metadata?: ApiHandlerCreateMessageMetadata, |
| 117 | ): ApiStream { |
| 118 | const { id: modelId, info } = await this.fetchModel() |
| 119 | |
| 120 | const openAiMessages = convertToOpenAiMessages(messages, { |
| 121 | normalizeToolCallId: sanitizeOpenAiCallId, |
| 122 | }) |
| 123 | |
| 124 | // Prepare messages with cache control if enabled and supported |
| 125 | let systemMessage: OpenAI.Chat.ChatCompletionMessageParam |
| 126 | let enhancedMessages: OpenAI.Chat.ChatCompletionMessageParam[] |
| 127 | |
| 128 | if (this.options.litellmUsePromptCache && info.supportsPromptCache) { |
| 129 | // Create system message with cache control in the proper format |
| 130 | systemMessage = { |
| 131 | role: "system", |
| 132 | content: [ |
| 133 | { |
| 134 | type: "text", |
| 135 | text: systemPrompt, |
| 136 | cache_control: { type: "ephemeral" }, |
| 137 | } as any, |
| 138 | ], |
| 139 | } |
| 140 | |
| 141 | // Find the last two user messages to apply caching |
| 142 | const userMsgIndices = openAiMessages.reduce( |
| 143 | (acc, msg, index) => (msg.role === "user" ? [...acc, index] : acc), |
| 144 | [] as number[], |
| 145 | ) |
| 146 | const lastUserMsgIndex = userMsgIndices[userMsgIndices.length - 1] ?? -1 |
| 147 | const secondLastUserMsgIndex = userMsgIndices[userMsgIndices.length - 2] ?? -1 |
| 148 | |
| 149 | // Apply cache_control to the last two user messages |
| 150 | enhancedMessages = openAiMessages.map((message, index) => { |
| 151 | if ((index === lastUserMsgIndex || index === secondLastUserMsgIndex) && message.role === "user") { |
| 152 | // Handle both string and array content types |
| 153 | if (typeof message.content === "string") { |
| 154 | return { |
| 155 | ...message, |
| 156 | content: [ |
| 157 | { |
| 158 | type: "text", |
| 159 | text: message.content, |
| 160 | cache_control: { type: "ephemeral" }, |
| 161 | } as any, |
| 162 | ], |
| 163 | } |
| 164 | } else if (Array.isArray(message.content)) { |
| 165 | // Apply cache control to the last content item in the array |
| 166 | return { |
| 167 | ...message, |
| 168 | content: message.content.map((content, contentIndex) => |
| 169 | contentIndex === message.content.length - 1 |
| 170 | ? ({ |
nothing calls this directly
no test coverage detected