From be38e1e5a3e3a0fc408fdf44aefa12bb7c4e008c Mon Sep 17 00:00:00 2001 From: Aleksei Voronov Date: Wed, 29 Nov 2023 13:57:44 +0100 Subject: [PATCH] Handle cases when chatgpt doesn't respond with anything gracefully It hasn't happened yet, but it's a ticking time bomb --- src/services/ai.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/services/ai.rs b/src/services/ai.rs index 71e7eae..739c0c7 100644 --- a/src/services/ai.rs +++ b/src/services/ai.rs @@ -1,4 +1,4 @@ -use anyhow::Result; +use anyhow::{anyhow, Result}; use chat_gpt_lib_rs::{ChatGPTClient, ChatInput, Message, Model, Role}; pub struct AI { @@ -35,7 +35,10 @@ impl AI { let response = self.chat_gpt_client.chat(chat_input).await?; - // TODO: Error handling? - Ok(response.choices[0].message.content.to_lowercase()) + response + .choices + .get(0) + .map(|choice| choice.message.content.to_lowercase()) + .ok_or_else(|| anyhow!("No choices received from ChatGPT, weird")) } }