OpenAI icon indicating copy to clipboard operation
OpenAI copied to clipboard

A number of types that are `Codable` don't encode correctly

Open gsabran opened this issue 4 months ago • 1 comments

Describe the bug A number of types that are Codable don't encode correctly. This seems to impact a number of the typed enums that are typically received from an OpenAI compatible server and that are not persisted by a client (unless the client would persist its requests)

For instance ChatQuery.ChatCompletionMessageParam would need a decoding such as

public init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    let role = try container.decode(Role.self, forKey: .role)
    switch role {
    case .system:
        self = try .system(.init(from: decoder))
    case .developer:
      self = try .developer(.init(from: decoder))
    case .user:
      self = try .user(.init(from: decoder))
    case .assistant:
      self = try .assistant(.init(from: decoder))
    case .tool:
      self = try .tool(.init(from: decoder))
    }
}

I mostly look at the types in ChatQuery but typically you need to hand write the encoding / decoding for each typed enum as the generated conformances are not correct and only you know about the key used to determine which nested type is right.

As a side note, it could be helpful to have tests that validate that the encoding and decoding of those types gives back the initial value.

Lmk if you want a PR.

gsabran avatar Aug 15 '25 05:08 gsabran

Hi @gsabran thanks for the issue, you are definitely right, all the types that are Codable should decode and encode correctly. There is already a tests file that tests encoding and decoding, but it probably doesn't cover the cases you mention. It would be great if you'd make PR with the fixes

nezhyborets avatar Aug 15 '25 07:08 nezhyborets