@@ -6,17 +6,65 @@ import Preferences
66
77/// https://platform.openai.com/docs/api-reference/chat/create
88actor OpenAIChatCompletionsService : ChatCompletionsStreamAPI , ChatCompletionsAPI {
9- struct CompletionAPIError : Error , Codable , LocalizedError {
10- struct E : Codable {
9+ struct CompletionAPIError : Error , Decodable , LocalizedError {
10+ struct ErrorDetail : Decodable {
1111 var message : String
1212 var type : String
1313 var param : String
1414 var code : String
1515 }
1616
17- var error : E
17+ struct MistralAIErrorMessage : Decodable {
18+ struct Detail : Decodable {
19+ var msg : String ?
20+ }
21+
22+ var message : String ?
23+ var msg : String ?
24+ var detail : [ Detail ] ?
25+ }
26+
27+ enum Message {
28+ case raw( String )
29+ case mistralAI( MistralAIErrorMessage )
30+ }
31+
32+ var error : ErrorDetail ?
33+ var message : Message
34+
35+ var errorDescription : String ? {
36+ if let message = error? . message { return message }
37+ switch message {
38+ case let . raw( string) :
39+ return string
40+ case let . mistralAI( mistralAIErrorMessage) :
41+ return mistralAIErrorMessage. message
42+ ?? mistralAIErrorMessage. msg
43+ ?? mistralAIErrorMessage. detail? . first? . msg
44+ ?? " Unknown Error "
45+ }
46+ }
47+
48+ enum CodingKeys : String , CodingKey {
49+ case error
50+ case message
51+ }
52+
53+ init ( from decoder: Decoder ) throws {
54+ let container : KeyedDecodingContainer < CodingKeys > = try decoder
55+ . container ( keyedBy: CodingKeys . self)
1856
19- var errorDescription : String ? { error. message }
57+ error = try ? container. decode ( ErrorDetail . self, forKey: . error)
58+ message = {
59+ if let e = try ? container. decode ( MistralAIErrorMessage . self, forKey: . message) {
60+ return CompletionAPIError . Message. mistralAI ( e)
61+ }
62+ if let e = try ? container. decode ( String . self, forKey: . message) {
63+ return . raw( e)
64+ }
65+ return . raw( " Unknown Error " )
66+ } ( )
67+ }
2068 }
2169
2270 enum MessageRole : String , Codable {
@@ -214,7 +262,7 @@ actor OpenAIChatCompletionsService: ChatCompletionsStreamAPI, ChatCompletionsAPI
214262 guard let data = text. data ( using: . utf8)
215263 else { throw ChatGPTServiceError . responseInvalid }
216264 let decoder = JSONDecoder ( )
217- let error = try ? decoder. decode ( ChatGPTError . self, from: data)
265+ let error = try ? decoder. decode ( CompletionAPIError . self, from: data)
218266 throw error ?? ChatGPTServiceError . responseInvalid
219267 }
220268
0 commit comments