如何在Kotlin使用OpenAI API客户端时捕获异常?

q8l4jmvw  于 2023-05-18  发布在  Kotlin
关注(0)|答案(1)|浏览(166)

bounty还有4天到期。回答此问题可获得+50声望奖励。HelloCW正在寻找一个答案从一个有信誉的来源

我在Android Studio项目中使用OpenAI API client forKotlin。
我用代码A把声音转录成文字
1:我不知道val transcription = openAI.transcription(transcriptionRequest)是否可以抛出异常,你能告诉我吗?
2:当val transcription = openAI.transcription(transcriptionRequest)崩溃时,我如何获得错误信息?
顺便说一句,代码B是源代码,它返回Transcription类,似乎不会抛出异常。

代码A

val apiKey = "sk-..."
    val openAI = OpenAI(apiKey)

    val transcriptionRequest = TranscriptionRequest(
        audio = FileSource(path = mInfo.soundFilename.toPath(), fileSystem = FileSystem.SYSTEM),
        model = ModelId("whisper-1"),
    )

   val transcription = openAI.transcription(transcriptionRequest)

    mInfo.text = transcription.text

代码B

@BetaOpenAI
    public suspend fun transcription(request: TranscriptionRequest): Transcription
kd3sttzy

kd3sttzy1#

看看aallam/openai-kotlin issue 131,你可以尝试用com.aallam.openai.api.exception包中的例外来封装你的OpenAI代码:

val apiKey = "sk-..."
val openAI = OpenAI(apiKey)

val transcriptionRequest = TranscriptionRequest(
    audio = FileSource(path = mInfo.soundFilename.toPath(), fileSystem = FileSystem.SYSTEM),
    model = ModelId("whisper-1"),
)

try {
    val transcription = openAI.transcription(transcriptionRequest)
    mInfo.text = transcription.text
} catch (e: OpenAIException) {
    // Handle OpenAIExceptions
    println("OpenAIException: ${e.message}")
} catch (e: OpenAIHttpException) {
    // Handle OpenAIHttpExceptions
    println("OpenAIHttpException: ${e.message}")
} catch (e: OpenAIAPIException) {
    // Handle OpenAIAPIExceptions
    println("OpenAIAPIException: ${e.message}")
} catch (e: Exception) {
    // Handle any other exceptions
    println("Unexpected error: ${e.message}")
}

这将处理OpenAIKotlinAPI客户端可能抛出的特定异常OpenAIExceptionOpenAIHttpExceptionOpenAIAPIException,以及任何其他异常的通用catch-all。

相关问题