Skip to content

Commit c2b4aef

Browse files
committed
New example: createChatCompletionWithFailover
1 parent 2192bbd commit c2b4aef

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

openai-core/src/main/scala/io/cequence/openaiscala/RetryHelpers.scala

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,11 @@ object RetryHelpers {
4444
if (attempt < maxAttempts) {
4545
fun().recoverWith {
4646
case e: Throwable if isRetryable(e) =>
47+
val failureMessagePart = failureMessage.map(message => message.stripSuffix(".") + ". ").getOrElse("")
48+
4749
log.foreach(
4850
_(
49-
s"${failureMessage.map(_ + ". ").getOrElse("")}Attempt ${attempt}. Retrying..."
51+
s"${failureMessagePart}Attempt ${attempt}. Retrying..."
5052
)
5153
)
5254

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package io.cequence.openaiscala.examples
2+
3+
import io.cequence.openaiscala.domain._
4+
import io.cequence.openaiscala.domain.settings.CreateChatCompletionSettings
5+
import io.cequence.openaiscala.service.OpenAIChatCompletionExtra._
6+
7+
import scala.concurrent.Future
8+
9+
object CreateChatCompletionWithFailover extends Example {
10+
11+
private val messages = Seq(
12+
SystemMessage("You are a helpful weather assistant."),
13+
UserMessage("What is the weather like in Norway?")
14+
)
15+
16+
override protected def run: Future[_] =
17+
service
18+
.createChatCompletionWithFailover(
19+
messages = messages,
20+
settings = CreateChatCompletionSettings(
21+
model = ModelId.o3_mini + "x" // initentionally to trigger a failure
22+
),
23+
failoverModels = Seq(ModelId.gpt_4_5_preview, ModelId.gpt_4o),
24+
retryOnAnyError = true, // if this is what you want
25+
failureMessage = "Weather assistant failed to provide a response"
26+
)
27+
.map { response =>
28+
println(response.usage.get)
29+
printMessageContent(response)
30+
}
31+
}

0 commit comments

Comments
 (0)