llm-wasm 0.4.2

If your cost guard needs Tokio, it cannot run where the call starts. LLM call logic with no I/O for wasm32 and native: real prices and budget ledger, retry with Retry-After, guards, routing, cache, stream decoding, JSON repair, JS bindings.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! # Module: Guard
//!
//! ## Responsibility
//! Inspect [`ChatRequest`]s before they are dispatched and either allow,
//! block, or modify them. Guards compose via [`GuardChain`].
//!
//! ## Guarantees
//! - `GuardChain::check` stops at the first `Block` result
//! - `GuardChain::check` returns `Ok(None)` if every guard allows the request
//! - No I/O: all evaluation is in-memory

use crate::error::LlmWasmError;
use crate::types::ChatRequest;

/// The outcome of a single guard evaluation.
///
/// `#[non_exhaustive]` since 0.3: a `match` on it needs a `_` arm.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum GuardResult {
    /// The request may proceed unchanged.
    Allow,
    /// The request should be rejected with the given reason.
    Block {
        /// Human-readable explanation.
        reason: String,
    },
    /// The request should be replaced with this modified version.
    Modify(ChatRequest),
}

/// A composable check applied to a [`ChatRequest`].
///
/// Guards are `Send + Sync` (since 0.3), so a [`GuardChain`] can live in
/// `Arc` shared state of an async server (axum, tower, actix) or a `static`.
pub trait Guard: Send + Sync {
    /// Short name identifying this guard (used in error messages).
    fn name(&self) -> &str;

    /// Evaluate the guard against the request.
    fn check(&self, request: &ChatRequest) -> GuardResult;
}

/// Rejects requests whose messages contain any blocklisted term.
///
/// Matching is case-insensitive (Unicode lowercase). By default a term matches
/// anywhere, so `"ass"` also blocks `"class"`; build the guard with
/// [`ContentGuard::whole_words`] to match whole words only.
///
/// # Example
/// ```rust
/// use llm_wasm::guard::{ContentGuard, Guard, GuardResult};
/// use llm_wasm::types::{ChatRequest, ChatMessage, Role};
///
/// let guard = ContentGuard::whole_words(vec!["spam".into()]);
/// let req = ChatRequest::new("m", vec![ChatMessage::new(Role::User, "buy SPAM now")]);
/// assert!(matches!(guard.check(&req), GuardResult::Block { .. }));
/// let ok = ChatRequest::new("m", vec![ChatMessage::new(Role::User, "spammer list")]);
/// assert!(matches!(guard.check(&ok), GuardResult::Allow));
/// ```
#[derive(Debug, Clone)]
pub struct ContentGuard {
    blocklist: Vec<String>,
    lowered: Vec<String>,
    whole_words: bool,
}

impl ContentGuard {
    /// Create a guard that blocks messages containing any term, anywhere.
    pub fn new(blocklist: Vec<String>) -> Self {
        let lowered = blocklist.iter().map(|t| t.to_lowercase()).collect();
        Self {
            blocklist,
            lowered,
            whole_words: false,
        }
    }

    /// Create a guard that blocks only whole-word (or whole-phrase) matches:
    /// the characters on each side of the match must not be letters or digits.
    pub fn whole_words(blocklist: Vec<String>) -> Self {
        Self {
            whole_words: true,
            ..Self::new(blocklist)
        }
    }

    fn matches(&self, lower_text: &str, term: &str) -> bool {
        if term.is_empty() {
            return false;
        }
        if !self.whole_words {
            return lower_text.contains(term);
        }
        lower_text.match_indices(term).any(|(i, m)| {
            let before = lower_text[..i].chars().next_back();
            let after = lower_text[i + m.len()..].chars().next();
            !before.is_some_and(char::is_alphanumeric) && !after.is_some_and(char::is_alphanumeric)
        })
    }
}

impl Guard for ContentGuard {
    fn name(&self) -> &str {
        "content"
    }

    fn check(&self, request: &ChatRequest) -> GuardResult {
        for message in &request.messages {
            let lower = message.content.to_lowercase();
            for (term, low) in self.blocklist.iter().zip(&self.lowered) {
                if self.matches(&lower, low) {
                    return GuardResult::Block {
                        reason: format!("message contains blocked term '{term}'"),
                    };
                }
            }
        }
        GuardResult::Allow
    }
}

/// Rejects requests whose total message character count exceeds a limit.
///
/// # Example
/// ```rust
/// use llm_wasm::guard::{LengthGuard, Guard, GuardResult};
/// use llm_wasm::types::{ChatRequest, ChatMessage, Role};
///
/// let guard = LengthGuard::new(10);
/// let req = ChatRequest::new("m", vec![ChatMessage::new(Role::User, "hello world!")]);
/// assert!(matches!(guard.check(&req), GuardResult::Block { .. }));
/// ```
#[derive(Debug, Clone)]
pub struct LengthGuard {
    max_total_chars: usize,
}

impl LengthGuard {
    /// Create a guard with the given maximum total character count.
    pub fn new(max_total_chars: usize) -> Self {
        Self { max_total_chars }
    }
}

impl Guard for LengthGuard {
    fn name(&self) -> &str {
        "length"
    }

    fn check(&self, request: &ChatRequest) -> GuardResult {
        let total: usize = request
            .messages
            .iter()
            .map(|m| m.content.chars().count())
            .sum();
        if total > self.max_total_chars {
            GuardResult::Block {
                reason: format!(
                    "total message length {total} exceeds limit {}",
                    self.max_total_chars
                ),
            }
        } else {
            GuardResult::Allow
        }
    }
}

/// Runs a sequence of guards in order, stopping at the first `Block`.
///
/// # Example
/// ```rust
/// use llm_wasm::guard::{GuardChain, ContentGuard, LengthGuard};
/// use llm_wasm::types::{ChatRequest, ChatMessage, Role};
///
/// let chain = GuardChain::new()
///     .add(ContentGuard::new(vec!["spam".into()]))
///     .add(LengthGuard::new(1000));
/// let req = ChatRequest::new("m", vec![ChatMessage::new(Role::User, "hello")]);
/// assert!(chain.check(&req).unwrap().is_none()); // allowed
/// ```
pub struct GuardChain {
    guards: Vec<Box<dyn Guard>>,
}

impl std::fmt::Debug for GuardChain {
    /// Lists the guards by [`Guard::name`], in order.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GuardChain")
            .field(
                "guards",
                &self.guards.iter().map(|g| g.name()).collect::<Vec<_>>(),
            )
            .finish()
    }
}

impl Default for GuardChain {
    fn default() -> Self {
        Self::new()
    }
}

impl GuardChain {
    /// Create an empty guard chain.
    pub fn new() -> Self {
        Self { guards: Vec::new() }
    }

    /// Append a guard and return `self` for chaining.
    #[allow(clippy::should_implement_trait)]
    pub fn add(mut self, guard: impl Guard + 'static) -> Self {
        self.guards.push(Box::new(guard));
        self
    }

    /// Run all guards in order against `request`.
    ///
    /// # Returns
    /// - `Ok(None)`: every guard allowed the request
    /// - `Ok(Some(modified))`: a guard returned a `Modify` result
    /// - `Err(LlmWasmError::GuardBlocked)`: a guard blocked the request
    ///
    /// Stops at the first `Block` or `Modify` result.
    ///
    /// # Panics
    /// This function never panics.
    pub fn check(&self, request: &ChatRequest) -> Result<Option<ChatRequest>, LlmWasmError> {
        let current = request;
        // We need an owned copy only if a Modify guard fires
        let mut owned: Option<ChatRequest> = None;

        for guard in &self.guards {
            let target = owned.as_ref().unwrap_or(current);
            match guard.check(target) {
                GuardResult::Allow => {}
                GuardResult::Block { reason } => {
                    return Err(LlmWasmError::GuardBlocked {
                        guard: guard.name().to_string(),
                        reason,
                    });
                }
                GuardResult::Modify(modified) => {
                    owned = Some(modified);
                }
            }
        }
        Ok(owned)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{ChatMessage, Role};

    fn req(content: &str) -> ChatRequest {
        ChatRequest::new("model", vec![ChatMessage::new(Role::User, content)])
    }

    #[test]
    fn test_content_guard_blocks_blocklisted_term() {
        let guard = ContentGuard::new(vec!["spam".into()]);
        assert!(matches!(
            guard.check(&req("buy spam now")),
            GuardResult::Block { .. }
        ));
    }

    #[test]
    fn test_content_guard_case_insensitive() {
        let guard = ContentGuard::new(vec!["spam".into()]);
        assert!(matches!(
            guard.check(&req("Buy SPAM Now")),
            GuardResult::Block { .. }
        ));
    }

    #[test]
    fn test_content_guard_allows_clean_request() {
        let guard = ContentGuard::new(vec!["spam".into()]);
        assert!(matches!(
            guard.check(&req("hello world")),
            GuardResult::Allow
        ));
    }

    #[test]
    fn test_length_guard_blocks_over_limit() {
        let guard = LengthGuard::new(5);
        assert!(matches!(
            guard.check(&req("hello world")),
            GuardResult::Block { .. }
        ));
    }

    #[test]
    fn test_length_guard_allows_under_limit() {
        let guard = LengthGuard::new(100);
        assert!(matches!(guard.check(&req("hi")), GuardResult::Allow));
    }

    #[test]
    fn test_length_guard_allows_at_exact_limit() {
        let guard = LengthGuard::new(5);
        assert!(matches!(guard.check(&req("hello")), GuardResult::Allow));
    }

    #[test]
    fn test_guard_chain_allows_clean_request() {
        let chain = GuardChain::new()
            .add(ContentGuard::new(vec!["bad".into()]))
            .add(LengthGuard::new(1000));
        let result = chain.check(&req("good content")).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_guard_chain_stops_at_first_block() {
        let chain = GuardChain::new()
            .add(ContentGuard::new(vec!["spam".into()]))
            .add(LengthGuard::new(3)); // also would block, but shouldn't be reached
        let result = chain.check(&req("spam"));
        assert!(matches!(
            result,
            Err(LlmWasmError::GuardBlocked { guard, .. }) if guard == "content"
        ));
    }

    #[test]
    fn test_guard_chain_empty_allows_everything() {
        let chain = GuardChain::new();
        assert!(chain.check(&req("anything")).unwrap().is_none());
    }

    #[test]
    fn test_guard_chain_length_blocks() {
        let chain = GuardChain::new().add(LengthGuard::new(2));
        let result = chain.check(&req("too long"));
        assert!(matches!(result, Err(LlmWasmError::GuardBlocked { .. })));
    }

    #[test]
    fn test_guard_chain_debug_lists_names_and_result_clones() {
        let chain = GuardChain::new()
            .add(ContentGuard::new(vec![]))
            .add(LengthGuard::new(1));
        assert_eq!(
            format!("{chain:?}"),
            r#"GuardChain { guards: ["content", "length"] }"#
        );
        let r = GuardResult::Block { reason: "x".into() };
        assert!(matches!(r.clone(), GuardResult::Block { reason } if reason == "x"));
    }

    #[test]
    fn test_length_guard_counts_characters_not_bytes() {
        // 0.1.x summed byte lengths, so 10 accented characters (20 bytes)
        // were blocked by a 10-character limit.
        let req = ChatRequest::new("m", vec![ChatMessage::new(Role::User, "\u{e9}".repeat(10))]);
        assert!(matches!(
            LengthGuard::new(10).check(&req),
            GuardResult::Allow
        ));
        assert!(matches!(
            LengthGuard::new(9).check(&req),
            GuardResult::Block { .. }
        ));
    }

    #[test]
    fn test_whole_words_avoids_scunthorpe_problem() {
        let g = ContentGuard::whole_words(vec!["ass".into(), "credit card".into(), "café".into()]);
        let check = |t: &str| {
            matches!(
                g.check(&ChatRequest::new(
                    "m",
                    vec![ChatMessage::new(Role::User, t)]
                )),
                GuardResult::Block { .. }
            )
        };
        assert!(!check("this class is about assessment"));
        assert!(check("what an ASS."));
        assert!(check("my Credit Card number"));
        assert!(!check("creditcard"));
        assert!(check("Le CAFÉ, s'il vous plaît")); // Unicode lowercase
        assert!(!check("cafés")); // followed by a letter
                                  // the substring guard still matches inside words, as before
        let sub = ContentGuard::new(vec!["ass".into()]);
        assert!(matches!(
            sub.check(&ChatRequest::new(
                "m",
                vec![ChatMessage::new(Role::User, "class")]
            )),
            GuardResult::Block { .. }
        ));
        // an empty term never matches
        let empty = ContentGuard::new(vec![String::new()]);
        assert!(matches!(
            empty.check(&ChatRequest::new(
                "m",
                vec![ChatMessage::new(Role::User, "x")]
            )),
            GuardResult::Allow
        ));
    }
}