Skip to content

Commit

Permalink
Merge pull request #638 from takahirom/takahirom/improve-openai-api-e…
Browse files Browse the repository at this point in the history
…rror-handring/2025-01-24

Improve OpenAI api error handling
  • Loading branch information
takahirom authored Jan 24, 2025
2 parents a1723f0 + c26f4ae commit 3f777cf
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,6 @@ INPUT_PROMPT
*/
val requiredFulfillmentPercent: Int? = 80
)
}
}

class AiAssertionApiException(val statusCode: Int, message: String) : Exception(message)
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class OpenAiAiAssertionModel(
install(Logging) {
logger = object : Logger {
override fun log(message: String) {
Logger.SIMPLE.log(message.replace(apiKey, "****"))
Logger.SIMPLE.log(message.hideApiKey(apiKey))
}
}
level = LogLevel.ALL
Expand Down Expand Up @@ -137,7 +137,13 @@ class OpenAiAiAssertionModel(
setBody(requestBody)
}
val bodyText = response.bodyAsText()
debugLog { "OpenAiAiModel: response: $bodyText" }
debugLog { "OpenAiAiModel: response: ${bodyText.hideApiKey(apiKey)}" }
if (response.status.value >= 400) {
throw AiAssertionApiException(
response.status.value, bodyText
.hideApiKey(apiKey)
)
}
val responseBody: ChatCompletionResponse = json.decodeFromString(bodyText)
return responseBody.choices.firstOrNull()?.message?.content ?: ""
}
Expand Down Expand Up @@ -301,4 +307,8 @@ private data class OpenAiConditionResult(
@SerialName("fulfillment_percent")
val fulfillmentPercent: Int,
val explanation: String?,
)
)

private fun String.hideApiKey(key: String): String {
return this.replace(key.ifBlank { "****" }, "****")
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,7 @@ import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.takahirom.roborazzi.AiAssertionOptions
import com.github.takahirom.roborazzi.DEFAULT_ROBORAZZI_OUTPUT_DIR_PATH
import com.github.takahirom.roborazzi.ExperimentalRoborazziApi
import com.github.takahirom.roborazzi.OpenAiAiAssertionModel
import com.github.takahirom.roborazzi.ROBORAZZI_DEBUG
import com.github.takahirom.roborazzi.RobolectricDeviceQualifiers
import com.github.takahirom.roborazzi.RoborazziOptions
import com.github.takahirom.roborazzi.RoborazziRule
import com.github.takahirom.roborazzi.RoborazziTaskType
import com.github.takahirom.roborazzi.captureRoboImage
import com.github.takahirom.roborazzi.provideRoborazziContext
import com.github.takahirom.roborazzi.roboOutputName
import com.github.takahirom.roborazzi.*
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
Expand Down

0 comments on commit 3f777cf

Please sign in to comment.