AIJSONDecoding.swift 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import Foundation
  2. /// Decodes OpenAI JSON fields that may arrive as a string or string array.
  3. struct FlexibleStringOrArray: Decodable {
  4. let value: String
  5. init(from decoder: Decoder) throws {
  6. let container = try decoder.singleValueContainer()
  7. if let string = try? container.decode(String.self) {
  8. value = string
  9. } else if let strings = try? container.decode([String].self) {
  10. value = strings.joined(separator: " ")
  11. } else {
  12. value = ""
  13. }
  14. }
  15. }
  16. /// Decodes OpenAI JSON score fields that may arrive as Int, Double, or String.
  17. struct FlexibleInt: Decodable {
  18. let value: Int
  19. init(from decoder: Decoder) throws {
  20. let container = try decoder.singleValueContainer()
  21. if let int = try? container.decode(Int.self) {
  22. value = int
  23. } else if let double = try? container.decode(Double.self) {
  24. value = Int(double.rounded())
  25. } else if let string = try? container.decode(String.self),
  26. let int = Int(string.trimmingCharacters(in: .whitespaces)) {
  27. value = int
  28. } else {
  29. value = 0
  30. }
  31. }
  32. }
  33. enum AIJSONDecoding {
  34. static func payloadData(from content: String) -> Data? {
  35. var trimmed = content.trimmingCharacters(in: .whitespacesAndNewlines)
  36. if trimmed.hasPrefix("```") {
  37. trimmed = trimmed
  38. .replacingOccurrences(of: "```json", with: "")
  39. .replacingOccurrences(of: "```", with: "")
  40. .trimmingCharacters(in: .whitespacesAndNewlines)
  41. }
  42. return trimmed.data(using: .utf8)
  43. }
  44. }