| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- import Foundation
- /// Decodes OpenAI JSON fields that may arrive as a string or string array.
- struct FlexibleStringOrArray: Decodable {
- let value: String
- init(from decoder: Decoder) throws {
- let container = try decoder.singleValueContainer()
- if let string = try? container.decode(String.self) {
- value = string
- } else if let strings = try? container.decode([String].self) {
- value = strings.joined(separator: " ")
- } else {
- value = ""
- }
- }
- }
- /// Decodes OpenAI JSON score fields that may arrive as Int, Double, or String.
- struct FlexibleInt: Decodable {
- let value: Int
- init(from decoder: Decoder) throws {
- let container = try decoder.singleValueContainer()
- if let int = try? container.decode(Int.self) {
- value = int
- } else if let double = try? container.decode(Double.self) {
- value = Int(double.rounded())
- } else if let string = try? container.decode(String.self),
- let int = Int(string.trimmingCharacters(in: .whitespaces)) {
- value = int
- } else {
- value = 0
- }
- }
- }
- enum AIJSONDecoding {
- static func payloadData(from content: String) -> Data? {
- var trimmed = content.trimmingCharacters(in: .whitespacesAndNewlines)
- if trimmed.hasPrefix("```") {
- trimmed = trimmed
- .replacingOccurrences(of: "```json", with: "")
- .replacingOccurrences(of: "```", with: "")
- .trimmingCharacters(in: .whitespacesAndNewlines)
- }
- return trimmed.data(using: .utf8)
- }
- }
|