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 14 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 @@ -62,6 +63,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 {
if let genai::Error::WebModelCall { webc_error, .. } = &err {
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:

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(),
});
}
}
}
};
err.into()
}
}

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>;
37 changes: 13 additions & 24 deletions src/cli/llm/infer_type_name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@
}

pub async fn generate(&mut self, config: &Config) -> Result<HashMap<String, String>> {

let mut new_name_mappings: HashMap<String, String> = HashMap::new();
// Filter out root operation types and types with non-auto-generated names
let types_to_be_processed = config
Expand Down Expand Up @@ -123,6 +124,7 @@
.collect(),
};


let mut delay = 3;
loop {
Comment on lines 128 to 129
Copy link
Contributor

Choose a reason for hiding this comment

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

loop is not needed anymore

let answer = self.wizard.ask(question.clone()).await;
Expand All @@ -137,32 +139,19 @@
new_name_mappings.insert(type_name.to_owned(), name);
break;
}
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());

Check failure on line 142 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Formatter and Lint Check

mismatched types

Check failure on line 142 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Formatter and Lint Check

mismatched types

Check failure on line 142 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Check Examples

mismatched types

Check failure on line 142 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on linux-x64-musl

mismatched types

Check failure on line 142 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on darwin-x64

mismatched types

Check failure on line 142 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on linux-x64-gnu

mismatched types

Check failure on line 142 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on linux-arm64-musl

mismatched types

Check failure on line 142 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on linux-ia32-gnu

mismatched types

Check failure on line 142 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on linux-arm64-gnu

mismatched types

Check failure on line 142 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on darwin-arm64

mismatched types

Check failure on line 142 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on win32-x64-msvc

mismatched types

Check failure on line 142 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on win32-ia32-msvc

mismatched types
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
);

Check failure on line 151 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Formatter and Lint Check

expected one of `,`, `=>`, `if`, `|`, or `}`, found `;`

Check failure on line 151 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Formatter and Lint Check

expected one of `,`, `=>`, `if`, `|`, or `}`, found `;`

Check failure on line 151 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Formatter and Lint Check

expected one of `,`, `=>`, `if`, `|`, or `}`, found `;`

Check failure on line 151 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Check Examples

expected one of `,`, `=>`, `if`, `|`, or `}`, found `;`

Check failure on line 151 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on linux-x64-musl

expected one of `,`, `=>`, `if`, `|`, or `}`, found `;`

Check failure on line 151 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on darwin-x64

expected one of `,`, `=>`, `if`, `|`, or `}`, found `;`

Check failure on line 151 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on linux-x64-gnu

expected one of `,`, `=>`, `if`, `|`, or `}`, found `;`

Check failure on line 151 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on linux-arm64-musl

expected one of `,`, `=>`, `if`, `|`, or `}`, found `;`

Check failure on line 151 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on linux-ia32-gnu

expected one of `,`, `=>`, `if`, `|`, or `}`, found `;`

Check failure on line 151 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on linux-arm64-gnu

expected one of `,`, `=>`, `if`, `|`, or `}`, found `;`

Check failure on line 151 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on darwin-arm64

expected one of `,`, `=>`, `if`, `|`, or `}`, found `;`

Check failure on line 151 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on win32-x64-msvc

expected one of `,`, `=>`, `if`, `|`, or `}`, found `;`

Check failure on line 151 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on win32-ia32-msvc

expected one of `,`, `=>`, `if`, `|`, or `}`, found `;`
}
Err(e) => {

Check failure on line 153 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Formatter and Lint Check

expected one of `.`, `;`, `?`, `}`, or an operator, found `=>`

Check failure on line 153 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Formatter and Lint Check

expected one of `.`, `;`, `?`, `}`, or an operator, found `=>`

Check failure on line 153 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Formatter and Lint Check

expected one of `.`, `;`, `?`, `}`, or an operator, found `=>`

Check failure on line 153 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Check Examples

expected one of `.`, `;`, `?`, `}`, or an operator, found `=>`

Check failure on line 153 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on linux-x64-musl

expected one of `.`, `;`, `?`, `}`, or an operator, found `=>`

Check failure on line 153 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on darwin-x64

expected one of `.`, `;`, `?`, `}`, or an operator, found `=>`

Check failure on line 153 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on linux-x64-gnu

expected one of `.`, `;`, `?`, `}`, or an operator, found `=>`

Check failure on line 153 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on linux-arm64-musl

expected one of `.`, `;`, `?`, `}`, or an operator, found `=>`

Check failure on line 153 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on linux-ia32-gnu

expected one of `.`, `;`, `?`, `}`, or an operator, found `=>`

Check failure on line 153 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on linux-arm64-gnu

expected one of `.`, `;`, `?`, `}`, or an operator, found `=>`

Check failure on line 153 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on darwin-arm64

expected one of `.`, `;`, `?`, `}`, or an operator, found `=>`

Check failure on line 153 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on win32-x64-msvc

expected one of `.`, `;`, `?`, `}`, or an operator, found `=>`

Check failure on line 153 in src/cli/llm/infer_type_name.rs

View workflow job for this annotation

GitHub Actions / Run Tests on win32-ia32-msvc

expected one of `.`, `;`, `?`, `}`, or an operator, found `=>`
tracing::error!("Failed to generate name for {}: {:?}", type_name, e);
}
}
}
Expand Down
30 changes: 21 additions & 9 deletions src/cli/llm/wizard.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use super::error::{Error, Result, WebcError};
use derive_setters::Setters;
use genai::adapter::AdapterKind;
use genai::chat::{ChatOptions, ChatRequest, ChatResponse};
use genai::resolver::AuthResolver;
use genai::Client;

use super::Result;
use reqwest::StatusCode;
use tokio_retry::strategy::{jitter, ExponentialBackoff};
use tokio_retry::RetryIf;

#[derive(Setters, Clone)]
pub struct Wizard<Q, A> {
Expand Down Expand Up @@ -40,13 +42,23 @@ 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


RetryIf::spawn(
retry_strategy,
|| async {
let request = q.clone().try_into()?;
self.client
.exec_chat(self.model.as_str(), request, None)
.await
.map_err(Error::from)
.and_then(A::try_from)
},
|err: &Error| matches!(err, Error::Webc(WebcError::ResponseFailedStatus { status, .. }) if *status == StatusCode::TOO_MANY_REQUESTS)
)
.await
}
}
Loading