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

use super::super::*;
use dynamo_renderer::{ChatTemplate, ContextMixins, OAIPromptFormatter, PromptFormatter};
use serde_json::{Value, json};

const TEMPLATE: &str =
    include_str!("../../../../../tests/data/muse_spark_open_deferred_tools.jinja");

fn formatter(template: &str) -> std::sync::Arc<dyn OAIPromptFormatter> {
    let config: ChatTemplate = serde_json::from_value(json!({"chat_template":template})).unwrap();
    let PromptFormatter::OAI(formatter) =
        PromptFormatter::from_parts(config, ContextMixins::new(&[]), true).unwrap();
    formatter
}

fn request(tools: Value, input: Value) -> NvCreateResponse {
    serde_json::from_value(json!({"model":"/model", "input":input, "tools":tools,
        "chat_template_args":{"current_date":"2026-10-06"}}))
    .unwrap()
}

fn namespace(defer: bool) -> Value {
    json!([{"type":"namespace", "name":"fs", "description":"Files", "defer_loading":defer,
        "tools":[{"type":"function", "name":"read", "description":"Read files", "parameters":{"type":"object", "properties":{"path":{"type":"string"}},"required":["path"]}}]}])
}

fn response_params(request: &NvCreateResponse) -> ResponseParams {
    ResponseParams {
        tools: request
            .inner
            .tools
            .as_ref()
            .map(|tools| tools.iter().map(|tool| tool.inner.clone()).collect()),
        template_tools: request.inner.tools.clone(),
        ..Default::default()
    }
}

fn unary_tool_response(
    params: &ResponseParams,
    name: &str,
    args: Value,
) -> anyhow::Result<NvResponse> {
    let response: NvCreateChatCompletionResponse = serde_json::from_value(json!({
        "id":"chat-1", "object":"chat.completion", "created":0, "model":"/model",
        "choices":[{"index":0,"message":{"role":"assistant","content":null,"tool_calls":[
            {"id":"call-1","type":"function","function":{"name":name,"arguments":args.to_string()}}
        ]},"finish_reason":"tool_calls","logprobs":null}]
    }))?;
    chat_completion_to_response(response, params, None)
}

#[test]
fn typed_responses_request_preserves_namespace_metadata_in_actual_template() {
    let response = request(namespace(true), json!("Read the file."));
    assert_eq!(
        serde_json::to_value(&response).unwrap()["tools"][0]["defer_loading"],
        true
    );
    let mut chat: NvCreateChatCompletionRequest = response.try_into().unwrap();
    let f = formatter(TEMPLATE);
    chat.normalize_responses_tools(f.supports_native_tools(&chat))
        .unwrap();
    assert_eq!(
        chat.inner.tools.as_ref().unwrap()[0].function.name,
        "fs.read"
    );
    let rendered = f.render(&chat).unwrap();
    assert!(rendered.contains("\"has_deferred_functions\": true"));
    assert!(rendered.contains("\"fs.*\""));
    assert!(!rendered.contains("\"parameters\""));
    chat.chat_template_args
        .as_mut()
        .unwrap()
        .insert("deferred_render_mode".into(), json!("tool_name_only"));
    let rendered = f.render(&chat).unwrap();
    assert!(rendered.contains("\"name\": \"fs.read\""));
    assert!(rendered.contains("\"defer_loading\": true"));
    assert!(!rendered.contains("\"parameters\""));
}

#[test]
fn legacy_templates_retain_eager_bare_names_and_flat_structure() {
    let response = request(namespace(true), json!("Read the file."));
    let mut chat: NvCreateChatCompletionRequest = response.try_into().unwrap();
    let f = formatter("{{ tools | tojson }}");
    chat.normalize_responses_tools(f.supports_native_tools(&chat))
        .unwrap();
    let rendered: Value = serde_json::from_str(&f.render(&chat).unwrap()).unwrap();
    assert_eq!(rendered[0]["function"]["name"], "read");
    assert!(rendered[0]["function"]["parameters"].is_object());
    assert!(rendered[0].get("defer_loading").is_none());
}

#[test]
fn native_names_distinguish_same_leaf_in_different_namespaces() {
    let mut tools = namespace(false);
    let mut second = tools[0].clone();
    second["name"] = json!("store");
    tools.as_array_mut().unwrap().push(second);
    let mut chat: NvCreateChatCompletionRequest =
        request(tools, json!("Read.")).try_into().unwrap();
    chat.normalize_responses_tools(true).unwrap();
    let tools = chat.inner.tools.as_ref().unwrap();
    assert_eq!(tools[0].function.name, "fs.read");
    assert_eq!(tools[1].function.name, "store.read");
    chat.normalize_responses_tools(false).unwrap();
    let tools = chat.inner.tools.as_ref().unwrap();
    assert_eq!(tools[0].function.name, "fs__read");
    assert_eq!(tools[1].function.name, "store__read");
}

#[test]
fn namespaced_history_and_named_choice_follow_selected_template_idempotently() {
    let input = json!([
        {"type":"function_call","call_id":"old-call","name":"read","namespace":"fs","arguments":"{\"path\":\"a.txt\"}"},
        {"type":"function_call_output","call_id":"old-call","output":"Contents"},
        {"role":"user","content":"Read it again."}
    ]);
    let mut response = request(namespace(false), input);
    response.inner.tool_choice =
        Some(serde_json::from_value(json!({"type":"function","name":"fs.read"})).unwrap());
    let mut chat: NvCreateChatCompletionRequest = response.try_into().unwrap();
    for (native, expected) in [(true, "fs.read"), (false, "read"), (true, "fs.read")] {
        chat.normalize_responses_tools(native).unwrap();
        let ChatCompletionRequestMessage::Assistant(message) = &chat.inner.messages[0] else {
            panic!("assistant history missing");
        };
        assert_eq!(
            message.tool_calls.as_ref().unwrap()[0].function.name,
            expected
        );
        let Some(ChatCompletionToolChoiceOption::Named(choice)) = &chat.inner.tool_choice else {
            panic!("named choice missing");
        };
        assert_eq!(choice.function.name, expected);
        let rendered = formatter(if native {
            TEMPLATE
        } else {
            "{{ messages | tojson }}"
        })
        .render(&chat)
        .unwrap();
        if native {
            assert!(rendered.contains("assistant to=fs.read<|message|>"));
            assert!(rendered.contains("<|start|>tool fs.read<|message|>"));
        }
    }
}

#[test]
fn historical_bare_identity_is_not_reassigned_to_a_namespaced_tool() {
    let input =
        json!([{"type":"function_call","call_id":"old-call","name":"read","arguments":"{}"}]);
    let mut chat: NvCreateChatCompletionRequest =
        request(namespace(false), input.clone()).try_into().unwrap();
    chat.normalize_responses_tools(true).unwrap();
    let ChatCompletionRequestMessage::Assistant(message) = &chat.inner.messages[0] else {
        panic!();
    };
    assert_eq!(
        message.tool_calls.as_ref().unwrap()[0].function.name,
        "read"
    );
    let mut tools = namespace(false);
    tools
        .as_array_mut()
        .unwrap()
        .push(json!({"type":"function","name":"read"}));
    let mut chat: NvCreateChatCompletionRequest = request(tools, input).try_into().unwrap();
    chat.normalize_responses_tools(true).unwrap();
    let ChatCompletionRequestMessage::Assistant(message) = &chat.inner.messages[0] else {
        panic!();
    };
    assert_eq!(
        message.tool_calls.as_ref().unwrap()[0].function.name,
        "read"
    );
}

#[test]
fn namespaced_unary_output_uses_leaf_name_and_namespace_and_echoes_deferral() {
    let response = request(namespace(true), json!("Read."));
    let output =
        unary_tool_response(&response_params(&response), "fs.read", json!({"path":"a"})).unwrap();
    let value = serde_json::to_value(output).unwrap();
    assert_eq!(value["output"][0]["type"], "function_call");
    assert_eq!(value["output"][0]["name"], "read");
    assert_eq!(value["output"][0]["namespace"], "fs");
    assert_eq!(value["tools"][0]["defer_loading"], true);
}

#[test]
fn custom_tool_unary_output_and_history_preserve_verbatim_freeform_payload() {
    let input = "*** Begin Patch\nUnicode: café 日本語\n\"quoted\" \\ backslash\n*** End Patch";
    let tools =
        json!([{"type":"namespace","name":"fs","tools":[{"type":"custom","name":"apply_patch"}]}]);
    let response = request(tools, json!("Apply the patch."));
    let output = unary_tool_response(
        &response_params(&response),
        "fs.apply_patch",
        json!({"input":input}),
    )
    .unwrap();
    let value = serde_json::to_value(output).unwrap();
    assert_eq!(value["output"][0]["type"], "custom_tool_call");
    assert_eq!(value["output"][0]["name"], "apply_patch");
    assert_eq!(value["output"][0]["namespace"], "fs");
    assert_eq!(value["output"][0]["input"], input);
    let mut replay = request(
        value["tools"].clone(),
        json!([
            value["output"][0].clone(),
            {"type":"custom_tool_call_output","call_id":"call-1","output":"Patch applied"},
            {"role":"user","content":"Continue."}
        ]),
    );
    replay.inner.tool_choice =
        Some(serde_json::from_value(json!({"type":"custom","name":"fs.apply_patch"})).unwrap());
    let mut chat: NvCreateChatCompletionRequest = replay.try_into().unwrap();
    chat.normalize_responses_tools(true).unwrap();
    let ChatCompletionRequestMessage::Assistant(message) = &chat.inner.messages[0] else {
        panic!();
    };
    assert_eq!(
        message.tool_calls.as_ref().unwrap()[0].function.name,
        "fs.apply_patch"
    );
    assert_eq!(
        custom_input(&message.tool_calls.as_ref().unwrap()[0].function.arguments).unwrap(),
        input
    );
    let rendered = formatter(TEMPLATE).render(&chat).unwrap();
    assert!(rendered.contains("<atem:parameter name=\"input\">*** Begin Patch"));
    assert!(rendered.contains("<|start|>tool fs.apply_patch<|message|>"));
    let fallback = serde_json::to_value(
        unary_tool_response(
            &response_params(&response),
            "fs.apply_patch",
            json!({"input":42}),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(fallback["output"][0]["input"], r#"{"input":42}"#);
}

#[test]
fn plain_functions_retain_the_existing_flat_prompt_view() {
    let response = request(
        json!([{"type":"function","name":"read","parameters":{"type":"object","properties":{},"additionalProperties":false},"strict":true}]),
        json!("Read."),
    );
    let chat: NvCreateChatCompletionRequest = response.try_into().unwrap();
    assert!(chat.native_template_tools().is_none());
    let rendered = formatter("{{ tools | tojson }}").render(&chat).unwrap();
    assert_eq!(
        serde_json::from_str::<Value>(&rendered).unwrap()[0]["function"]["strict"],
        true
    );
    assert!(
        serde_json::to_value(&chat)
            .unwrap()
            .get("responses_tools")
            .is_none()
    );
}

#[test]
fn responses_and_chat_accept_qualified_functions_but_reject_invalid_namespaces() {
    let chat: NvCreateChatCompletionRequest = request(namespace(false), json!("Read."))
        .try_into()
        .unwrap();
    crate::engines::ValidateRequest::validate(&chat).unwrap();
    let wire_chat: NvCreateChatCompletionRequest = serde_json::from_value(json!({"model":"/model",
        "messages":[{"role":"user","content":"Read."}],
        "tools":[{"type":"function","function":{"name":"fs.read"}}]
    }))
    .unwrap();
    crate::engines::ValidateRequest::validate(&wire_chat).unwrap();
    let mut invalid = namespace(false);
    invalid[0]["name"] = json!("bad namespace");
    let chat: NvCreateChatCompletionRequest = request(invalid, json!("Read.")).try_into().unwrap();
    assert!(crate::engines::ValidateRequest::validate(&chat).is_err());
}

#[test]
fn native_and_legacy_names_reach_muse_parser_with_verbatim_custom_input() {
    let input = "  *** Begin Patch\n+ café 日本語\n*** End Patch  ";
    let response = request(
        json!([{"type":"namespace","name":"fs","tools":[
            {"type":"custom","name":"apply_patch"}
        ]}]),
        json!("Apply the patch."),
    );
    for (native, name) in [(true, "fs.apply_patch"), (false, "apply_patch")] {
        let mut chat: NvCreateChatCompletionRequest = response.clone().try_into().unwrap();
        chat.normalize_responses_tools(native).unwrap();
        let tools =
            crate::preprocessor::tool_choice::convert_tools(chat.inner.tools.as_deref().unwrap());
        let raw = format!(
            "<|start|>assistant to={name}<|message|><atem:function_calls>\n<atem:invoke name=\"{name}\">\n<atem:parameter name=\"input\">{input}</atem:parameter>\n</atem:invoke>\n</atem:function_calls><|eot|>"
        );
        let (calls, _, _) =
            crate::protocols::openai::chat_completions::tool_parser_v2::parse_complete_unified(
                &raw,
                Some(&tools),
                "muse_spark",
            )
            .unwrap();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].function.name, name);
        assert_eq!(custom_input(&calls[0].function.arguments).unwrap(), input);
        let params = response_params(&response);
        let output = params
            .tool_output(
                "item-1".into(),
                "call-1".into(),
                name,
                &calls[0].function.arguments,
                OutputStatus::Completed,
            )
            .unwrap();
        assert_eq!(serde_json::to_value(output).unwrap()["input"], input);
    }
}

#[test]
fn python_adapter_preserves_native_catalog_and_engine_identities() {
    let input = json!([
        {"type":"function_call","call_id":"c1","namespace":"fs","name":"read","arguments":"{}"},
        {"type":"function_call_output","call_id":"c1","output":"ok"},
        {"role":"user","content":"Read again"}
    ]);
    let chat: NvCreateChatCompletionRequest = request(namespace(true), input).try_into().unwrap();
    let python = chat
        .python_chat_processor_request_json(&Default::default())
        .unwrap();
    let native = &python["responses_native_tools"];
    assert_eq!(native["template_tools"][0]["type"], "namespace");
    assert_eq!(native["template_tools"][0]["defer_loading"], true);
    assert_eq!(native["tools"][0]["function"]["name"], "fs.read");
    assert_eq!(
        native["messages"][0]["tool_calls"][0]["function"]["name"],
        "fs.read"
    );
    assert_eq!(python["tools"][0]["function"]["name"], "read");
    let wire = serde_json::to_value(&chat).unwrap();
    assert!(wire.get("responses_native_tools").is_none());
    let mut spoofed = wire;
    spoofed["responses_native_tools"] = native.clone();
    let decoded: NvCreateChatCompletionRequest = serde_json::from_value(spoofed).unwrap();
    assert!(
        decoded
            .python_chat_processor_request_json(&Default::default())
            .unwrap()
            .get("responses_native_tools")
            .is_none()
    );
}

#[test]
fn responses_tool_kinds_are_validated_before_function_conversion() {
    let function = json!({"type":"function","name":"run","parameters":{"type":"object"}});
    let custom = json!({"type":"custom","name":"run"});
    for (tools, choice) in [
        (
            json!([function.clone()]),
            json!({"type":"custom","name":"run"}),
        ),
        (
            json!([custom.clone()]),
            json!({"type":"function","name":"run"}),
        ),
        (json!([function.clone(), custom.clone()]), json!("auto")),
        (json!([custom.clone(), function.clone()]), json!("auto")),
        (
            json!([{"type":"namespace","name":"fs","description":"Files","tools":[function.clone(),custom.clone()]}]),
            json!("auto"),
        ),
    ] {
        let mut req = request(tools.clone(), json!("hi"));
        req.inner.tool_choice = Some(serde_json::from_value(choice.clone()).unwrap());
        let result = NvCreateChatCompletionRequest::try_from(req);
        assert!(
            result.is_err(),
            "invalid registry/choice accepted: {tools} {choice}"
        );
    }
    for (tools, choice) in [
        (
            json!([function.clone()]),
            json!({"type":"function","name":"run"}),
        ),
        (
            json!([custom.clone()]),
            json!({"type":"custom","name":"run"}),
        ),
        (
            json!([function.clone(),{"type":"namespace","name":"fs","description":"Files","tools":[custom.clone()]}]),
            json!({"type":"custom","name":"fs.run"}),
        ),
        (
            json!([{"type":"namespace","name":"fs","description":"Files","tools":[function]}, {"type":"namespace","name":"shell","description":"Shell","tools":[custom]}]),
            json!("auto"),
        ),
    ] {
        let mut req = request(tools, json!("hi"));
        req.inner.tool_choice = Some(serde_json::from_value(choice).unwrap());
        NvCreateChatCompletionRequest::try_from(req).unwrap();
    }
}

#[test]
fn named_tool_rendering_policy_matches_the_production_preprocessor() {
    use crate::{model_card::ModelDeploymentCard, preprocessor::OpenAIPreprocessor};
    let mut tools = namespace(true);
    tools
        .as_array_mut()
        .unwrap()
        .push(json!({"type":"function","name":"other","parameters":{"type":"object"}}));
    for parser in [None, Some("muse_spark_open")] {
        let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/data/sample-models/mock-llama-3.1-8b-instruct");
        let mut mdc = ModelDeploymentCard::load_from_disk(path, None).unwrap();
        mdc.runtime_config.tool_call_parser = parser.map(str::to_owned);
        let mut response = request(tools.clone(), json!("Read a file."));
        response.inner.tool_choice =
            Some(serde_json::from_value(json!({"type":"function","name":"fs.read"})).unwrap());
        let mut chat: NvCreateChatCompletionRequest = response.try_into().unwrap();
        chat.normalize_responses_tools(true).unwrap();
        let python = chat
            .python_chat_processor_request_json(&mdc.runtime_config)
            .unwrap();
        let spark = parser.is_some();
        assert_eq!(
            python["responses_native_tools"]["render_named_tool_eagerly"],
            spark
        );
        let tokenizer = mdc.tokenizer().unwrap();
        let preprocessor =
            OpenAIPreprocessor::new_with_parts(mdc, formatter(TEMPLATE), tokenizer).unwrap();
        let prompt = preprocessor.apply_template(&chat).unwrap().unwrap();
        assert_eq!(prompt.as_str().contains("\"path\""), spark);
        assert_eq!(prompt.as_str().contains("\"name\": \"other\""), !spark);
    }
}

/// Function tools declared with an omitted, null, or explicit description,
/// plus a namespace whose member function omits it.
fn description_matrix_tools() -> Value {
    json!([
        {"type":"function","name":"fn0","parameters":{"type":"object"}},
        {"type":"function","name":"fn1","description":null,"parameters":{"type":"object"}},
        {"type":"function","name":"fn2","description":"fixture","parameters":{"type":"object"}},
        {"type":"namespace","name":"fs","description":"Files","tools":[
            {"type":"function","name":"read","parameters":{"type":"object"}}]}
    ])
}

/// Presence-aware: indexing a missing key also yields `Null`, so check the key.
fn assert_echoed_tool_descriptions(tools: &Value) {
    let description = |tool: &Value| {
        let tool = tool.as_object().unwrap();
        assert_eq!(tool["strict"], true, "{tool:?}");
        assert!(tool.contains_key("description"), "missing key: {tool:?}");
        tool["description"].clone()
    };
    assert_eq!(description(&tools[0]), Value::Null);
    assert_eq!(description(&tools[1]), Value::Null);
    assert_eq!(description(&tools[2]), "fixture");
    assert_eq!(tools[3]["description"], "Files");
    assert_eq!(description(&tools[3]["tools"][0]), Value::Null);
}

#[test]
fn unary_response_echoes_null_function_tool_descriptions() {
    let params = response_params(&request(description_matrix_tools(), json!("Hi")));
    let chat: NvCreateChatCompletionResponse = serde_json::from_value(json!({
        "id":"chat-1", "object":"chat.completion", "created":0, "model":"/model",
        "choices":[{"index":0,"message":{"role":"assistant","content":"ok"},
            "finish_reason":"stop","logprobs":null}]
    }))
    .unwrap();
    let response = chat_completion_to_response(chat, &params, None).unwrap();
    assert_echoed_tool_descriptions(&serde_json::to_value(&response).unwrap()["tools"]);
}