dynamo-llm 1.4.0

Dynamo LLM Library
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
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! HTTP regressions for validation performed by protocol adapters.

use dynamo_llm::http::service::metrics::{Endpoint, ErrorType, RequestType, Status};
use dynamo_runtime::config::environment_names::llm::{
    DYN_ENABLE_ANTHROPIC_API, DYN_HTTP_GRACEFUL_SHUTDOWN_TIMEOUT_SECS,
};
use serde_json::{Value, json};
use serial_test::serial;

#[allow(dead_code)]
#[path = "common/http_harness.rs"]
mod http_harness;
#[path = "common/ports.rs"]
mod ports;
#[allow(dead_code)]
#[path = "common/scripted_chat_engine.rs"]
mod scripted_chat_engine;

use http_harness::{HarnessService, MODEL, load_agent_fixture};

const BASE_ENV: [(&str, Option<&str>); 2] = [
    (DYN_ENABLE_ANTHROPIC_API, Some("1")),
    (DYN_HTTP_GRACEFUL_SHUTDOWN_TIMEOUT_SECS, Some("0")),
];

async fn post_json(svc: &HarnessService, path: &str, body: Value) -> reqwest::Response {
    svc.client
        .post(format!("{}{path}", svc.base_url))
        .json(&body)
        .send()
        .await
        .unwrap()
}

#[derive(Clone, Copy)]
enum ExpectedError {
    Validation,
    NotImplemented,
}

impl ExpectedError {
    fn status(self) -> reqwest::StatusCode {
        match self {
            Self::Validation => reqwest::StatusCode::BAD_REQUEST,
            Self::NotImplemented => reqwest::StatusCode::NOT_IMPLEMENTED,
        }
    }

    fn anthropic_type(self) -> &'static str {
        match self {
            Self::Validation => "invalid_request_error",
            Self::NotImplemented => "api_error",
        }
    }
}

async fn assert_openai_error(response: reqwest::Response, expected: ExpectedError, message: &str) {
    let status = expected.status();
    assert_eq!(response.status(), status);
    let body: Value = response.json().await.unwrap();
    assert_eq!(body["code"].as_u64(), Some(u64::from(status.as_u16())));
    assert!(
        body["message"].as_str().is_some_and(|actual| actual
            .to_ascii_lowercase()
            .contains(&message.to_ascii_lowercase())),
        "unexpected OpenAI error body: {body}"
    );
}

async fn assert_anthropic_error(
    response: reqwest::Response,
    expected: ExpectedError,
    message: &str,
) {
    assert_eq!(response.status(), expected.status());
    let body: Value = response.json().await.unwrap();
    assert_eq!(body["type"], "error");
    assert_eq!(body["error"]["type"], expected.anthropic_type());
    assert!(
        body["error"]["message"]
            .as_str()
            .is_some_and(|actual| actual.contains(message)),
        "unexpected Anthropic error body: {body}"
    );
}

fn assert_error_metrics(
    svc: &HarnessService,
    endpoint: &Endpoint,
    request_type: &RequestType,
    expected: &[(ErrorType, u64)],
) {
    for (error_type, expected) in expected {
        assert_eq!(
            svc.metrics.get_request_counter(
                MODEL,
                endpoint,
                request_type,
                &Status::Error,
                error_type,
            ),
            *expected,
            "unexpected {error_type:?} count for {endpoint}/{request_type}"
        );
    }
}

fn tool_name_requests(name: &str) -> [(&'static str, Value, bool); 3] {
    [
        (
            "/v1/messages",
            json!({
                "model": MODEL,
                "max_tokens": 16,
                "messages": [{"role": "user", "content": "ping"}],
                "tools": [{
                    "name": name,
                    "input_schema": {"type": "object", "properties": {}}
                }]
            }),
            true,
        ),
        (
            "/v1/responses",
            json!({
                "model": MODEL,
                "input": "ping",
                "tools": [{
                    "type": "function",
                    "name": name,
                    "parameters": {"type": "object", "properties": {}}
                }]
            }),
            false,
        ),
        (
            "/v1/chat/completions",
            json!({
                "model": MODEL,
                "messages": [{"role": "user", "content": "ping"}],
                "tools": [{
                    "type": "function",
                    "function": {
                        "name": name,
                        "parameters": {"type": "object", "properties": {}}
                    }
                }]
            }),
            false,
        ),
    ]
}

#[tokio::test]
#[serial]
async fn responses_conversion_distinguishes_invalid_from_unsupported() {
    temp_env::async_with_vars(BASE_ENV, async {
        let svc = HarnessService::start(Vec::new()).await;

        for (stream, content, expected, message) in [
            (
                true,
                json!({"type": "input_image", "file_id": "file_123"}),
                ExpectedError::NotImplemented,
                "image input by file_id",
            ),
            (
                false,
                json!({
                    "type": "input_file",
                    "file_url": "https://example.com/report.pdf"
                }),
                ExpectedError::NotImplemented,
                "file input content",
            ),
            (
                false,
                json!({"type": "input_image"}),
                ExpectedError::Validation,
                "requires file_id or image_url",
            ),
            (
                true,
                json!({"type": "input_file"}),
                ExpectedError::Validation,
                "requires exactly one of file_data, file_id, or file_url",
            ),
        ] {
            let response = post_json(
                &svc,
                "/v1/responses",
                json!({
                    "model": MODEL,
                    "stream": stream,
                    "input": [{"role": "user", "content": [content]}]
                }),
            )
            .await;
            assert_openai_error(response, expected, message).await;
        }

        for request_type in [RequestType::Unary, RequestType::Stream] {
            assert_error_metrics(
                &svc,
                &Endpoint::Responses,
                &request_type,
                &[
                    (ErrorType::NotImplemented, 1),
                    (ErrorType::Validation, 1),
                    (ErrorType::Internal, 0),
                ],
            );
        }

        assert!(svc.engine.take_requests().await.is_empty());
        svc.shutdown().await;
    })
    .await;
}

#[tokio::test]
#[serial]
async fn anthropic_tools_reject_unsupported_and_malformed_definitions() {
    temp_env::async_with_vars(BASE_ENV, async {
        let svc = HarnessService::start(Vec::new()).await;

        for (stream, tool_choice) in [
            (false, None),
            (true, Some(json!({"type": "tool", "name": "web_search"}))),
        ] {
            let mut body = json!({
                "model": MODEL,
                "max_tokens": 16,
                "stream": stream,
                "messages": [{"role": "user", "content": "ping"}],
                "tools": [{
                    "type": "web_search_20260209",
                    "name": "web_search"
                }]
            });
            if let Some(tool_choice) = tool_choice {
                body["tool_choice"] = tool_choice;
            }
            let response = post_json(&svc, "/v1/messages", body).await;
            assert_anthropic_error(
                response,
                ExpectedError::NotImplemented,
                "server tool type \"web_search_20260209\" is not supported",
            )
            .await;
        }

        let response = post_json(
            &svc,
            "/v1/messages",
            json!({
                    "model": MODEL,
                    "max_tokens": 16,
                    "stream": false,
                    "messages": [{"role": "user", "content": "ping"}],
                    "tools": [{"name": "get_weather"}]
            }),
        )
        .await;
        assert_anthropic_error(
            response,
            ExpectedError::Validation,
            "tools[0].input_schema: field required",
        )
        .await;

        for request_type in [RequestType::Unary, RequestType::Stream] {
            let validation = match &request_type {
                RequestType::Unary => 1,
                RequestType::Stream => 0,
            };
            assert_error_metrics(
                &svc,
                &Endpoint::AnthropicMessages,
                &request_type,
                &[
                    (ErrorType::NotImplemented, 1),
                    (ErrorType::Validation, validation),
                    (ErrorType::Internal, 0),
                ],
            );
        }

        assert!(svc.engine.take_requests().await.is_empty());
        svc.shutdown().await;
    })
    .await;
}

// `reqwest::send` completes when response headers arrive. A 400 for `stream: true`
// proves converted-request validation ran before the HTTP 200 SSE response was committed.
#[tokio::test]
#[serial]
async fn converted_validation_errors_are_returned_before_streaming_headers() {
    temp_env::async_with_vars(BASE_ENV, async {
        let svc = HarnessService::start(Vec::new()).await;

        for (stream, field) in [
            (false, json!({"top_p": 2.0})),
            (true, json!({"temperature": 3.0})),
        ] {
            let mut body = json!({"model": MODEL, "input": "ping", "stream": stream});
            body.as_object_mut()
                .unwrap()
                .extend(field.as_object().unwrap().clone());
            let response = post_json(&svc, "/v1/responses", body).await;
            assert_openai_error(response, ExpectedError::Validation, "must be").await;
        }

        for (stream, field) in [
            (false, json!({"temperature": 3.0})),
            (true, json!({"top_p": 2.0})),
        ] {
            let mut body = json!({
                "model": MODEL,
                "max_tokens": 16,
                "stream": stream,
                "messages": [{"role": "user", "content": "ping"}]
            });
            body.as_object_mut()
                .unwrap()
                .extend(field.as_object().unwrap().clone());
            let response = post_json(&svc, "/v1/messages", body).await;
            assert_anthropic_error(response, ExpectedError::Validation, "must be").await;
        }

        for endpoint in [Endpoint::Responses, Endpoint::AnthropicMessages] {
            for request_type in [RequestType::Unary, RequestType::Stream] {
                assert_error_metrics(
                    &svc,
                    &endpoint,
                    &request_type,
                    &[(ErrorType::Validation, 1), (ErrorType::Internal, 0)],
                );
            }
        }

        assert!(svc.engine.take_requests().await.is_empty());
        svc.shutdown().await;
    })
    .await;
}

#[tokio::test]
#[serial]
async fn responses_reject_empty_input_and_required_tool_choice_without_tools() {
    temp_env::async_with_vars(BASE_ENV, async {
        let svc = HarnessService::start(Vec::new()).await;

        for (body, message) in [
            (
                json!({"model": MODEL, "input": [], "max_tokens": 10}),
                "messages",
            ),
            (
                json!({
                    "model": MODEL,
                    "input": "ping",
                    "tools": [],
                    "tool_choice": "required"
                }),
                "tool_choice is \"required\"",
            ),
        ] {
            let response = post_json(&svc, "/v1/responses", body).await;
            assert_openai_error(response, ExpectedError::Validation, message).await;
        }

        assert!(svc.engine.take_requests().await.is_empty());
        svc.shutdown().await;
    })
    .await;
}

#[tokio::test]
#[serial]
async fn anthropic_content_validation_applies_to_messages_and_count_tokens() {
    temp_env::async_with_vars(BASE_ENV, async {
        let svc = HarnessService::start(Vec::new()).await;

        for (path, body, expected, message) in [
            (
                "/v1/messages",
                json!({
                    "model": MODEL,
                    "max_tokens": 10,
                    "stream": true,
                    "messages": [{"role": "user", "content": ["hello"]}]
                }),
                ExpectedError::Validation,
                "content blocks must be objects",
            ),
            (
                "/v1/messages",
                json!({
                    "model": MODEL,
                    "max_tokens": 10,
                    "messages": [{"role": "user", "content": []}]
                }),
                ExpectedError::Validation,
                "must contain at least one content block",
            ),
            (
                "/v1/messages/count_tokens",
                json!({
                    "model": MODEL,
                    "messages": [{"role": "user", "content": ["hello"]}]
                }),
                ExpectedError::Validation,
                "content blocks must be objects",
            ),
            (
                "/v1/messages",
                json!({
                    "model": MODEL,
                    "max_tokens": 16,
                    "messages": [{
                        "role": "user",
                        "content": [
                            {"type": "future_block_type", "value": 1},
                            {"type": "text", "text": "ping"}
                        ]
                    }]
                }),
                ExpectedError::NotImplemented,
                "content block type \"future_block_type\"",
            ),
            (
                "/v1/messages/count_tokens",
                json!({
                    "model": MODEL,
                    "messages": [{
                        "role": "user",
                        "content": [{"type": "future_block_type", "value": 1}]
                    }]
                }),
                ExpectedError::NotImplemented,
                "content block type \"future_block_type\"",
            ),
        ] {
            let response = post_json(&svc, path, body).await;
            assert_anthropic_error(response, expected, message).await;
        }

        for request_type in [RequestType::Unary, RequestType::Stream] {
            let not_implemented = match &request_type {
                RequestType::Unary => 1,
                RequestType::Stream => 0,
            };
            assert_error_metrics(
                &svc,
                &Endpoint::AnthropicMessages,
                &request_type,
                &[
                    (ErrorType::Validation, 1),
                    (ErrorType::NotImplemented, not_implemented),
                    (ErrorType::Internal, 0),
                ],
            );
        }

        assert!(svc.engine.take_requests().await.is_empty());
        svc.shutdown().await;
    })
    .await;
}

#[tokio::test]
#[serial]
async fn tool_name_limit_is_shared_across_protocols() {
    temp_env::async_with_vars(BASE_ENV, async {
        let valid_script = load_agent_fixture("text.sse").await.unwrap();
        let svc =
            HarnessService::start([valid_script.clone(), valid_script.clone(), valid_script]).await;

        let max_length_tool_name = "a".repeat(128);
        for (path, body, _) in tool_name_requests(&max_length_tool_name) {
            let response = post_json(&svc, path, body).await;
            assert_eq!(response.status(), reqwest::StatusCode::OK);
        }

        let too_long_tool_name = "a".repeat(129);
        for (path, body, anthropic) in tool_name_requests(&too_long_tool_name) {
            let response = post_json(&svc, path, body).await;
            if anthropic {
                assert_anthropic_error(response, ExpectedError::Validation, "128 character limit")
                    .await;
            } else {
                assert_openai_error(response, ExpectedError::Validation, "128 character limit")
                    .await;
            }
        }

        assert_eq!(svc.engine.take_requests().await.len(), 3);
        svc.shutdown().await;
    })
    .await;
}