| 39 | } |
| 40 | |
| 41 | std::string normalize_system_for_cache(const json & system_or_messages) { |
| 42 | if (system_or_messages.is_array()) { |
| 43 | if (system_or_messages.empty()) return ""; |
| 44 | const auto & first = system_or_messages[0]; |
| 45 | if (first.is_object() && first.contains("role")) { |
| 46 | // OpenAI messages array: strip billing-header lines from messages[0]. |
| 47 | if (first.value("role", "") == "system") { |
| 48 | const auto & content = first["content"]; |
| 49 | if (content.is_string()) { |
| 50 | return strip_billing_header_lines(content.get<std::string>()); |
| 51 | } |
| 52 | if (content.is_array()) { |
| 53 | std::string out; |
| 54 | for (const auto & block : content) { |
| 55 | if (block.is_object() && block.value("type", "") == "text") { |
| 56 | out += block.value("text", ""); |
| 57 | } |
| 58 | } |
| 59 | return strip_billing_header_lines(out); |
| 60 | } |
| 61 | } |
| 62 | return ""; |
| 63 | } |
| 64 | // Anthropic content-block array: skip billing-header blocks entirely. |
| 65 | std::string out; |
| 66 | for (const auto & block : system_or_messages) { |
| 67 | if (block.is_object() && block.value("type", "") == "text") { |
| 68 | std::string text = block.value("text", ""); |
| 69 | if (!is_billing_header_block(text)) out += text; |
| 70 | } |
| 71 | } |
| 72 | return out; |
| 73 | } |
| 74 | |
| 75 | if (system_or_messages.is_string()) { |
| 76 | return strip_billing_header_lines(system_or_messages.get<std::string>()); |
| 77 | } |
| 78 | |
| 79 | return ""; |
| 80 | } |
| 81 | |
| 82 | } // namespace dflash::common |