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 9 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
45 changes: 40 additions & 5 deletions src/cli/llm/error.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,46 @@
use derive_more::From;
use strum_macros::Display;
use reqwest::StatusCode;
use thiserror::Error;

#[derive(Debug, From, Display, thiserror::Error)]
#[derive(Debug, Error)]
pub enum WebcError {
#[error("Response failed with status {status}: {body}")]
ResponseFailedStatus { status: StatusCode, body: String },
#[error("Reqwest error: {0}")]
Reqwest(#[from] reqwest::Error),
}

#[derive(Debug, Error)]
pub enum Error {
#[error("GenAI error: {0}")]
GenAI(genai::Error),
#[error("Webc error: {0}")]
Webc(WebcError),
#[error("Empty response")]
EmptyResponse,
Serde(serde_json::Error),
#[error("Serde error: {0}")]
Serde(#[from] serde_json::Error),
}

impl From<genai::Error> for Error {
fn from(err: genai::Error) -> Self {
Comment on lines +24 to +25
Copy link
Contributor

Choose a reason for hiding this comment

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

You might not need so much code since this is merged — jeremychone/rust-genai@736bbec

Copy link
Author

Choose a reason for hiding this comment

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

Oh, great.

Copy link
Author

Choose a reason for hiding this comment

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

@tusharmath Pls, why is this repo: https://github.dev/laststylebender14/rust-genai being used instead of the main genai repo: https://github.com/jeremychone/rust-genai

jeremychone's latest lib.rs:

// region:    --- Modules

mod support;

mod client;
mod common;
mod error;

// -- Flatten
pub use client::*;
pub use common::*;
pub use error::{Error, Result};

// -- Public Modules
pub mod adapter;
pub mod chat;
pub mod resolver;
pub mod webc;

// endregion: --- Modules

laststylebender14's latest commit hash lib.rs:

// region:    --- Modules

mod support;
mod webc;

mod client;
mod common;
mod error;

// -- Flatten
pub use client::*;
pub use common::*;
pub use error::{Error, Result};

// -- Public Modules
pub mod adapter;
pub mod chat;
pub mod resolver;

// endregion: --- Modules

So the webc is still private.

Copy link
Contributor

Choose a reason for hiding this comment

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

@laststylebender14 can you update your Repo with the latest changes? Also can you transfer ownership to tailcallhq

Copy link
Contributor

Choose a reason for hiding this comment

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

@onyedikachi-david I have taken the latest changes here — https://github.com/tailcallhq/rust-genai

Copy link
Author

Choose a reason for hiding this comment

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

Okay

Copy link
Contributor

Choose a reason for hiding this comment

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

please apply discussed changes:

if let genai::Error::WebModelCall { webc_error, .. } = &err {
let error_str = webc_error.to_string();
if error_str.contains("ResponseFailedStatus") {
// Extract status and body from the error message
let parts: Vec<&str> = error_str.splitn(3, ": ").collect();
if parts.len() >= 3 {
if let Ok(status) = parts[1].parse::<u16>() {
return Error::Webc(WebcError::ResponseFailedStatus {
status: StatusCode::from_u16(status)
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
body: parts[2].to_string(),
});
}
}
}
}
Error::GenAI(err)
}
}
onyedikachi-david marked this conversation as resolved.
Show resolved Hide resolved

pub type Result<A> = std::result::Result<A, Error>;
pub type Result<T> = std::result::Result<T, Error>;
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
40 changes: 32 additions & 8 deletions src/cli/llm/wizard.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
// use std::borrow::Borrow;
onyedikachi-david marked this conversation as resolved.
Show resolved Hide resolved

use derive_setters::Setters;
use genai::adapter::AdapterKind;
use genai::chat::{ChatOptions, ChatRequest, ChatResponse};
use genai::resolver::AuthResolver;
use genai::Client;
use reqwest::StatusCode;
use tokio_retry::strategy::{jitter, ExponentialBackoff};
use tokio_retry::Retry;

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

#[derive(Setters, Clone)]
Expand Down Expand Up @@ -41,13 +46,32 @@ 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(err) => {
let error = Error::from(err);
match &error {
Error::Webc(WebcError::ResponseFailedStatus { status, .. })
if *status == StatusCode::TOO_MANY_REQUESTS =>
{
Err(error) // Propagate the error to trigger a retry
}
_ => Ok(Err(error)?), // Other errors are returned without retrying
}
}
}
})
.await
}
}