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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
use super::*;
use crate::clients::base::{
    ApiFormat, ChunkStream, ChunkType, LLMRequestOptions, LLMResponse, SamplingParams, StreamChunk,
    TextResponse,
};
use crate::core::tool_spec::ToolSpec;
use crate::error::{BackendError, ContextDiscoveryError, StreamError};
use indexmap::IndexMap;
use serde_json::Value;

// Dummy client for testing HTTP routing without a real backend.
struct DummyClient;

impl LLMClient for DummyClient {
    fn api_format(&self) -> ApiFormat {
        ApiFormat::OpenAI
    }
    async fn send(
        &self,
        _messages: Vec<Value>,
        _tools: Option<Vec<ToolSpec>>,
        _sampling: Option<SamplingParams>,
    ) -> Result<crate::clients::base::LLMResponse, BackendError> {
        Ok(crate::clients::base::LLMResponse::Text(
            crate::clients::base::TextResponse::new("test"),
        ))
    }
    async fn send_stream(
        &self,
        _messages: Vec<Value>,
        _tools: Option<Vec<ToolSpec>>,
        _sampling: Option<SamplingParams>,
    ) -> Result<ChunkStream, StreamError> {
        Ok(Box::pin(futures_util::stream::iter(vec![Ok(
            StreamChunk::new(ChunkType::Final)
                .with_response(LLMResponse::Text(TextResponse::new("test"))),
        )])))
    }
    async fn get_context_length(&self) -> Result<Option<i64>, ContextDiscoveryError> {
        Ok(Some(4096))
    }
}

struct RespondClient;

impl LLMClient for RespondClient {
    fn api_format(&self) -> ApiFormat {
        ApiFormat::OpenAI
    }
    async fn send(
        &self,
        _messages: Vec<Value>,
        _tools: Option<Vec<ToolSpec>>,
        _sampling: Option<SamplingParams>,
    ) -> Result<crate::clients::base::LLMResponse, BackendError> {
        let mut args = IndexMap::new();
        args.insert("message".to_string(), json!("responded"));
        Ok(crate::clients::base::LLMResponse::ToolCalls(vec![
            crate::clients::base::ToolCall::new("respond", args),
        ]))
    }
    async fn send_stream(
        &self,
        _messages: Vec<Value>,
        _tools: Option<Vec<ToolSpec>>,
        _sampling: Option<SamplingParams>,
    ) -> Result<ChunkStream, StreamError> {
        Err(StreamError::new("not implemented"))
    }
    async fn get_context_length(&self) -> Result<Option<i64>, ContextDiscoveryError> {
        Ok(Some(4096))
    }
}

fn dummy_ctx() -> ContextManager {
    ContextManager::new(
        Box::new(crate::context::strategies::NoCompact),
        4096,
        None,
        None,
        None,
    )
}

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

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

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

    async fn send(
        &self,
        _messages: Vec<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<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<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))
    }
}

#[test]
fn http_server_new() {
    let srv = HTTPServer::new("127.0.0.1", 8081, true, 3, true, "test-model");
    assert_eq!(srv.host, "127.0.0.1");
    assert_eq!(srv.port, 8081);
    assert!(srv.serialize_requests);
    assert_eq!(srv.max_retries, 3);
}

#[tokio::test]
async fn health_endpoint() {
    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "test");
    let (status, _ct, _headers, body) = srv
        .handle_request(
            "GET",
            "/health",
            &[],
            &Arc::new(DummyClient),
            &Arc::new(Mutex::new(dummy_ctx())),
        )
        .await;
    assert_eq!(status, 200);
    let v: Value = serde_json::from_str(&body).unwrap();
    assert_eq!(v["status"], "ok");
}

#[tokio::test]
async fn models_endpoint() {
    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "my-model");
    let (status, _ct, _headers, body) = srv
        .handle_request(
            "GET",
            "/v1/models",
            &[],
            &Arc::new(DummyClient),
            &Arc::new(Mutex::new(dummy_ctx())),
        )
        .await;
    assert_eq!(status, 200);
    let v: Value = serde_json::from_str(&body).unwrap();
    assert_eq!(v["data"][0]["id"], "my-model");
}

#[tokio::test]
async fn cors_preflight() {
    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "test");
    let (status, _ct, _headers, _body) = srv
        .handle_request(
            "OPTIONS",
            "/v1/chat/completions",
            &[],
            &Arc::new(DummyClient),
            &Arc::new(Mutex::new(dummy_ctx())),
        )
        .await;
    assert_eq!(status, 204);
}

#[tokio::test]
async fn invalid_json_returns_400() {
    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "test");
    let (status, _ct, _headers, _body) = srv
        .handle_request(
            "POST",
            "/v1/chat/completions",
            b"not json",
            &Arc::new(DummyClient),
            &Arc::new(Mutex::new(dummy_ctx())),
        )
        .await;
    assert_eq!(status, 400);
}

#[tokio::test]
async fn oversized_body_returns_413() {
    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "test");
    let big_body = vec![b'x'; 17 * 1024 * 1024];
    let (status, _ct, _headers, _body) = srv
        .handle_request(
            "POST",
            "/v1/chat/completions",
            &big_body,
            &Arc::new(DummyClient),
            &Arc::new(Mutex::new(dummy_ctx())),
        )
        .await;
    assert_eq!(status, 413);
}

#[tokio::test]
async fn unknown_route_returns_404() {
    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "test");
    let (status, _ct, _headers, _body) = srv
        .handle_request(
            "GET",
            "/unknown",
            &[],
            &Arc::new(DummyClient),
            &Arc::new(Mutex::new(dummy_ctx())),
        )
        .await;
    assert_eq!(status, 404);
}

#[tokio::test]
async fn chat_completions_valid_request() {
    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "test");
    let body = serde_json::to_vec(&json!({
        "messages": [{"role": "user", "content": "hi"}],
        "model": "test"
    }))
    .unwrap();
    let (status, _ct, _headers, body_str) = srv
        .handle_request(
            "POST",
            "/v1/chat/completions",
            &body,
            &Arc::new(DummyClient),
            &Arc::new(Mutex::new(dummy_ctx())),
        )
        .await;
    assert_eq!(status, 200);
    let v: Value = serde_json::from_str(&body_str).unwrap();
    assert_eq!(v["choices"][0]["message"]["content"], "test");
}

#[tokio::test]
async fn chat_completions_unknown_role_returns_400() {
    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "test");
    let body = serde_json::to_vec(&json!({
        "messages": [{"role": "function", "content": "hi"}],
        "model": "test"
    }))
    .unwrap();
    let (status, _ct, _headers, body_str) = srv
        .handle_request(
            "POST",
            "/v1/chat/completions",
            &body,
            &Arc::new(DummyClient),
            &Arc::new(Mutex::new(dummy_ctx())),
        )
        .await;

    assert_eq!(status, 400);
    let v: Value = serde_json::from_str(&body_str).unwrap();
    assert!(v["error"].as_str().unwrap().contains("role must be one of"));
}

#[tokio::test]
async fn chat_completions_malformed_tool_arguments_returns_400() {
    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "test");
    let body = serde_json::to_vec(&json!({
        "messages": [{
            "role": "assistant",
            "content": "",
            "tool_calls": [{
                "id": "c1",
                "type": "function",
                "function": {"name": "search", "arguments": "{broken"}
            }]
        }],
        "model": "test"
    }))
    .unwrap();
    let (status, _ct, _headers, body_str) = srv
        .handle_request(
            "POST",
            "/v1/chat/completions",
            &body,
            &Arc::new(DummyClient),
            &Arc::new(Mutex::new(dummy_ctx())),
        )
        .await;

    assert_eq!(status, 400);
    let v: Value = serde_json::from_str(&body_str).unwrap();
    assert!(v["error"]
        .as_str()
        .unwrap()
        .contains("arguments must be valid JSON"));
}

#[tokio::test]
async fn anthropic_messages_valid_request() {
    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "test");
    let body = serde_json::to_vec(&json!({
        "model": "claude-test",
        "max_tokens": 128,
        "messages": [{"role": "user", "content": "hi"}]
    }))
    .unwrap();
    let (status, ct, _headers, body_str) = srv
        .handle_request(
            "POST",
            "/v1/messages",
            &body,
            &Arc::new(DummyClient),
            &Arc::new(Mutex::new(dummy_ctx())),
        )
        .await;
    assert_eq!(status, 200);
    assert_eq!(ct, "application/json");
    let v: Value = serde_json::from_str(&body_str).unwrap();
    assert_eq!(v["type"], "message");
    assert_eq!(v["model"], "claude-test");
    assert_eq!(v["content"][0]["text"], "test");
    assert_eq!(v["stop_reason"], "end_turn");
}

#[tokio::test]
async fn anthropic_messages_route_ignores_query_string() {
    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "test");
    let body = serde_json::to_vec(&json!({
        "model": "claude-test",
        "max_tokens": 128,
        "messages": [{"role": "user", "content": "hi"}]
    }))
    .unwrap();
    let (status, ct, _headers, body_str) = srv
        .handle_request(
            "POST",
            "/v1/messages?beta=true",
            &body,
            &Arc::new(DummyClient),
            &Arc::new(Mutex::new(dummy_ctx())),
        )
        .await;

    assert_eq!(status, 200);
    assert_eq!(ct, "application/json");
    let v: Value = serde_json::from_str(&body_str).unwrap();
    assert_eq!(v["content"][0]["text"], "test");
}

#[tokio::test]
async fn anthropic_messages_with_tools_strips_respond() {
    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "test");
    let body = serde_json::to_vec(&json!({
        "model": "claude-test",
        "max_tokens": 128,
        "messages": [{"role": "user", "content": "hi"}],
        "tools": [{
            "name": "search",
            "description": "Search",
            "input_schema": {
                "type": "object",
                "properties": {"query": {"type": "string"}},
                "required": ["query"]
            }
        }]
    }))
    .unwrap();
    let (status, _ct, _headers, body_str) = srv
        .handle_request(
            "POST",
            "/v1/messages",
            &body,
            &Arc::new(RespondClient),
            &Arc::new(Mutex::new(dummy_ctx())),
        )
        .await;
    assert_eq!(status, 200);
    let v: Value = serde_json::from_str(&body_str).unwrap();
    assert_eq!(v["content"][0]["text"], "responded");
    assert_eq!(v["stop_reason"], "end_turn");
}

#[tokio::test]
async fn anthropic_messages_invalid_json_returns_400() {
    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "test");
    let (status, _ct, _headers, _body) = srv
        .handle_request(
            "POST",
            "/v1/messages",
            b"not json",
            &Arc::new(DummyClient),
            &Arc::new(Mutex::new(dummy_ctx())),
        )
        .await;
    assert_eq!(status, 400);
}

#[tokio::test]
async fn anthropic_messages_streaming_request() {
    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "test");
    let body = serde_json::to_vec(&json!({
        "model": "claude-test",
        "max_tokens": 128,
        "messages": [{"role": "user", "content": "hi"}],
        "stream": true
    }))
    .unwrap();
    let (status, ct, _headers, body_str) = srv
        .handle_request(
            "POST",
            "/v1/messages",
            &body,
            &Arc::new(DummyClient),
            &Arc::new(Mutex::new(dummy_ctx())),
        )
        .await;
    assert_eq!(status, 200);
    assert_eq!(ct, "text/event-stream");
    assert!(body_str.contains("event: message_start"));
    assert!(body_str.contains("event: content_block_delta"));
    assert!(body_str.contains("event: message_stop"));
    assert!(body_str.contains("test"));
    assert!(!body_str.contains("[DONE]"));
}

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

    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "test");
    let (tx, rx) = tokio::sync::mpsc::channel(4);
    let client = Arc::new(ChannelStreamClient::new(rx));
    let ctx = Arc::new(Mutex::new(dummy_ctx()));
    let body = serde_json::to_vec(&json!({
        "model": "claude-test",
        "max_tokens": 128,
        "messages": [{"role": "user", "content": "hi"}],
        "stream": true
    }))
    .unwrap();

    let response = srv
        .handle_anthropic_messages_response(&body, &client, &ctx)
        .await;
    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]"));
}

#[tokio::test]
async fn streaming_request() {
    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "test");
    let body = serde_json::to_vec(&json!({
        "messages": [{"role": "user", "content": "hi"}],
        "model": "test",
        "stream": true
    }))
    .unwrap();
    let (status, ct, _headers, body_str) = srv
        .handle_request(
            "POST",
            "/v1/chat/completions",
            &body,
            &Arc::new(DummyClient),
            &Arc::new(Mutex::new(dummy_ctx())),
        )
        .await;
    assert_eq!(status, 200);
    assert_eq!(ct, "text/event-stream");
    assert!(body_str.contains("data: [DONE]"));
}

#[tokio::test]
async fn chat_completion_malformed_tool_returns_400() {
    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "test");
    let body = serde_json::to_vec(&json!({
            "messages": [{"role": "user", "content": "hi"}],
            "model": "test",
            "tools": [{"type": "function", "function": {"name": "search", "parameters": {"type": "array"}}}]
        }))
        .unwrap();
    let (status, _ct, _headers, body_str) = srv
        .handle_request(
            "POST",
            "/v1/chat/completions",
            &body,
            &Arc::new(DummyClient),
            &Arc::new(Mutex::new(dummy_ctx())),
        )
        .await;
    assert_eq!(status, 400);
    assert!(body_str.contains("function.parameters must have type 'object'"));
}

#[tokio::test]
async fn chat_completion_bad_forge_contract_returns_400() {
    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "test");
    let body = serde_json::to_vec(&json!({
        "messages": [{"role": "user", "content": "hi"}],
        "model": "test",
        "tools": [{
            "type": "function",
            "function": {
                "name": "search",
                "parameters": {"type": "object", "properties": {}}
            }
        }],
        "_forge": {"required_steps": ["missing"]}
    }))
    .unwrap();
    let response = srv
        .handle_chat_completions_response(
            &body,
            &Arc::new(DummyClient),
            &Arc::new(Mutex::new(dummy_ctx())),
        )
        .await;
    assert_eq!(response.status(), axum::http::StatusCode::BAD_REQUEST);
}

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

    let srv = HTTPServer::new("127.0.0.1", 8081, false, 3, true, "test");
    let (tx, rx) = tokio::sync::mpsc::channel(4);
    let client = Arc::new(ChannelStreamClient::new(rx));
    let ctx = Arc::new(Mutex::new(dummy_ctx()));
    let body = serde_json::to_vec(&json!({
        "messages": [{"role": "user", "content": "hi"}],
        "model": "test",
        "stream": true
    }))
    .unwrap();

    let response = srv
        .handle_chat_completions_response(&body, &client, &ctx)
        .await;
    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.contains("first"));
    assert!(!first.contains("[DONE]"));

    assert!(timeout(Duration::from_millis(50), body_stream.next())
        .await
        .is_err());

    tx.send(Ok(StreamChunk::new(ChunkType::Final)
        .with_response(LLMResponse::Text(TextResponse::new("first")))))
        .await
        .unwrap();
    let final_event = timeout(Duration::from_millis(100), body_stream.next())
        .await
        .expect("final body chunk")
        .expect("final event")
        .expect("body ok");
    assert!(std::str::from_utf8(&final_event)
        .unwrap()
        .contains("\"finish_reason\":\"stop\""));
}

#[test]
fn cors_headers_content() {
    let headers = HTTPServer::cors_headers();
    assert!(headers
        .iter()
        .any(|(k, _)| *k == "Access-Control-Allow-Origin"));
    assert!(headers
        .iter()
        .any(|(k, v)| *k == "Access-Control-Allow-Headers" && v.contains("Content-Type")));
}

#[test]
fn format_sse_body_structure() {
    let events = vec![json!({"test": 1})];
    let body = format_sse_body(&events);
    assert!(body.starts_with("data: "));
    assert!(body.contains("data: [DONE]"));
}

#[test]
fn parse_http_request_basic() {
    let raw = b"POST /v1/chat/completions HTTP/1.1\r\nContent-Type: application/json\r\n\r\n{\"test\": true}";
    let (method, path, headers, body) = parse_http_request(raw).unwrap();
    assert_eq!(method, "POST");
    assert_eq!(path, "/v1/chat/completions");
    assert_eq!(headers.len(), 1);
    assert!(body.starts_with(b"{"));
}

#[test]
fn parse_http_request_invalid() {
    assert!(parse_http_request(b"").is_none());
}

#[test]
fn max_body_size_is_16mb() {
    assert_eq!(MAX_BODY_SIZE, 16 * 1024 * 1024);
}