1
1
package io .cequence .openaiscala .service
2
2
3
3
import akka .actor .Scheduler
4
+ import com .fasterxml .jackson .core .JsonParseException
4
5
import io .cequence .openaiscala .JsonFormats .eitherJsonSchemaFormat
5
6
import io .cequence .openaiscala .RetryHelpers .RetrySettings
6
- import io .cequence .openaiscala .{RetryHelpers , Retryable }
7
+ import io .cequence .openaiscala .{OpenAIScalaClientException , RetryHelpers , Retryable }
7
8
import io .cequence .openaiscala .domain .response .ChatCompletionResponse
8
9
import io .cequence .openaiscala .domain .settings .{
9
10
ChatCompletionResponseFormatType ,
@@ -92,7 +93,7 @@ object OpenAIChatCompletionExtra {
92
93
val content = response.choices.head.message.content
93
94
val contentTrimmed = content.stripPrefix(" ```json" ).stripSuffix(" ```" ).trim
94
95
val contentJson = contentTrimmed.dropWhile(_ != '{' )
95
- val json = Json .parse (contentJson)
96
+ val json = parseJsonOrThrow (contentJson)
96
97
97
98
logger.debug(
98
99
s " ${taskNameForLoggingFinal.capitalize} finished in " + (new java.util.Date ().getTime - start.getTime) + " ms."
@@ -102,6 +103,17 @@ object OpenAIChatCompletionExtra {
102
103
}
103
104
}
104
105
106
+ private def parseJsonOrThrow (
107
+ jsonString : String
108
+ ) = try {
109
+ Json .parse(jsonString)
110
+ } catch {
111
+ case e : JsonParseException =>
112
+ val message = " Failed to parse JSON response:\n " + jsonString
113
+ logger.error(message)
114
+ throw new OpenAIScalaClientException (message, e)
115
+ }
116
+
105
117
private def isRetryable (
106
118
retryOnAnyError : Boolean
107
119
): Throwable => Boolean =
0 commit comments