(systemPrompt: string, messages: OpenAI.Chat.ChatCompletionMessageParam[])
| 1 | import OpenAI from "openai" |
| 2 | |
| 3 | export function addCacheBreakpoints(systemPrompt: string, messages: OpenAI.Chat.ChatCompletionMessageParam[]) { |
| 4 | // Apply cache_control to system message at the message level |
| 5 | messages[0] = { |
| 6 | role: "system", |
| 7 | content: systemPrompt, |
| 8 | // @ts-ignore-next-line |
| 9 | cache_control: { type: "ephemeral" }, |
| 10 | } |
| 11 | |
| 12 | // Add cache_control to the last two user messages for conversation context caching |
| 13 | const lastTwoUserMessages = messages.filter((msg) => msg.role === "user").slice(-2) |
| 14 | |
| 15 | lastTwoUserMessages.forEach((msg) => { |
| 16 | if (typeof msg.content === "string" && msg.content.length > 0) { |
| 17 | msg.content = [{ type: "text", text: msg.content }] |
| 18 | } |
| 19 | |
| 20 | if (Array.isArray(msg.content)) { |
| 21 | // Find the last text part in the message content |
| 22 | const lastTextPart = msg.content.filter((part) => part.type === "text").pop() |
| 23 | |
| 24 | if (lastTextPart && lastTextPart.text && lastTextPart.text.length > 0) { |
| 25 | // @ts-ignore-next-line |
| 26 | lastTextPart["cache_control"] = { type: "ephemeral" } |
| 27 | } |
| 28 | } |
| 29 | }) |
| 30 | } |
no test coverage detected