64bit / async-openai

Rust library for OpenAI
https://docs.rs/async-openai
MIT License
1.09k stars 161 forks source link

Format `OpenAIError::APIError` with client-friendly message #238

Closed GabrielBianconi closed 1 month ago

GabrielBianconi commented 2 months ago

In error.rs, we have:

...
    #[error("{:?}: {}", .0.r#type, .0.message)]
    ApiError(ApiError),
...
pub struct ApiError {
    pub message: String,
    pub r#type: Option<String>,
    pub param: Option<String>,
    pub code: Option<String>,
}
...

The {:?} leads to error messages that aren't client-friendly, such as:

Some(\"invalid_request_error\"): This model's maximum context length is 16385 tokens. However, your messages resulted in 25015 tokens (24961 in the messages, 54 in the functions). Please reduce the length of the messages or functions.

Could we replace it with something more client-friendly like:

...
    #[error("{}: {}", .0.r#type. unwrap_or("unknown_error_type".to_string()), .0.message)]
    ApiError(ApiError),
...

Thanks!

64bit commented 2 months ago

Sure, however I wouldn't put a made up type unknown_error_type and instead keep it empty '' when absent, or not even include it in format string if absent.

In addition, it makes sense to do the same for all fields of struct ApiError for consistency. PR is welcome!

GabrielBianconi commented 2 months ago

Great.

@64bit Could you clarify what you have in mind for "In addition, it makes sense to do the same for all fields of struct ApiError for consistency."? Do you mean adding param and code, if available? (They're not currently included, and message isn't optional.)

I can send a PR later.

64bit commented 1 month ago

Ah yes, your interpretation is correct. Previously the message was sort of "key": "value". Might as well do the same for all the fields in the struct ApiError once and for all..

GabrielBianconi commented 1 month ago

Sounds good. I'll send a PR in a few days.