wxMaxima
Loading...
Searching...
No Matches
llm_retry.hpp
1#pragma once
2
3// llm-retry: single-header C++ retry + circuit breaker for LLM API calls
4// Usage: #define LLM_RETRY_IMPLEMENTATION in ONE .cpp file before including.
5
6#include <chrono>
7#include <ctime>
8#include <functional>
9#include <mutex>
10#include <random>
11#include <stdexcept>
12#include <string>
13#include <thread>
14#include <vector>
15
16namespace llm {
17
18// ─── Config ──────────────────────────────────────────────────────────────────
19
21 int max_attempts = 3;
22 double base_delay_ms = 500.0;
23 double max_delay_ms = 30000.0;
24 double backoff_multiplier = 2.0;
25 double jitter_factor = 0.1;
26 // 408 request timeout and 529 overloaded (Anthropic's overloaded_error)
27 // are transient, so they are retried along with 429 and the 5xx codes.
28 std::vector<int> retry_on_http_codes = {408, 429, 500, 502, 503, 504, 529};
29};
30
32 int failure_threshold = 5;
33 double success_threshold = 0.8; // unused since 0.2: one half-open trial decides
34 double timeout_seconds = 60.0;
35};
36
37// ─── Types ───────────────────────────────────────────────────────────────────
38
39enum class CircuitState { Closed, Open, HalfOpen };
40
41template<typename T>
43 T value;
44 int attempts_used;
45 double total_elapsed_ms;
46 bool from_fallback;
47};
48
49struct LLMError {
50 int http_code; // 0 if not HTTP error
51 std::string message;
52 bool is_retryable;
53 // Seconds from the server's Retry-After header, or -1 if there was none.
54 // When set, with_retry waits this long (plus a random spread) instead of
55 // using its own backoff formula.
56 double retry_after_seconds = -1.0;
57};
58
59// ─── Helpers (declarations) ──────────────────────────────────────────────────
60
61int parse_http_code(const std::string& response_header);
62
63namespace detail {
64 bool is_retryable_code(int code, const std::vector<int>& codes);
65 double compute_delay_ms(int attempt, const RetryConfig& cfg);
66 // A 4xx the caller caused (bad request, auth, too long): not 408 or 429.
67 inline bool is_client_error(int code) {
68 return code >= 400 && code < 500 && code != 408 && code != 429;
69 }
70} // namespace detail
71
72// ─── with_retry ──────────────────────────────────────────────────────────────
73
74template<typename T>
75RetryResult<T> with_retry(
76 std::function<T()> fn,
77 const RetryConfig& config = {}
78) {
79 using clock = std::chrono::steady_clock;
80 auto start = clock::now();
81
82 std::mt19937 rng(std::random_device{}());
83
84 for (int attempt = 1; attempt <= config.max_attempts; ++attempt) {
85 try {
86 T result = fn();
87 double elapsed = std::chrono::duration<double, std::milli>(
88 clock::now() - start).count();
89 return RetryResult<T>{std::move(result), attempt, elapsed, false};
90 } catch (const LLMError& err) {
91 bool last = (attempt == config.max_attempts);
92 bool retryable = err.is_retryable &&
93 detail::is_retryable_code(err.http_code, config.retry_on_http_codes);
94 if (last || !retryable) throw;
95
96 double delay = detail::compute_delay_ms(attempt, config);
97 if (err.retry_after_seconds >= 0.0) {
98 // The server said when to come back: obey it, plus a random
99 // spread so every client does not return on the same second.
100 std::uniform_real_distribution<double> spread(0.0, delay);
101 delay = err.retry_after_seconds * 1000.0 + spread(rng);
102 } else {
103 std::uniform_real_distribution<double> jitter_dist(
104 1.0 - config.jitter_factor, 1.0 + config.jitter_factor);
105 delay *= jitter_dist(rng);
106 }
107 std::this_thread::sleep_for(
108 std::chrono::duration<double, std::milli>(delay));
109 }
110 // Any other exception came from the caller's own code (a JSON parse,
111 // a logic error). Retrying a bug only delays it, so it propagates
112 // immediately. Report transient network failures as LLMError{0, ...}.
113 }
114 throw LLMError{0, "with_retry: exhausted all attempts", false};
115}
116
117// ─── with_failover ───────────────────────────────────────────────────────────
118
119template<typename T>
120RetryResult<T> with_failover(
121 std::function<T()> primary,
122 std::function<T()> fallback,
123 const RetryConfig& config = {}
124) {
125 try {
126 return with_retry<T>(primary, config);
127 } catch (const LLMError& err) {
128 // A 4xx other than 408/429 means the request itself is broken; the
129 // fallback model would hide the bug behind a quality drop. Surface it.
130 if (detail::is_client_error(err.http_code)) throw;
131 using clock = std::chrono::steady_clock;
132 auto start = clock::now();
133 T result = fallback();
134 double elapsed = std::chrono::duration<double, std::milli>(
135 clock::now() - start).count();
136 return RetryResult<T>{std::move(result), 1, elapsed, true};
137 } catch (...) {
138 // Not an HTTP error (e.g. CircuitBreaker open): fail over.
139 using clock = std::chrono::steady_clock;
140 auto start = clock::now();
141 T result = fallback();
142 double elapsed = std::chrono::duration<double, std::milli>(
143 clock::now() - start).count();
144 return RetryResult<T>{std::move(result), 1, elapsed, true};
145 }
146}
147
148// ─── CircuitBreaker ──────────────────────────────────────────────────────────
149
151public:
152 struct Stats {
153 CircuitState state;
154 int consecutive_failures;
155 double failure_rate;
156 std::time_t last_failure;
157 std::time_t last_success;
158 };
159
160 explicit CircuitBreaker(std::string name, CircuitBreakerConfig config = {})
161 : name_(std::move(name)), config_(config) {}
162
163 // After the cool-down the circuit goes HalfOpen and admits exactly ONE
164 // trial call; concurrent callers fail fast until it finishes. Its success
165 // closes the circuit and clears the counters, its failure reopens it.
166 template<typename T>
167 T call(std::function<T()> fn) {
168 bool trial = false;
169 {
170 std::lock_guard<std::mutex> lk(mutex_);
171 if (state_ == CircuitState::Open) {
172 auto now = std::chrono::steady_clock::now();
173 double secs = std::chrono::duration<double>(
174 now - last_failure_time_).count();
175 if (secs >= config_.timeout_seconds) {
176 state_ = CircuitState::HalfOpen;
177 } else {
178 throw std::runtime_error(
179 "CircuitBreaker[" + name_ + "]: circuit is Open");
180 }
181 }
182 if (state_ == CircuitState::HalfOpen) {
183 if (trial_in_flight_) {
184 throw std::runtime_error(
185 "CircuitBreaker[" + name_ + "]: circuit is HalfOpen, trial in flight");
186 }
187 trial_in_flight_ = trial = true;
188 }
189 }
190
191 try {
192 T result = fn();
193 record_success(trial);
194 return result;
195 } catch (...) {
196 record_failure(trial);
197 throw;
198 }
199 }
200
201 CircuitState state() const {
202 std::lock_guard<std::mutex> lk(mutex_);
203 return state_;
204 }
205
206 Stats stats() const {
207 std::lock_guard<std::mutex> lk(mutex_);
208 double rate = (total_calls_ == 0) ? 0.0 :
209 static_cast<double>(failure_calls_) / total_calls_;
210 return Stats{
211 state_,
212 consecutive_failures_,
213 rate,
214 last_failure_ts_,
215 last_success_ts_
216 };
217 }
218
219 void reset() {
220 std::lock_guard<std::mutex> lk(mutex_);
221 state_ = CircuitState::Closed;
222 consecutive_failures_ = 0;
223 total_calls_ = 0;
224 failure_calls_ = 0;
225 trial_in_flight_ = false;
226 }
227
228private:
229 void record_success(bool trial) {
230 std::lock_guard<std::mutex> lk(mutex_);
231 ++total_calls_;
232 consecutive_failures_ = 0;
233 last_success_ts_ = std::time(nullptr);
234 if (trial) {
235 // The half-open trial worked: the provider is back.
236 state_ = CircuitState::Closed;
237 trial_in_flight_ = false;
238 failure_calls_ = 0;
239 total_calls_ = 0;
240 }
241 }
242
243 void record_failure(bool trial) {
244 std::lock_guard<std::mutex> lk(mutex_);
245 ++total_calls_;
246 ++failure_calls_;
247 ++consecutive_failures_;
248 last_failure_ts_ = std::time(nullptr);
249 last_failure_time_ = std::chrono::steady_clock::now();
250 if (trial || consecutive_failures_ >= config_.failure_threshold) {
251 state_ = CircuitState::Open;
252 trial_in_flight_ = false;
253 }
254 }
255
256 std::string name_;
257 CircuitBreakerConfig config_;
258 mutable std::mutex mutex_;
259 CircuitState state_ = CircuitState::Closed;
260 int consecutive_failures_ = 0;
261 int total_calls_ = 0;
262 int failure_calls_ = 0;
263 bool trial_in_flight_ = false;
264 std::time_t last_failure_ts_ = 0;
265 std::time_t last_success_ts_ = 0;
266 std::chrono::steady_clock::time_point last_failure_time_;
267};
268
269} // namespace llm
270
271// ─── Implementation ──────────────────────────────────────────────────────────
272
273#ifdef LLM_RETRY_IMPLEMENTATION
274
275namespace llm {
276
277int parse_http_code(const std::string& header) {
278 // Expects "HTTP/1.1 429 Too Many Requests" style
279 auto pos = header.find("HTTP/");
280 if (pos == std::string::npos) return 0;
281 auto space = header.find(' ', pos);
282 if (space == std::string::npos) return 0;
283 try { return std::stoi(header.substr(space + 1, 3)); }
284 catch (...) { return 0; }
285}
286
287namespace detail {
288
289bool is_retryable_code(int code, const std::vector<int>& codes) {
290 if (code == 0) return true; // network error, always retry
291 for (int c : codes) if (c == code) return true;
292 return false;
293}
294
295double compute_delay_ms(int attempt, const RetryConfig& cfg) {
296 double delay = cfg.base_delay_ms;
297 for (int i = 1; i < attempt; ++i) delay *= cfg.backoff_multiplier;
298 if (delay > cfg.max_delay_ms) delay = cfg.max_delay_ms;
299 return delay;
300}
301
302} // namespace detail
303} // namespace llm
304
305#endif // LLM_RETRY_IMPLEMENTATION
Definition: llm_retry.hpp:150
detail namespace with internal helper functions
Definition: json.hpp:249
Definition: llm_retry.hpp:31
Definition: llm_retry.hpp:152
Definition: llm_retry.hpp:49
Definition: llm_retry.hpp:20
Definition: llm_retry.hpp:42