1use std::time::{Duration, SystemTime};
6
7use super::ErrorReport;
8
9impl ErrorReport {
10 pub fn retry_after(&self, now: SystemTime) -> Option<Duration> {
15 let header = |name: &str| {
16 self.provider_response_headers()
17 .and_then(|headers| headers.get(name))
18 .and_then(|value| value.to_str().ok())
19 .map(str::trim)
20 };
21 if let Some(millis) = header("retry-after-ms").and_then(|value| value.parse::<f64>().ok()) {
22 return seconds(millis / 1000.0);
23 }
24 if let Some(value) = header("retry-after") {
25 return match value.parse::<f64>() {
26 Ok(secs) => seconds(secs),
27 Err(_) => httpdate::parse_http_date(value)
28 .ok()
29 .map(|at| at.duration_since(now).unwrap_or_default()),
30 };
31 }
32 let body = self
33 .provider_response_body()
34 .unwrap_or(&self.message)
35 .to_ascii_lowercase();
36 ["\"retrydelay\"", "try again in "]
37 .iter()
38 .find_map(|marker| {
39 let after = body.get(body.find(marker)? + marker.len()..)?;
40 hinted_wait(after.trim_start_matches([' ', ':', '"']))
41 })
42 }
43
44 pub fn is_context_overflow(&self) -> bool {
51 if self.code.as_deref() == Some("context_length_exceeded") {
52 return true;
53 }
54 if self.is_retryable() {
55 return false;
56 }
57 if self.http_status == Some(413) {
58 return true;
59 }
60 [Some(self.message.as_str()), self.provider_response_body()]
61 .into_iter()
62 .flatten()
63 .map(str::to_ascii_lowercase)
64 .any(|text| says_overflow(&text) && !says_rate_limit(&text))
65 }
66}
67
68const OVERFLOW: &[&str] = &[
71 "prompt is too long",
72 "prompt too long",
73 "prompt exceeds max length",
74 "request_too_large",
75 "input is too long for requested model",
76 "exceeds the context window",
77 "maximum context length",
78 "maximum prompt length is",
79 "reduce the length of the messages",
80 "maximum allowed input length",
81 "than the model's context length",
82 "than the models context length",
83 "greater than the context length",
84 "exceeds the limit of ",
85 "exceeds the available context size",
86 "context window exceeds limit",
87 "exceeded model token limit",
88 "but the configured context size is",
89 "model_context_window_exceeded",
90 "exceeded context length",
91 "exceeded max context length",
92 "range of input length should be",
93 "context_length_exceeded",
94 "context length exceeded",
95 "too many tokens",
96 "token limit exceeded",
97];
98
99fn says_overflow(text: &str) -> bool {
101 OVERFLOW.iter().any(|phrase| text.contains(phrase))
102 || (text.contains("input token count") && text.contains("exceeds the maximum"))
103}
104
105fn says_rate_limit(text: &str) -> bool {
108 text.starts_with("throttling error:")
109 || text.starts_with("service unavailable:")
110 || text.contains("rate limit")
111 || text.contains("too many requests")
112}
113
114fn seconds(secs: f64) -> Option<Duration> {
116 Duration::try_from_secs_f64(secs.max(0.0)).ok()
117}
118
119fn hinted_wait(text: &str) -> Option<Duration> {
121 let end = text
122 .find(|c: char| !(c.is_ascii_digit() || c == '.'))
123 .unwrap_or(text.len());
124 let amount: f64 = text.get(..end)?.parse().ok()?;
125 let unit = text.get(end..)?.trim_start();
126 let unit_end = unit
127 .find(|c: char| !c.is_ascii_alphanumeric())
128 .unwrap_or(unit.len());
129 match unit.get(..unit_end)? {
130 "ms" => seconds(amount / 1000.0),
131 "s" => seconds(amount),
132 _ => None,
133 }
134}
135
136#[cfg(test)]
137mod tests;