liter_llm 1.0.0.pre.rc.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/README.md +239 -0
- data/ext/liter_llm_rb/extconf.rb +65 -0
- data/ext/liter_llm_rb/native/.cargo/config.toml +23 -0
- data/ext/liter_llm_rb/native/Cargo.lock +3713 -0
- data/ext/liter_llm_rb/native/Cargo.toml +32 -0
- data/ext/liter_llm_rb/native/build.rs +15 -0
- data/ext/liter_llm_rb/native/src/lib.rs +1079 -0
- data/lib/liter_llm.rb +8 -0
- data/sig/liter_llm.rbs +416 -0
- data/vendor/Cargo.toml +54 -0
- data/vendor/liter-llm/Cargo.toml +92 -0
- data/vendor/liter-llm/README.md +252 -0
- data/vendor/liter-llm/schemas/pricing.json +40 -0
- data/vendor/liter-llm/schemas/providers.json +1662 -0
- data/vendor/liter-llm/src/auth/azure_ad.rs +264 -0
- data/vendor/liter-llm/src/auth/bedrock_sts.rs +353 -0
- data/vendor/liter-llm/src/auth/mod.rs +68 -0
- data/vendor/liter-llm/src/auth/vertex_oauth.rs +353 -0
- data/vendor/liter-llm/src/client/config.rs +351 -0
- data/vendor/liter-llm/src/client/managed.rs +622 -0
- data/vendor/liter-llm/src/client/mod.rs +864 -0
- data/vendor/liter-llm/src/cost.rs +212 -0
- data/vendor/liter-llm/src/error.rs +190 -0
- data/vendor/liter-llm/src/http/eventstream.rs +860 -0
- data/vendor/liter-llm/src/http/mod.rs +12 -0
- data/vendor/liter-llm/src/http/request.rs +438 -0
- data/vendor/liter-llm/src/http/retry.rs +72 -0
- data/vendor/liter-llm/src/http/streaming.rs +289 -0
- data/vendor/liter-llm/src/lib.rs +37 -0
- data/vendor/liter-llm/src/provider/anthropic.rs +2250 -0
- data/vendor/liter-llm/src/provider/azure.rs +579 -0
- data/vendor/liter-llm/src/provider/bedrock.rs +1543 -0
- data/vendor/liter-llm/src/provider/cohere.rs +654 -0
- data/vendor/liter-llm/src/provider/custom.rs +404 -0
- data/vendor/liter-llm/src/provider/google_ai.rs +281 -0
- data/vendor/liter-llm/src/provider/mistral.rs +188 -0
- data/vendor/liter-llm/src/provider/mod.rs +616 -0
- data/vendor/liter-llm/src/provider/vertex.rs +1504 -0
- data/vendor/liter-llm/src/tests.rs +1425 -0
- data/vendor/liter-llm/src/tokenizer.rs +281 -0
- data/vendor/liter-llm/src/tower/budget.rs +599 -0
- data/vendor/liter-llm/src/tower/cache.rs +502 -0
- data/vendor/liter-llm/src/tower/cache_opendal.rs +270 -0
- data/vendor/liter-llm/src/tower/cooldown.rs +231 -0
- data/vendor/liter-llm/src/tower/cost.rs +404 -0
- data/vendor/liter-llm/src/tower/fallback.rs +121 -0
- data/vendor/liter-llm/src/tower/health.rs +219 -0
- data/vendor/liter-llm/src/tower/hooks.rs +369 -0
- data/vendor/liter-llm/src/tower/mod.rs +77 -0
- data/vendor/liter-llm/src/tower/rate_limit.rs +300 -0
- data/vendor/liter-llm/src/tower/router.rs +436 -0
- data/vendor/liter-llm/src/tower/service.rs +181 -0
- data/vendor/liter-llm/src/tower/tests.rs +539 -0
- data/vendor/liter-llm/src/tower/tests_common.rs +252 -0
- data/vendor/liter-llm/src/tower/tracing.rs +209 -0
- data/vendor/liter-llm/src/tower/types.rs +170 -0
- data/vendor/liter-llm/src/types/audio.rs +52 -0
- data/vendor/liter-llm/src/types/batch.rs +77 -0
- data/vendor/liter-llm/src/types/chat.rs +214 -0
- data/vendor/liter-llm/src/types/common.rs +244 -0
- data/vendor/liter-llm/src/types/embedding.rs +84 -0
- data/vendor/liter-llm/src/types/files.rs +58 -0
- data/vendor/liter-llm/src/types/image.rs +40 -0
- data/vendor/liter-llm/src/types/mod.rs +27 -0
- data/vendor/liter-llm/src/types/models.rs +21 -0
- data/vendor/liter-llm/src/types/moderation.rs +80 -0
- data/vendor/liter-llm/src/types/ocr.rs +87 -0
- data/vendor/liter-llm/src/types/rerank.rs +46 -0
- data/vendor/liter-llm/src/types/responses.rs +55 -0
- data/vendor/liter-llm/src/types/search.rs +45 -0
- data/vendor/liter-llm/tests/contract.rs +332 -0
- data/vendor/liter-llm-ffi/Cargo.toml +30 -0
- data/vendor/liter-llm-ffi/build.rs +66 -0
- data/vendor/liter-llm-ffi/cbindgen.toml +60 -0
- data/vendor/liter-llm-ffi/liter_llm.h +850 -0
- data/vendor/liter-llm-ffi/src/lib.rs +2488 -0
- metadata +286 -0
|
@@ -0,0 +1,599 @@
|
|
|
1
|
+
//! Budget enforcement middleware.
|
|
2
|
+
//!
|
|
3
|
+
//! [`BudgetLayer`] wraps any [`Service<LlmRequest>`] and enforces spending
|
|
4
|
+
//! limits (global and per-model) in USD. Cost is calculated after each
|
|
5
|
+
//! successful response using [`crate::cost::completion_cost`] and accumulated
|
|
6
|
+
//! atomically in [`BudgetState`].
|
|
7
|
+
//!
|
|
8
|
+
//! Two enforcement modes are supported:
|
|
9
|
+
//!
|
|
10
|
+
//! - **Hard** — pre-request check rejects with [`LiterLlmError::BudgetExceeded`]
|
|
11
|
+
//! when the accumulated spend is at or above the configured limit. Note that
|
|
12
|
+
//! hard enforcement is **best-effort** under concurrent load: because cost is
|
|
13
|
+
//! recorded after the response, concurrent in-flight requests may collectively
|
|
14
|
+
//! overshoot the limit. See [`check_budget`] for details.
|
|
15
|
+
//! - **Soft** — requests are never rejected; a `tracing::warn!` is emitted when
|
|
16
|
+
//! the limit is exceeded.
|
|
17
|
+
//!
|
|
18
|
+
//! # Example
|
|
19
|
+
//!
|
|
20
|
+
//! ```rust,ignore
|
|
21
|
+
//! use liter_llm::tower::{BudgetConfig, BudgetLayer, BudgetState, Enforcement, LlmService};
|
|
22
|
+
//! use tower::ServiceBuilder;
|
|
23
|
+
//! use std::sync::Arc;
|
|
24
|
+
//!
|
|
25
|
+
//! let state = Arc::new(BudgetState::new());
|
|
26
|
+
//! let config = BudgetConfig {
|
|
27
|
+
//! global_limit: Some(10.0),
|
|
28
|
+
//! model_limits: Default::default(),
|
|
29
|
+
//! enforcement: Enforcement::Hard,
|
|
30
|
+
//! };
|
|
31
|
+
//!
|
|
32
|
+
//! let client = liter_llm::DefaultClient::new(cfg, None)?;
|
|
33
|
+
//! let service = ServiceBuilder::new()
|
|
34
|
+
//! .layer(BudgetLayer::new(config, Arc::clone(&state)))
|
|
35
|
+
//! .service(LlmService::new(client));
|
|
36
|
+
//! ```
|
|
37
|
+
|
|
38
|
+
use std::collections::HashMap;
|
|
39
|
+
use std::sync::Arc;
|
|
40
|
+
use std::sync::atomic::{AtomicU64, Ordering};
|
|
41
|
+
use std::task::{Context, Poll};
|
|
42
|
+
|
|
43
|
+
use dashmap::DashMap;
|
|
44
|
+
use tower::{Layer, Service};
|
|
45
|
+
|
|
46
|
+
use super::types::{LlmRequest, LlmResponse};
|
|
47
|
+
use crate::client::BoxFuture;
|
|
48
|
+
use crate::cost;
|
|
49
|
+
use crate::error::{LiterLlmError, Result};
|
|
50
|
+
|
|
51
|
+
// ---- Types -----------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
/// How budget limits are enforced.
|
|
54
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
55
|
+
pub enum Enforcement {
|
|
56
|
+
/// Reject requests that would exceed the budget with
|
|
57
|
+
/// [`LiterLlmError::BudgetExceeded`].
|
|
58
|
+
Hard,
|
|
59
|
+
/// Allow requests through but emit a `tracing::warn!` when the budget is
|
|
60
|
+
/// exceeded.
|
|
61
|
+
Soft,
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// ---- Config ----------------------------------------------------------------
|
|
65
|
+
|
|
66
|
+
/// Configuration for budget enforcement.
|
|
67
|
+
#[derive(Debug, Clone)]
|
|
68
|
+
pub struct BudgetConfig {
|
|
69
|
+
/// Maximum total spend across all models, in USD. `None` means unlimited.
|
|
70
|
+
pub global_limit: Option<f64>,
|
|
71
|
+
/// Per-model spending limits in USD. Models not listed here are only
|
|
72
|
+
/// constrained by `global_limit`.
|
|
73
|
+
pub model_limits: HashMap<String, f64>,
|
|
74
|
+
/// Whether to reject requests or merely warn when a limit is exceeded.
|
|
75
|
+
pub enforcement: Enforcement,
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
impl Default for BudgetConfig {
|
|
79
|
+
fn default() -> Self {
|
|
80
|
+
Self {
|
|
81
|
+
global_limit: None,
|
|
82
|
+
model_limits: HashMap::new(),
|
|
83
|
+
enforcement: Enforcement::Hard,
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ---- State -----------------------------------------------------------------
|
|
89
|
+
|
|
90
|
+
/// Shared, thread-safe budget accumulator.
|
|
91
|
+
///
|
|
92
|
+
/// All values are stored in **microcents** (USD * 1_000_000) as `AtomicU64` to
|
|
93
|
+
/// avoid floating-point atomics while retaining sub-cent precision.
|
|
94
|
+
#[derive(Debug)]
|
|
95
|
+
pub struct BudgetState {
|
|
96
|
+
/// Total spend across all models (microcents).
|
|
97
|
+
global_spend: AtomicU64,
|
|
98
|
+
/// Per-model spend (microcents).
|
|
99
|
+
model_spend: DashMap<String, AtomicU64>,
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
impl BudgetState {
|
|
103
|
+
/// Create a new, zeroed budget state.
|
|
104
|
+
#[must_use]
|
|
105
|
+
pub fn new() -> Self {
|
|
106
|
+
Self {
|
|
107
|
+
global_spend: AtomicU64::new(0),
|
|
108
|
+
model_spend: DashMap::new(),
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/// Return the total global spend in USD.
|
|
113
|
+
#[must_use]
|
|
114
|
+
pub fn global_spend(&self) -> f64 {
|
|
115
|
+
microcents_to_usd(self.global_spend.load(Ordering::Relaxed))
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/// Return the spend for a specific model in USD, or `0.0` if the model has
|
|
119
|
+
/// not been seen.
|
|
120
|
+
#[must_use]
|
|
121
|
+
pub fn model_spend(&self, model: &str) -> f64 {
|
|
122
|
+
self.model_spend
|
|
123
|
+
.get(model)
|
|
124
|
+
.map(|v| microcents_to_usd(v.load(Ordering::Relaxed)))
|
|
125
|
+
.unwrap_or(0.0)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/// Reset all counters to zero.
|
|
129
|
+
pub fn reset(&self) {
|
|
130
|
+
self.global_spend.store(0, Ordering::Relaxed);
|
|
131
|
+
self.model_spend.clear();
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/// Add `usd` to the global and per-model counters.
|
|
135
|
+
fn record(&self, model: &str, usd: f64) {
|
|
136
|
+
let mc = usd_to_microcents(usd);
|
|
137
|
+
self.global_spend.fetch_add(mc, Ordering::Relaxed);
|
|
138
|
+
self.model_spend
|
|
139
|
+
.entry(model.to_owned())
|
|
140
|
+
.or_insert_with(|| AtomicU64::new(0))
|
|
141
|
+
.fetch_add(mc, Ordering::Relaxed);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
impl Default for BudgetState {
|
|
146
|
+
fn default() -> Self {
|
|
147
|
+
Self::new()
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// ---- Conversions -----------------------------------------------------------
|
|
152
|
+
|
|
153
|
+
fn usd_to_microcents(usd: f64) -> u64 {
|
|
154
|
+
// Clamp negative values to zero to avoid wrapping in unsigned arithmetic.
|
|
155
|
+
if usd <= 0.0 {
|
|
156
|
+
return 0;
|
|
157
|
+
}
|
|
158
|
+
(usd * 1_000_000.0).round() as u64
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
fn microcents_to_usd(mc: u64) -> f64 {
|
|
162
|
+
mc as f64 / 1_000_000.0
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// ---- Layer -----------------------------------------------------------------
|
|
166
|
+
|
|
167
|
+
/// Tower [`Layer`] that enforces spending budgets.
|
|
168
|
+
pub struct BudgetLayer {
|
|
169
|
+
config: BudgetConfig,
|
|
170
|
+
state: Arc<BudgetState>,
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
impl BudgetLayer {
|
|
174
|
+
/// Create a new budget layer with the given configuration and shared state.
|
|
175
|
+
///
|
|
176
|
+
/// The caller retains an `Arc<BudgetState>` for runtime introspection
|
|
177
|
+
/// (e.g. dashboard queries, manual resets).
|
|
178
|
+
#[must_use]
|
|
179
|
+
pub fn new(config: BudgetConfig, state: Arc<BudgetState>) -> Self {
|
|
180
|
+
Self { config, state }
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
impl<S> Layer<S> for BudgetLayer {
|
|
185
|
+
type Service = BudgetService<S>;
|
|
186
|
+
|
|
187
|
+
fn layer(&self, inner: S) -> Self::Service {
|
|
188
|
+
BudgetService {
|
|
189
|
+
inner,
|
|
190
|
+
config: self.config.clone(),
|
|
191
|
+
state: Arc::clone(&self.state),
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ---- Service ---------------------------------------------------------------
|
|
197
|
+
|
|
198
|
+
/// Tower service produced by [`BudgetLayer`].
|
|
199
|
+
pub struct BudgetService<S> {
|
|
200
|
+
inner: S,
|
|
201
|
+
config: BudgetConfig,
|
|
202
|
+
state: Arc<BudgetState>,
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
impl<S: Clone> Clone for BudgetService<S> {
|
|
206
|
+
fn clone(&self) -> Self {
|
|
207
|
+
Self {
|
|
208
|
+
inner: self.inner.clone(),
|
|
209
|
+
config: self.config.clone(),
|
|
210
|
+
state: Arc::clone(&self.state),
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
impl<S> Service<LlmRequest> for BudgetService<S>
|
|
216
|
+
where
|
|
217
|
+
S: Service<LlmRequest, Response = LlmResponse, Error = LiterLlmError> + Send + 'static,
|
|
218
|
+
S::Future: Send + 'static,
|
|
219
|
+
{
|
|
220
|
+
type Response = LlmResponse;
|
|
221
|
+
type Error = LiterLlmError;
|
|
222
|
+
type Future = BoxFuture<'static, LlmResponse>;
|
|
223
|
+
|
|
224
|
+
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<()>> {
|
|
225
|
+
self.inner.poll_ready(cx)
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
fn call(&mut self, req: LlmRequest) -> Self::Future {
|
|
229
|
+
let model = req.model().unwrap_or("unknown").to_owned();
|
|
230
|
+
let config = self.config.clone();
|
|
231
|
+
let state = Arc::clone(&self.state);
|
|
232
|
+
|
|
233
|
+
// --- Pre-flight: hard enforcement check ---
|
|
234
|
+
if config.enforcement == Enforcement::Hard
|
|
235
|
+
&& let Some(err) = check_budget(&config, &state, &model)
|
|
236
|
+
{
|
|
237
|
+
return Box::pin(async move { Err(err) });
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
let fut = self.inner.call(req);
|
|
241
|
+
|
|
242
|
+
Box::pin(async move {
|
|
243
|
+
let resp = fut.await?;
|
|
244
|
+
|
|
245
|
+
// --- Post-flight: record cost ---
|
|
246
|
+
if let Some(usage) = resp.usage()
|
|
247
|
+
&& let Some(usd) = cost::completion_cost(&model, usage.prompt_tokens, usage.completion_tokens)
|
|
248
|
+
{
|
|
249
|
+
state.record(&model, usd);
|
|
250
|
+
|
|
251
|
+
// Soft enforcement: warn after recording.
|
|
252
|
+
if config.enforcement == Enforcement::Soft {
|
|
253
|
+
emit_soft_warnings(&config, &state, &model);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
Ok(resp)
|
|
258
|
+
})
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// ---- Helpers ---------------------------------------------------------------
|
|
263
|
+
|
|
264
|
+
/// Check whether the current spend exceeds any configured limit. Returns
|
|
265
|
+
/// `Some(LiterLlmError)` if the budget is exceeded under hard enforcement.
|
|
266
|
+
///
|
|
267
|
+
/// **Concurrency note:** This check is best-effort under concurrent load.
|
|
268
|
+
/// Because the budget is checked (read) before the request and recorded
|
|
269
|
+
/// (write) after the response, concurrent requests may all pass the
|
|
270
|
+
/// pre-flight check before any of them record their cost. This means
|
|
271
|
+
/// hard enforcement can slightly overshoot the configured limit by up to
|
|
272
|
+
/// `N * max_single_request_cost` where `N` is the number of concurrent
|
|
273
|
+
/// in-flight requests. For strict dollar-accurate enforcement, use an
|
|
274
|
+
/// external budget service with transactional semantics.
|
|
275
|
+
fn check_budget(config: &BudgetConfig, state: &BudgetState, model: &str) -> Option<LiterLlmError> {
|
|
276
|
+
// Global limit check.
|
|
277
|
+
if let Some(limit) = config.global_limit
|
|
278
|
+
&& state.global_spend() >= limit
|
|
279
|
+
{
|
|
280
|
+
return Some(LiterLlmError::BudgetExceeded {
|
|
281
|
+
message: format!(
|
|
282
|
+
"global budget exceeded: spent ${:.6}, limit ${:.6}",
|
|
283
|
+
state.global_spend(),
|
|
284
|
+
limit,
|
|
285
|
+
),
|
|
286
|
+
model: None,
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// Per-model limit check.
|
|
291
|
+
if let Some(&limit) = config.model_limits.get(model)
|
|
292
|
+
&& state.model_spend(model) >= limit
|
|
293
|
+
{
|
|
294
|
+
return Some(LiterLlmError::BudgetExceeded {
|
|
295
|
+
message: format!(
|
|
296
|
+
"model {model} budget exceeded: spent ${:.6}, limit ${:.6}",
|
|
297
|
+
state.model_spend(model),
|
|
298
|
+
limit,
|
|
299
|
+
),
|
|
300
|
+
model: Some(model.to_owned()),
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
None
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/// Emit `tracing::warn!` messages for any exceeded limits (soft mode).
|
|
308
|
+
fn emit_soft_warnings(config: &BudgetConfig, state: &BudgetState, model: &str) {
|
|
309
|
+
if let Some(limit) = config.global_limit
|
|
310
|
+
&& state.global_spend() >= limit
|
|
311
|
+
{
|
|
312
|
+
tracing::warn!(
|
|
313
|
+
spend = state.global_spend(),
|
|
314
|
+
limit,
|
|
315
|
+
"global budget exceeded (soft enforcement)"
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
if let Some(&limit) = config.model_limits.get(model)
|
|
320
|
+
&& state.model_spend(model) >= limit
|
|
321
|
+
{
|
|
322
|
+
tracing::warn!(
|
|
323
|
+
model,
|
|
324
|
+
spend = state.model_spend(model),
|
|
325
|
+
limit,
|
|
326
|
+
"model budget exceeded (soft enforcement)"
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// ---- Tests -----------------------------------------------------------------
|
|
332
|
+
|
|
333
|
+
#[cfg(test)]
|
|
334
|
+
mod tests {
|
|
335
|
+
use std::collections::HashMap;
|
|
336
|
+
use std::sync::Arc;
|
|
337
|
+
|
|
338
|
+
use tower::{Layer as _, Service as _};
|
|
339
|
+
|
|
340
|
+
use super::*;
|
|
341
|
+
use crate::tower::service::LlmService;
|
|
342
|
+
use crate::tower::tests_common::{MockClient, chat_req};
|
|
343
|
+
use crate::tower::types::LlmRequest;
|
|
344
|
+
|
|
345
|
+
/// Helper: build a budget layer + service with the given config.
|
|
346
|
+
fn build_service(config: BudgetConfig, state: Arc<BudgetState>) -> BudgetService<LlmService<MockClient>> {
|
|
347
|
+
let layer = BudgetLayer::new(config, state);
|
|
348
|
+
let inner = LlmService::new(MockClient::ok());
|
|
349
|
+
layer.layer(inner)
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// ── Hard enforcement ────────────────────────────────────────────────────
|
|
353
|
+
|
|
354
|
+
#[tokio::test]
|
|
355
|
+
async fn hard_enforcement_rejects_when_global_limit_exceeded() {
|
|
356
|
+
let state = Arc::new(BudgetState::new());
|
|
357
|
+
// Pre-seed spend above the limit.
|
|
358
|
+
state.global_spend.store(usd_to_microcents(10.0), Ordering::Relaxed);
|
|
359
|
+
|
|
360
|
+
let config = BudgetConfig {
|
|
361
|
+
global_limit: Some(5.0),
|
|
362
|
+
enforcement: Enforcement::Hard,
|
|
363
|
+
..Default::default()
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
let mut svc = build_service(config, state);
|
|
367
|
+
let err = svc
|
|
368
|
+
.call(LlmRequest::Chat(chat_req("gpt-4")))
|
|
369
|
+
.await
|
|
370
|
+
.expect_err("should reject over-budget request");
|
|
371
|
+
assert!(matches!(err, LiterLlmError::BudgetExceeded { .. }));
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
#[tokio::test]
|
|
375
|
+
async fn hard_enforcement_rejects_when_model_limit_exceeded() {
|
|
376
|
+
let state = Arc::new(BudgetState::new());
|
|
377
|
+
// Pre-seed per-model spend above the model limit.
|
|
378
|
+
state
|
|
379
|
+
.model_spend
|
|
380
|
+
.entry("gpt-4".to_owned())
|
|
381
|
+
.or_insert_with(|| AtomicU64::new(0))
|
|
382
|
+
.store(usd_to_microcents(2.0), Ordering::Relaxed);
|
|
383
|
+
|
|
384
|
+
let mut limits = HashMap::new();
|
|
385
|
+
limits.insert("gpt-4".into(), 1.0);
|
|
386
|
+
|
|
387
|
+
let config = BudgetConfig {
|
|
388
|
+
global_limit: None,
|
|
389
|
+
model_limits: limits,
|
|
390
|
+
enforcement: Enforcement::Hard,
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
let mut svc = build_service(config, state);
|
|
394
|
+
let err = svc
|
|
395
|
+
.call(LlmRequest::Chat(chat_req("gpt-4")))
|
|
396
|
+
.await
|
|
397
|
+
.expect_err("should reject over-budget model request");
|
|
398
|
+
|
|
399
|
+
match &err {
|
|
400
|
+
LiterLlmError::BudgetExceeded { model, .. } => {
|
|
401
|
+
assert_eq!(model.as_deref(), Some("gpt-4"));
|
|
402
|
+
}
|
|
403
|
+
other => panic!("expected BudgetExceeded, got {other:?}"),
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
#[tokio::test]
|
|
408
|
+
async fn hard_enforcement_allows_requests_under_limit() {
|
|
409
|
+
let state = Arc::new(BudgetState::new());
|
|
410
|
+
let config = BudgetConfig {
|
|
411
|
+
global_limit: Some(100.0),
|
|
412
|
+
enforcement: Enforcement::Hard,
|
|
413
|
+
..Default::default()
|
|
414
|
+
};
|
|
415
|
+
|
|
416
|
+
let mut svc = build_service(config, state);
|
|
417
|
+
let resp = svc.call(LlmRequest::Chat(chat_req("gpt-4"))).await;
|
|
418
|
+
assert!(resp.is_ok(), "request under budget should succeed");
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// ── Soft enforcement ────────────────────────────────────────────────────
|
|
422
|
+
|
|
423
|
+
#[tokio::test]
|
|
424
|
+
async fn soft_enforcement_allows_requests_over_global_limit() {
|
|
425
|
+
let state = Arc::new(BudgetState::new());
|
|
426
|
+
state.global_spend.store(usd_to_microcents(100.0), Ordering::Relaxed);
|
|
427
|
+
|
|
428
|
+
let config = BudgetConfig {
|
|
429
|
+
global_limit: Some(5.0),
|
|
430
|
+
enforcement: Enforcement::Soft,
|
|
431
|
+
..Default::default()
|
|
432
|
+
};
|
|
433
|
+
|
|
434
|
+
let mut svc = build_service(config, state);
|
|
435
|
+
let resp = svc.call(LlmRequest::Chat(chat_req("gpt-4"))).await;
|
|
436
|
+
assert!(resp.is_ok(), "soft mode should never reject");
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
#[tokio::test]
|
|
440
|
+
async fn soft_enforcement_allows_requests_over_model_limit() {
|
|
441
|
+
let state = Arc::new(BudgetState::new());
|
|
442
|
+
state
|
|
443
|
+
.model_spend
|
|
444
|
+
.entry("gpt-4".to_owned())
|
|
445
|
+
.or_insert_with(|| AtomicU64::new(0))
|
|
446
|
+
.store(usd_to_microcents(10.0), Ordering::Relaxed);
|
|
447
|
+
|
|
448
|
+
let mut limits = HashMap::new();
|
|
449
|
+
limits.insert("gpt-4".into(), 1.0);
|
|
450
|
+
|
|
451
|
+
let config = BudgetConfig {
|
|
452
|
+
global_limit: None,
|
|
453
|
+
model_limits: limits,
|
|
454
|
+
enforcement: Enforcement::Soft,
|
|
455
|
+
};
|
|
456
|
+
|
|
457
|
+
let mut svc = build_service(config, state);
|
|
458
|
+
let resp = svc.call(LlmRequest::Chat(chat_req("gpt-4"))).await;
|
|
459
|
+
assert!(resp.is_ok(), "soft mode should never reject");
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// ── Cost accumulation ───────────────────────────────────────────────────
|
|
463
|
+
|
|
464
|
+
#[tokio::test]
|
|
465
|
+
async fn accumulates_cost_after_response() {
|
|
466
|
+
let state = Arc::new(BudgetState::new());
|
|
467
|
+
let config = BudgetConfig {
|
|
468
|
+
global_limit: Some(100.0),
|
|
469
|
+
enforcement: Enforcement::Hard,
|
|
470
|
+
..Default::default()
|
|
471
|
+
};
|
|
472
|
+
|
|
473
|
+
let mut svc = build_service(config, Arc::clone(&state));
|
|
474
|
+
// MockClient returns usage: prompt=10, completion=5 for the model.
|
|
475
|
+
svc.call(LlmRequest::Chat(chat_req("gpt-4"))).await.unwrap();
|
|
476
|
+
|
|
477
|
+
// gpt-4 pricing: input=0.00003/token, output=0.00006/token
|
|
478
|
+
// 10 * 0.00003 + 5 * 0.00006 = 0.0003 + 0.0003 = 0.0006
|
|
479
|
+
assert!(state.global_spend() > 0.0, "global spend should be recorded");
|
|
480
|
+
assert!(state.model_spend("gpt-4") > 0.0, "model spend should be recorded");
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// ── Per-model limits (independent) ──────────────────────────────────────
|
|
484
|
+
|
|
485
|
+
#[tokio::test]
|
|
486
|
+
async fn per_model_limits_are_independent() {
|
|
487
|
+
let state = Arc::new(BudgetState::new());
|
|
488
|
+
// Set gpt-4 over its limit, but gpt-3.5-turbo has no model limit.
|
|
489
|
+
state
|
|
490
|
+
.model_spend
|
|
491
|
+
.entry("gpt-4".to_owned())
|
|
492
|
+
.or_insert_with(|| AtomicU64::new(0))
|
|
493
|
+
.store(usd_to_microcents(5.0), Ordering::Relaxed);
|
|
494
|
+
|
|
495
|
+
let mut limits = HashMap::new();
|
|
496
|
+
limits.insert("gpt-4".into(), 1.0);
|
|
497
|
+
|
|
498
|
+
let config = BudgetConfig {
|
|
499
|
+
global_limit: None,
|
|
500
|
+
model_limits: limits,
|
|
501
|
+
enforcement: Enforcement::Hard,
|
|
502
|
+
};
|
|
503
|
+
|
|
504
|
+
let mut svc = build_service(config, state);
|
|
505
|
+
|
|
506
|
+
// gpt-4 should be rejected.
|
|
507
|
+
let err = svc.call(LlmRequest::Chat(chat_req("gpt-4"))).await;
|
|
508
|
+
assert!(err.is_err(), "gpt-4 should be rejected");
|
|
509
|
+
|
|
510
|
+
// gpt-3.5-turbo has no per-model limit, should succeed.
|
|
511
|
+
let ok = svc.call(LlmRequest::Chat(chat_req("gpt-3.5-turbo"))).await;
|
|
512
|
+
assert!(ok.is_ok(), "gpt-3.5-turbo should not be limited");
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// ── Reset ───────────────────────────────────────────────────────────────
|
|
516
|
+
|
|
517
|
+
#[tokio::test]
|
|
518
|
+
async fn reset_clears_all_counters() {
|
|
519
|
+
let state = Arc::new(BudgetState::new());
|
|
520
|
+
state.global_spend.store(usd_to_microcents(50.0), Ordering::Relaxed);
|
|
521
|
+
state
|
|
522
|
+
.model_spend
|
|
523
|
+
.entry("gpt-4".to_owned())
|
|
524
|
+
.or_insert_with(|| AtomicU64::new(0))
|
|
525
|
+
.store(usd_to_microcents(25.0), Ordering::Relaxed);
|
|
526
|
+
|
|
527
|
+
assert!(state.global_spend() > 0.0);
|
|
528
|
+
assert!(state.model_spend("gpt-4") > 0.0);
|
|
529
|
+
|
|
530
|
+
state.reset();
|
|
531
|
+
|
|
532
|
+
assert_eq!(state.global_spend(), 0.0, "global spend should be zero after reset");
|
|
533
|
+
assert_eq!(
|
|
534
|
+
state.model_spend("gpt-4"),
|
|
535
|
+
0.0,
|
|
536
|
+
"model spend should be zero after reset"
|
|
537
|
+
);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
// ── Reset then allow ────────────────────────────────────────────────────
|
|
541
|
+
|
|
542
|
+
#[tokio::test]
|
|
543
|
+
async fn reset_allows_previously_blocked_requests() {
|
|
544
|
+
let state = Arc::new(BudgetState::new());
|
|
545
|
+
state.global_spend.store(usd_to_microcents(10.0), Ordering::Relaxed);
|
|
546
|
+
|
|
547
|
+
let config = BudgetConfig {
|
|
548
|
+
global_limit: Some(5.0),
|
|
549
|
+
enforcement: Enforcement::Hard,
|
|
550
|
+
..Default::default()
|
|
551
|
+
};
|
|
552
|
+
|
|
553
|
+
let mut svc = build_service(config, Arc::clone(&state));
|
|
554
|
+
|
|
555
|
+
// Should be rejected.
|
|
556
|
+
let err = svc.call(LlmRequest::Chat(chat_req("gpt-4"))).await;
|
|
557
|
+
assert!(err.is_err());
|
|
558
|
+
|
|
559
|
+
// Reset and retry.
|
|
560
|
+
state.reset();
|
|
561
|
+
let ok = svc.call(LlmRequest::Chat(chat_req("gpt-4"))).await;
|
|
562
|
+
assert!(ok.is_ok(), "should succeed after reset");
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// ── Unlimited config ────────────────────────────────────────────────────
|
|
566
|
+
|
|
567
|
+
#[tokio::test]
|
|
568
|
+
async fn unlimited_config_allows_all_requests() {
|
|
569
|
+
let state = Arc::new(BudgetState::new());
|
|
570
|
+
let config = BudgetConfig::default();
|
|
571
|
+
|
|
572
|
+
let mut svc = build_service(config, state);
|
|
573
|
+
for _ in 0..20 {
|
|
574
|
+
assert!(svc.call(LlmRequest::Chat(chat_req("gpt-4"))).await.is_ok());
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// ── Propagates inner errors ─────────────────────────────────────────────
|
|
579
|
+
|
|
580
|
+
#[tokio::test]
|
|
581
|
+
async fn propagates_inner_service_errors() {
|
|
582
|
+
let state = Arc::new(BudgetState::new());
|
|
583
|
+
let config = BudgetConfig {
|
|
584
|
+
global_limit: Some(100.0),
|
|
585
|
+
enforcement: Enforcement::Hard,
|
|
586
|
+
..Default::default()
|
|
587
|
+
};
|
|
588
|
+
|
|
589
|
+
let layer = BudgetLayer::new(config, state);
|
|
590
|
+
let inner = LlmService::new(MockClient::failing_timeout());
|
|
591
|
+
let mut svc = layer.layer(inner);
|
|
592
|
+
|
|
593
|
+
let err = svc
|
|
594
|
+
.call(LlmRequest::Chat(chat_req("gpt-4")))
|
|
595
|
+
.await
|
|
596
|
+
.expect_err("should propagate inner error");
|
|
597
|
+
assert!(matches!(err, LiterLlmError::Timeout));
|
|
598
|
+
}
|
|
599
|
+
}
|