Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(2671): move retry logic and implement tokio_retry #2674

Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ futures-util = { version = "0.3.30" }
indexmap = "2.2.6"
insta = { version = "1.38.0", features = ["json"] }
tokio = { version = "1.37.0", features = ["rt", "time"] }
tokio-retry = "0.3"
reqwest = { version = "0.11", features = [
"json",
"rustls-tls",
Expand Down Expand Up @@ -61,6 +62,7 @@ rustls-pemfile = { version = "1.0.4" }
schemars = { version = "0.8.17", features = ["derive"] }
hyper = { version = "0.14.28", features = ["server"], default-features = false }
tokio = { workspace = true }
tokio-retry = { workspace = true }
anyhow = { workspace = true }
reqwest = { workspace = true }
derive_setters = "0.1.6"
Expand Down
58 changes: 18 additions & 40 deletions src/cli/llm/infer_type_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,7 @@ impl InferTypeName {
}
pub async fn generate(&mut self, config: &Config) -> Result<HashMap<String, String>> {
let secret = self.secret.as_ref().map(|s| s.to_owned());

let wizard: Wizard<Question, Answer> = Wizard::new(groq::LLAMA38192, secret);

let mut new_name_mappings: HashMap<String, String> = HashMap::new();

// removed root type from types.
Expand All @@ -102,47 +100,27 @@ impl InferTypeName {
.collect(),
};

let mut delay = 3;
loop {
let answer = wizard.ask(question.clone()).await;
match answer {
Ok(answer) => {
let name = &answer.suggestions.join(", ");
for name in answer.suggestions {
if config.types.contains_key(&name)
|| new_name_mappings.contains_key(&name)
{
continue;
}
new_name_mappings.insert(name, type_name.to_owned());
break;
match wizard.ask(question).await {
onyedikachi-david marked this conversation as resolved.
Show resolved Hide resolved
Ok(answer) => {
let name = &answer.suggestions.join(", ");
for name in answer.suggestions {
if config.types.contains_key(&name) || new_name_mappings.contains_key(&name)
{
continue;
}
tracing::info!(
"Suggestions for {}: [{}] - {}/{}",
type_name,
name,
i + 1,
total
);

// TODO: case where suggested names are already used, then extend the base
// question with `suggest different names, we have already used following
// names: [names list]`
new_name_mappings.insert(name, type_name.to_owned());
break;
}
Err(e) => {
// TODO: log errors after certain number of retries.
if let Error::GenAI(_) = e {
// TODO: retry only when it's required.
tracing::warn!(
"Unable to retrieve a name for the type '{}'. Retrying in {}s",
type_name,
delay
);
tokio::time::sleep(tokio::time::Duration::from_secs(delay)).await;
delay *= std::cmp::min(delay * 2, 60);
}
}
tracing::info!(
"Suggestions for {}: [{}] - {}/{}",
type_name,
name,
i + 1,
total
);
}
Err(e) => {
tracing::error!("Failed to generate name for {}: {:?}", type_name, e);
}
}
}
Expand Down
48 changes: 40 additions & 8 deletions src/cli/llm/wizard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ use genai::adapter::AdapterKind;
use genai::chat::{ChatOptions, ChatRequest, ChatResponse};
use genai::resolver::AuthResolver;
use genai::Client;
use tokio_retry::strategy::{jitter, ExponentialBackoff};
use tokio_retry::Retry;

use super::Result;
use super::error::{Error, Result};
use crate::cli::llm::model::Model;

#[derive(Setters, Clone)]
Expand Down Expand Up @@ -41,13 +43,43 @@ impl<Q, A> Wizard<Q, A> {

pub async fn ask(&self, q: Q) -> Result<A>
where
Q: TryInto<ChatRequest, Error = super::Error>,
A: TryFrom<ChatResponse, Error = super::Error>,
Q: TryInto<ChatRequest, Error = Error> + Clone,
A: TryFrom<ChatResponse, Error = Error>,
{
let response = self
.client
.exec_chat(self.model.as_str(), q.try_into()?, None)
.await?;
A::try_from(response)
let retry_strategy = ExponentialBackoff::from_millis(1000).map(jitter).take(5);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the base for the strategy is too high, please, check the doc, it'll be 1 sec -> 16 minutes -> 277 hours -> ... in that case.

Consider:

  • change the base the way base ^ attempt is reasonable
  • you may use the factor option to simplify the math
  • specify max_delay to limit maximum delay
  • don't use jitter, it adds randomness making it harder to mitigate 429 status


Retry::spawn(retry_strategy, || async {
onyedikachi-david marked this conversation as resolved.
Show resolved Hide resolved
let request = q.clone().try_into()?;
match self
.client
.exec_chat(self.model.as_str(), request, None)
.await
{
Ok(response) => Ok(A::try_from(response)?),
Err(genai::Error::WebModelCall { webc_error, .. }) => {
if webc_error.to_string().contains("429") {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pattern match instead of performing a string comparison — webc::Error::ResponseFailedStatus { status: 429, body: _ }

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The webc module is not publicly exposed, so i cant match with it.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've gotten a workaround. I'll make a push soon.

Err(Error::GenAI(genai::Error::WebModelCall {
model_info: genai::ModelInfo::new(
AdapterKind::from_model(self.model.as_str())
.unwrap_or(AdapterKind::Ollama),
self.model.as_str(),
),
webc_error,
}))
} else {
Ok(Err(Error::GenAI(genai::Error::WebModelCall {
model_info: genai::ModelInfo::new(
AdapterKind::from_model(self.model.as_str())
.unwrap_or(AdapterKind::Ollama),
self.model.as_str(),
),
webc_error,
}))?)
}
}
Err(e) => Ok(Err(Error::GenAI(e))?),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should just check for the condition here that the status code is 429

}
})
.await
}
}
Loading