forge-guardrails 0.1.2

Foundation types for an LLM-agent workflow framework
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
//! Proxy routes unit tests.

use std::sync::Arc;

use axum::body::Bytes;
use axum::extract::State;
use axum::http::HeaderMap;
use futures_util::StreamExt;
use serde_json::json;
use tokio::sync::Mutex as TokioMutex;

use forge_guardrails::{
    ApiFormat, BackendError, ChunkStream, ChunkType, ClassifierModelKind, ContextDiscoveryError,
    LLMRequestOptions, LLMResponse, SamplingParams, SchemaCompressionMode, ScorerMode, StreamChunk,
    StreamError, TextResponse, ToolCallPolicyConfig, ToolOutputCompressionConfig, ToolSpec,
};

use super::handlers::{
    anthropic_messages, anthropic_messages_with_client, chat_completions, extract_anthropic_model,
    extract_openai_model, models,
};
use super::AppState;
use crate::client::ClientFactory;
use crate::config::ProxyConfig;

#[cfg(feature = "secrets-scanner")]
const SECRET: &str = "ghp_n0tArEaLsEcReTgHuBpAt1234567890AbCde";

fn test_config() -> Arc<ProxyConfig> {
    Arc::new(ProxyConfig {
        host: "127.0.0.1".to_string(),
        port: 8081,
        default_model: "default".to_string(),
        default_model_explicit: true,
        context_tokens: 8192,
        max_retries: 0,
        rescue_enabled: true,
        serialize_requests: false,
        verbose: false,
        classifier_dir: None,
        classifier_mode: ScorerMode::Shadow,
        classifier_model: ClassifierModelKind::Quantized,
        classifier_auto_download: false,
        classifier_max_latency_ms: None,
        final_response_classifier_dir: None,
        final_response_classifier_mode: ScorerMode::Shadow,
        final_response_classifier_model: ClassifierModelKind::Quantized,
        final_response_classifier_max_latency_ms: None,
        tool_output_compression: ToolOutputCompressionConfig::disabled(),
        tool_call_policy: ToolCallPolicyConfig::disabled(),
        schema_compression: SchemaCompressionMode::Disabled,
        redact_secrets: false,
    })
}

fn test_config_without_default_model() -> Arc<ProxyConfig> {
    let mut config = (*test_config()).clone();
    config.default_model = "forge-guardrails-unset".to_string();
    config.default_model_explicit = false;
    Arc::new(config)
}

#[cfg(feature = "secrets-scanner")]
fn test_config_with_secret_redaction() -> Arc<ProxyConfig> {
    let mut config = (*test_config()).clone();
    config.redact_secrets = true;
    Arc::new(config)
}

fn test_state() -> AppState {
    AppState {
        config: test_config(),
        client_factory: Arc::new(ClientFactory::DirectOpenAi {
            base_url: "http://127.0.0.1:9".to_string(),
            api_key: None,
            http_client: reqwest::Client::new(),
            context_tokens: 8192,
        }),
        request_mutex: Arc::new(TokioMutex::new(())),
        scorer: None,
        final_response_scorer: None,
        tool_output_state: Arc::new(forge_guardrails::ToolOutputCompressionState::new()),
    }
}

#[cfg(feature = "secrets-scanner")]
fn test_state_with_secret_redaction(base_url: String) -> AppState {
    AppState {
        config: test_config_with_secret_redaction(),
        client_factory: Arc::new(ClientFactory::DirectOpenAi {
            base_url,
            api_key: None,
            http_client: reqwest::Client::new(),
            context_tokens: 8192,
        }),
        request_mutex: Arc::new(TokioMutex::new(())),
        scorer: None,
        final_response_scorer: None,
        tool_output_state: Arc::new(forge_guardrails::ToolOutputCompressionState::new()),
    }
}

fn test_state_without_default_model() -> AppState {
    AppState {
        config: test_config_without_default_model(),
        client_factory: Arc::new(ClientFactory::DirectOpenAi {
            base_url: "http://127.0.0.1:9".to_string(),
            api_key: None,
            http_client: reqwest::Client::new(),
            context_tokens: 8192,
        }),
        request_mutex: Arc::new(TokioMutex::new(())),
        scorer: None,
        final_response_scorer: None,
        tool_output_state: Arc::new(forge_guardrails::ToolOutputCompressionState::new()),
    }
}

struct BinaryChannelStreamClient {
    receiver:
        std::sync::Mutex<Option<tokio::sync::mpsc::Receiver<Result<StreamChunk, StreamError>>>>,
}

struct StaticTextClient;

impl BinaryChannelStreamClient {
    fn new(receiver: tokio::sync::mpsc::Receiver<Result<StreamChunk, StreamError>>) -> Self {
        Self {
            receiver: std::sync::Mutex::new(Some(receiver)),
        }
    }
}

impl forge_guardrails::LLMClient for BinaryChannelStreamClient {
    fn api_format(&self) -> ApiFormat {
        ApiFormat::OpenAI
    }

    async fn send(
        &self,
        _messages: Vec<serde_json::Value>,
        _tools: Option<Vec<ToolSpec>>,
        _sampling: Option<SamplingParams>,
    ) -> Result<LLMResponse, BackendError> {
        Err(BackendError::new(500, "send should not be used"))
    }

    async fn send_stream(
        &self,
        _messages: Vec<serde_json::Value>,
        _tools: Option<Vec<ToolSpec>>,
        _sampling: Option<SamplingParams>,
    ) -> Result<ChunkStream, StreamError> {
        Err(StreamError::new("use send_stream_with_options"))
    }

    async fn send_stream_with_options(
        &self,
        _messages: Vec<serde_json::Value>,
        _tools: Option<Vec<ToolSpec>>,
        _options: LLMRequestOptions,
    ) -> Result<ChunkStream, StreamError> {
        let mut receiver = self
            .receiver
            .lock()
            .unwrap()
            .take()
            .expect("receiver used once");
        Ok(Box::pin(async_stream::stream! {
            while let Some(chunk) = receiver.recv().await {
                yield chunk;
            }
        }))
    }

    async fn get_context_length(&self) -> Result<Option<i64>, ContextDiscoveryError> {
        Ok(Some(4096))
    }
}

impl forge_guardrails::LLMClient for StaticTextClient {
    fn api_format(&self) -> ApiFormat {
        ApiFormat::OpenAI
    }

    async fn send(
        &self,
        _messages: Vec<serde_json::Value>,
        _tools: Option<Vec<ToolSpec>>,
        _sampling: Option<SamplingParams>,
    ) -> Result<LLMResponse, BackendError> {
        Ok(LLMResponse::Text(TextResponse::new("ok")))
    }

    async fn send_stream(
        &self,
        _messages: Vec<serde_json::Value>,
        _tools: Option<Vec<ToolSpec>>,
        _sampling: Option<SamplingParams>,
    ) -> Result<ChunkStream, StreamError> {
        Err(StreamError::new("stream should not be used"))
    }

    async fn get_context_length(&self) -> Result<Option<i64>, ContextDiscoveryError> {
        Ok(Some(4096))
    }
}

#[test]
fn extracts_openai_request_model() {
    let body = br#"{"model":"forge-virtual","messages":[]}"#;
    assert_eq!(extract_openai_model(body, "default"), "forge-virtual");
}

#[test]
fn extracts_anthropic_request_model() {
    let body = br#"{"model":"claude-sonnet","messages":[],"max_tokens":64}"#;
    assert_eq!(extract_anthropic_model(body, "default"), "claude-sonnet");
}

#[test]
fn model_extraction_falls_back_for_invalid_json() {
    assert_eq!(extract_openai_model(b"not json", "default"), "default");
}

#[test]
fn model_extraction_falls_back_for_empty_model() {
    let body = br#"{"model":"   ","messages":[]}"#;
    assert_eq!(extract_anthropic_model(body, "default"), "default");
}

#[tokio::test]
async fn binary_openai_invalid_json_returns_400() {
    let response = chat_completions(State(test_state()), Bytes::from_static(b"not json")).await;

    assert_eq!(response.status().as_u16(), 400);
}

#[tokio::test]
async fn binary_openai_oversized_body_returns_413() {
    let response = chat_completions(
        State(test_state()),
        Bytes::from(vec![b'x'; 17 * 1024 * 1024]),
    )
    .await;

    assert_eq!(response.status().as_u16(), 413);
}

#[tokio::test]
async fn binary_models_endpoint_is_empty_without_explicit_default_model() {
    let response = models(State(test_state_without_default_model())).await;

    assert_eq!(response.status().as_u16(), 200);
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .expect("body");
    let body: serde_json::Value = serde_json::from_slice(&bytes).expect("json");
    assert_eq!(body["data"].as_array().expect("data").len(), 0);
}

#[tokio::test]
async fn binary_openai_missing_model_returns_400_without_explicit_default() {
    let body = Bytes::from(
        json!({
            "messages": [{"role": "user", "content": "hi"}],
            "stream": false
        })
        .to_string(),
    );

    let response = chat_completions(State(test_state_without_default_model()), body).await;

    assert_eq!(response.status().as_u16(), 400);
}

#[tokio::test]
async fn binary_anthropic_invalid_json_returns_400() {
    let response = anthropic_messages(
        State(test_state()),
        HeaderMap::new(),
        Bytes::from_static(b"not json"),
    )
    .await;

    assert_eq!(response.status().as_u16(), 400);
}

#[tokio::test]
async fn binary_anthropic_typed_parse_failure_returns_400() {
    let response = anthropic_messages(
        State(test_state()),
        HeaderMap::new(),
        Bytes::from_static(br#"{"model":"claude-test","messages":[]}"#),
    )
    .await;

    assert_eq!(response.status().as_u16(), 400);
}

#[tokio::test]
async fn binary_anthropic_adaptive_thinking_request_is_accepted() {
    let body = Bytes::from(
        json!({
            "model": "claude-opus-4-8",
            "max_tokens": 128,
            "messages": [{"role": "user", "content": "hello"}],
            "thinking": {"type": "adaptive", "display": "summarized"},
            "output_config": {"effort": "xhigh"}
        })
        .to_string(),
    );
    let response = anthropic_messages_with_client(
        test_config(),
        Arc::new(TokioMutex::new(())),
        Arc::new(StaticTextClient),
        body,
    )
    .await;

    assert_eq!(response.status().as_u16(), 200);
}

#[tokio::test]
async fn binary_openai_malformed_tool_request_returns_400() {
    let body = Bytes::from(
        json!({
            "messages": [{"role": "user", "content": "hi"}],
            "model": "test",
            "tools": [{
                "type": "function",
                "function": {
                    "name": "search",
                    "parameters": {"type": "array"}
                }
            }]
        })
        .to_string(),
    );

    let response = chat_completions(State(test_state()), body).await;

    assert_eq!(response.status().as_u16(), 400);
}

#[tokio::test]
async fn external_backend_uses_request_model() {
    let mut upstream = mockito::Server::new_async().await;
    let _mock = upstream
        .mock("POST", "/v1/chat/completions")
        .match_body(mockito::Matcher::Json(json!({
            "model": "request-model",
            "messages": [{"role": "user", "content": "hello"}],
            "stream": false
        })))
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(
            json!({
                "id": "chatcmpl-routed",
                "object": "chat.completion",
                "created": 1,
                "model": "request-model",
                "choices": [{
                    "index": 0,
                    "message": {"role": "assistant", "content": "ok"},
                    "finish_reason": "stop"
                }],
                "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}
            })
            .to_string(),
        )
        .create_async()
        .await;

    let state = AppState {
        config: test_config(),
        client_factory: Arc::new(ClientFactory::DirectOpenAi {
            base_url: upstream.url(),
            api_key: None,
            http_client: reqwest::Client::new(),
            context_tokens: 8192,
        }),
        request_mutex: Arc::new(TokioMutex::new(())),
        scorer: None,
        final_response_scorer: None,
        tool_output_state: Arc::new(forge_guardrails::ToolOutputCompressionState::new()),
    };
    let body = Bytes::from(
        json!({
            "model": "request-model",
            "messages": [{"role": "user", "content": "hello"}],
            "stream": false
        })
        .to_string(),
    );

    let response = chat_completions(State(state), body).await;

    assert_eq!(response.status().as_u16(), 200);
}

#[cfg(feature = "secrets-scanner")]
#[tokio::test]
async fn openai_route_redacts_messages_before_upstream_when_enabled() {
    let mut upstream = mockito::Server::new_async().await;
    let _mock = upstream
        .mock("POST", "/v1/chat/completions")
        .match_body(mockito::Matcher::Json(json!({
            "model": "request-model",
            "messages": [{"role": "user", "content": "leaked [REDACTED_SECRET]"}],
            "stream": false
        })))
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(
            json!({
                "id": "chatcmpl-redacted",
                "object": "chat.completion",
                "created": 1,
                "model": "request-model",
                "choices": [{
                    "index": 0,
                    "message": {"role": "assistant", "content": "ok"},
                    "finish_reason": "stop"
                }]
            })
            .to_string(),
        )
        .create_async()
        .await;
    let body = Bytes::from(
        json!({
            "model": "request-model",
            "messages": [{"role": "user", "content": format!("leaked {SECRET}")}],
            "stream": false
        })
        .to_string(),
    );

    let response = chat_completions(
        State(test_state_with_secret_redaction(upstream.url())),
        body,
    )
    .await;

    assert_eq!(response.status().as_u16(), 200);
}

#[cfg(feature = "secrets-scanner")]
#[tokio::test]
async fn anthropic_route_redacts_raw_body_before_provider_preserving_upstream() {
    let mut upstream = mockito::Server::new_async().await;
    let _mock = upstream
        .mock("POST", "/v1/chat/completions")
        .match_body(mockito::Matcher::Regex(
            r#""content"\s*:\s*"leaked \[REDACTED_SECRET\]""#.to_string(),
        ))
        .with_status(200)
        .with_header("content-type", "application/json")
        .with_body(
            json!({
                "id": "chatcmpl-redacted-anthropic",
                "object": "chat.completion",
                "created": 1,
                "model": "claude-test",
                "choices": [{
                    "index": 0,
                    "message": {"role": "assistant", "content": "ok"},
                    "finish_reason": "stop"
                }],
                "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}
            })
            .to_string(),
        )
        .create_async()
        .await;
    let body = Bytes::from(
        json!({
            "model": "claude-test",
            "max_tokens": 128,
            "messages": [{"role": "user", "content": [{"type": "text", "text": format!("leaked {SECRET}")}]}]
        })
        .to_string(),
    );

    let response = anthropic_messages(
        State(test_state_with_secret_redaction(upstream.url())),
        HeaderMap::new(),
        body,
    )
    .await;

    assert_eq!(response.status().as_u16(), 200);
}

#[tokio::test]
async fn binary_anthropic_response_yields_body_chunk_before_backend_final() {
    use tokio::time::{timeout, Duration};

    let config = test_config();
    let (tx, rx) = tokio::sync::mpsc::channel(4);
    let client = Arc::new(BinaryChannelStreamClient::new(rx));
    let body = Bytes::from(
        json!({
            "model": "claude-test",
            "max_tokens": 128,
            "messages": [{"role": "user", "content": "hello"}],
            "stream": true
        })
        .to_string(),
    );

    let response =
        anthropic_messages_with_client(config, Arc::new(TokioMutex::new(())), client, body).await;
    assert_eq!(response.status().as_u16(), 200);
    assert_eq!(
        response.headers().get("content-type").unwrap(),
        "text/event-stream"
    );
    assert_eq!(response.headers().get("cache-control").unwrap(), "no-cache");
    assert_eq!(response.headers().get("x-accel-buffering").unwrap(), "no");

    let mut body_stream = response.into_body().into_data_stream();
    tx.send(Ok(
        StreamChunk::new(ChunkType::TextDelta).with_content("first")
    ))
    .await
    .unwrap();
    let first = timeout(Duration::from_millis(100), body_stream.next())
        .await
        .expect("first body chunk before final")
        .expect("body chunk")
        .expect("body ok");
    let first = std::str::from_utf8(&first).unwrap();
    assert!(first.starts_with("event: "));
    assert!(!first.contains("[DONE]"));

    tx.send(Ok(StreamChunk::new(ChunkType::Final)
        .with_response(LLMResponse::Text(TextResponse::new("first")))))
        .await
        .unwrap();
}