"tests/vscode:/vscode.git/clone" did not exist on "a90ada153d8a68d8037f2818d6c5dac42f6f614d"
test_preprocessor.rs 25.6 KB
Newer Older
1
2
// SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
3

4
use async_trait::async_trait;
5
6
use dynamo_async_openai::types::ChatCompletionToolChoiceOption;
use dynamo_async_openai::types::CreateChatCompletionRequest;
7
8
9
10
11
use dynamo_async_openai::types::{
    ChatChoiceStream, ChatCompletionStreamResponseDelta, FinishReason as OAIFinishReason, Role,
};
use dynamo_llm::preprocessor::{
    ANNOTATION_POSSIBLE_TOOL_CALL, PossibleToolCallAnnotation, apply_tool_calling_jail_internal,
12
13
14
15
    maybe_enable_tool_call,
};
use dynamo_llm::protocols::openai::chat_completions::{
    NvCreateChatCompletionRequest, NvCreateChatCompletionStreamResponse,
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
};
use dynamo_parsers::tool_calling::parsers::detect_tool_call_start;
use dynamo_runtime::pipeline::ResponseStream;
use dynamo_runtime::protocols::annotated::Annotated;
use futures::stream::{self, StreamExt};
use std::sync::Arc;

#[allow(deprecated)]
// Helper function to create a mock chat response chunk
fn create_mock_response_chunk(
    content: String,
    index: u32,
) -> Annotated<NvCreateChatCompletionStreamResponse> {
    let choice = ChatChoiceStream {
        index,
        delta: ChatCompletionStreamResponseDelta {
            role: Some(Role::Assistant),
            content: Some(content),
            tool_calls: None,
            function_call: None,
            refusal: None,
            reasoning_content: None,
        },
        finish_reason: None,
        logprobs: None,
    };

    let response = NvCreateChatCompletionStreamResponse {
        id: "test-id".to_string(),
        choices: vec![choice],
        created: 1234567890,
        model: "test-model".to_string(),
        system_fingerprint: Some("test-fingerprint".to_string()),
        object: "chat.completion.chunk".to_string(),
        usage: None,
        service_tier: None,
    };

    Annotated {
        data: Some(response),
        id: None,
        event: None,
        comment: None,
    }
}

#[allow(deprecated)]
// Helper function to create a final response chunk with finish reason
fn create_final_response_chunk(index: u32) -> Annotated<NvCreateChatCompletionStreamResponse> {
    let choice = ChatChoiceStream {
        index,
        delta: ChatCompletionStreamResponseDelta {
            role: None,
            content: None,
            tool_calls: None,
            function_call: None,
            refusal: None,
            reasoning_content: None,
        },
        finish_reason: Some(OAIFinishReason::Stop),
        logprobs: None,
    };

    let response = NvCreateChatCompletionStreamResponse {
        id: "test-id".to_string(),
        choices: vec![choice],
        created: 1234567890,
        model: "test-model".to_string(),
        system_fingerprint: Some("test-fingerprint".to_string()),
        object: "chat.completion.chunk".to_string(),
        usage: None,
        service_tier: None,
    };

    Annotated {
        data: Some(response),
        id: None,
        event: None,
        comment: None,
    }
}

// Mock async engine context for testing
#[derive(Debug)]
struct MockAsyncEngineContext {
    id: String,
    stopped: std::sync::atomic::AtomicBool,
}

impl MockAsyncEngineContext {
    fn new(id: String) -> Self {
        Self {
            id,
            stopped: std::sync::atomic::AtomicBool::new(false),
        }
    }
}

#[async_trait]
impl dynamo_runtime::pipeline::AsyncEngineContext for MockAsyncEngineContext {
    fn id(&self) -> &str {
        &self.id
    }

    fn stop(&self) {
        self.stopped
            .store(true, std::sync::atomic::Ordering::Relaxed);
    }

    fn stop_generating(&self) {
        self.stopped
            .store(true, std::sync::atomic::Ordering::Relaxed);
    }

    fn kill(&self) {
        self.stopped
            .store(true, std::sync::atomic::Ordering::Relaxed);
    }

    fn is_stopped(&self) -> bool {
        self.stopped.load(std::sync::atomic::Ordering::Relaxed)
    }

    fn is_killed(&self) -> bool {
        self.stopped.load(std::sync::atomic::Ordering::Relaxed)
    }

    async fn stopped(&self) {
        // No-op for testing
    }

    async fn killed(&self) {
        // No-op for testing
    }

    fn link_child(&self, _: Arc<dyn dynamo_runtime::pipeline::AsyncEngineContext>) {
        // No-op for testing
    }
}

#[tokio::test]
async fn test_apply_tool_calling_jail_internal_with_tool_call_detection() {
    // Create a stream with tool call content that SHOULD trigger jailing
    let mock_context = Arc::new(MockAsyncEngineContext::new("test-request-id".to_string()));

    // Create chunks that represent a tool call being generated
    let chunks = vec![
        create_mock_response_chunk("<TOOLCALL>".to_string(), 0),
        create_mock_response_chunk("[{\"name\": \"get_weather\", ".to_string(), 0),
        create_mock_response_chunk(
            "\"arguments\": {\"location\": \"San Francisco\"}}]".to_string(),
            0,
        ),
        create_mock_response_chunk("</TOOLCALL>".to_string(), 0),
    ];

    let input_stream = stream::iter(chunks);
    let response_stream = ResponseStream::new(Box::pin(input_stream), mock_context.clone());

    // Apply the jail with nemotron_deci parser - should trigger jailing on first chunk
    let jailed_stream =
177
        apply_tool_calling_jail_internal(response_stream, Some("nemotron_deci".to_string())).await;
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

    // Collect all results
    let results: Vec<_> = jailed_stream.collect().await;

    // Verify that jailing was triggered
    assert!(!results.is_empty(), "Should have some results");

    // Results should be of length 1
    // First Stream: [{"name": "get_weather", "arguments":"{"location": "San Francisco"}}]"

    assert_eq!(results.len(), 1);
    assert!(
        results[0].data.as_ref().unwrap().choices[0]
            .delta
            .tool_calls
            .is_some()
    );
    let tools = results[0].data.as_ref().unwrap().choices[0]
        .delta
        .tool_calls
        .as_ref()
        .unwrap();
    assert_eq!(tools.len(), 1);
    let name = tools[0].function.as_ref().unwrap().name.as_ref().unwrap();
    let arguments = serde_json::from_str::<serde_json::Value>(
        tools[0]
            .function
            .as_ref()
            .unwrap()
            .arguments
            .as_ref()
            .unwrap(),
    )
    .unwrap();
    assert_eq!(name, "get_weather");
    assert_eq!(arguments["location"], "San Francisco");
}

#[tokio::test]
async fn test_apply_tool_calling_jail_internal_no_tool_calls() {
    // Create a stream with regular content that should NOT trigger jailing
    let mock_context = Arc::new(MockAsyncEngineContext::new("test-request-id-2".to_string()));

    let chunks = vec![
        create_mock_response_chunk("Hello, ".to_string(), 0),
        create_mock_response_chunk("how can I ".to_string(), 0),
        create_mock_response_chunk("help you today?".to_string(), 0),
        create_final_response_chunk(0),
    ];

    let input_stream = stream::iter(chunks);
    let response_stream = ResponseStream::new(Box::pin(input_stream), mock_context.clone());

    // Apply the jail with nemotron_deci parser - regular text should NOT be jailed
    let jailed_stream =
233
        apply_tool_calling_jail_internal(response_stream, Some("nemotron_deci".to_string())).await;
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

    // Collect all results
    let results: Vec<_> = jailed_stream.collect().await;

    // Should have results and they should NOT be jailed (content should be preserved)
    assert!(!results.is_empty(), "Should have results");
    assert_eq!(results.len(), 4, "Should have all 4 chunks");

    // Verify that content is NOT jailed - first few chunks should have their original content
    for (i, result) in results.iter().take(3).enumerate() {
        if let Some(ref response_data) = result.data {
            let expected_content = match i {
                0 => "Hello, ",
                1 => "how can I ",
                2 => "help you today?",
                _ => unreachable!(),
            };
            assert_eq!(
                response_data.choices[0].delta.content.as_deref(),
                Some(expected_content),
                "Chunk {} should have original content, not be jailed",
                i
            );
            // Should NOT have annotation events for regular content
            assert!(
                result.event.is_none(),
                "Regular content should not have annotation events"
            );
        }
    }

    // Last chunk should be the final response with finish reason
    if let Some(last_result) = results.last()
        && let Some(ref response_data) = last_result.data
    {
        assert_eq!(
            response_data.choices[0].finish_reason,
            Some(OAIFinishReason::Stop)
        );
    }
}

#[tokio::test]
async fn test_apply_tool_calling_jail_internal_with_empty_stream() {
    let mock_context = Arc::new(MockAsyncEngineContext::new("test-request-id-3".to_string()));

    let chunks: Vec<Annotated<NvCreateChatCompletionStreamResponse>> = vec![];
    let input_stream = stream::iter(chunks);
    let response_stream = ResponseStream::new(Box::pin(input_stream), mock_context.clone());

284
    let jailed_stream = apply_tool_calling_jail_internal(response_stream, None).await;
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
    let results: Vec<_> = jailed_stream.collect().await;

    assert!(results.is_empty(), "Empty stream should produce no results");
}

#[tokio::test]
async fn test_apply_tool_calling_jail_internal_with_different_parsers() {
    let mock_context = Arc::new(MockAsyncEngineContext::new("test-request-id-4".to_string()));

    // Test with hermes parser format
    let chunks = vec![
        create_mock_response_chunk("<tool_call>".to_string(), 0),
        create_mock_response_chunk(
            "{\"name\": \"get_weather\", \"arguments\": {\"location\": \"Tokyo\"}}".to_string(),
            0,
        ),
        create_mock_response_chunk("</tool_call>".to_string(), 0),
    ];

    let input_stream = stream::iter(chunks);
    let response_stream = ResponseStream::new(Box::pin(input_stream), mock_context.clone());

    let jailed_stream =
308
        apply_tool_calling_jail_internal(response_stream, Some("hermes".to_string())).await;
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
    let results: Vec<_> = jailed_stream.collect().await;

    assert!(!results.is_empty(), "Should have results for hermes parser");
}

#[tokio::test]
async fn test_detect_tool_call_start_different_parsers() {
    // Test nemotron_deci parser
    assert!(detect_tool_call_start("<TOOLCALL>", Some("nemotron_deci")).unwrap());
    assert!(!detect_tool_call_start("Hello world", Some("nemotron_deci")).unwrap());
    assert!(!detect_tool_call_start("<tool_call>", Some("nemotron_deci")).unwrap()); // Wrong format

    // Test hermes parser - now also detects JSON patterns
    assert!(detect_tool_call_start("<tool_call>", Some("hermes")).unwrap());
    assert!(detect_tool_call_start("{\"name\": \"test\"}", Some("hermes")).unwrap()); // JSON detection
    assert!(!detect_tool_call_start("Hello world", Some("hermes")).unwrap());
    assert!(!detect_tool_call_start("<TOOLCALL>", Some("hermes")).unwrap()); // Wrong format

    // Test phi4 parser
    assert!(detect_tool_call_start("functools[", Some("phi4")).unwrap());
    assert!(detect_tool_call_start("{\"name\": \"test\"}", Some("phi4")).unwrap()); // JSON detection
    assert!(!detect_tool_call_start("Hello world", Some("phi4")).unwrap());

    // Test mistral parser
    assert!(detect_tool_call_start("[{", Some("mistral")).unwrap());
    assert!(detect_tool_call_start("[TOOL_CALLS]", Some("mistral")).unwrap());
    assert!(!detect_tool_call_start("Hello world", Some("mistral")).unwrap());

    // Test llama3_json parser
    assert!(detect_tool_call_start("<|python_tag|>", Some("llama3_json")).unwrap());
    assert!(detect_tool_call_start("{\"name\": \"test\"}", Some("llama3_json")).unwrap()); // JSON detection

    // Test default parser (should behave like nemotron_deci)
    assert!(detect_tool_call_start("<TOOLCALL>", None).unwrap());
    assert!(detect_tool_call_start("{\"name\": \"test\"}", None).unwrap()); // JSON detection
    assert!(!detect_tool_call_start("Hello world", None).unwrap());
}

#[tokio::test]
async fn test_apply_tool_calling_jail_internal_hermes_parser() {
    // Test with hermes parser format
    let mock_context = Arc::new(MockAsyncEngineContext::new(
        "test-request-id-hermes".to_string(),
    ));

    let chunks = vec![
        create_mock_response_chunk("I'll help you with that. ".to_string(), 0),
        create_mock_response_chunk("<tool_call>".to_string(), 0), // This should trigger jailing
        create_mock_response_chunk(
            "{\"name\": \"get_weather\", \"arguments\": {\"location\": \"Tokyo\"}}".to_string(),
            0,
        ),
        create_mock_response_chunk("</tool_call>".to_string(), 0),
    ];

    let input_stream = stream::iter(chunks);
    let response_stream = ResponseStream::new(Box::pin(input_stream), mock_context.clone());

    let jailed_stream =
368
        apply_tool_calling_jail_internal(response_stream, Some("hermes".to_string())).await;
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
    let results: Vec<_> = jailed_stream.collect().await;

    assert!(!results.is_empty(), "Should have results for hermes parser");

    // Results should be of length 2
    // First Stream : I'll help you with that.
    // Second Stream : [{"name": "get_weather", "arguments":"{"location": "Tokyo"}}]" (jailed)
    assert_eq!(results.len(), 2);
    assert_eq!(
        results[0].data.as_ref().unwrap().choices[0].delta.content,
        Some("I'll help you with that. ".to_string())
    );
    assert!(
        results[1].data.as_ref().unwrap().choices[0]
            .delta
            .tool_calls
            .is_some()
    );
    let tools = results[1].data.as_ref().unwrap().choices[0]
        .delta
        .tool_calls
        .as_ref()
        .unwrap();
    assert_eq!(tools.len(), 1);
    let name = tools[0].function.as_ref().unwrap().name.as_ref().unwrap();
    let arguments = serde_json::from_str::<serde_json::Value>(
        tools[0]
            .function
            .as_ref()
            .unwrap()
            .arguments
            .as_ref()
            .unwrap(),
    )
    .unwrap();
    assert_eq!(name, "get_weather");
    assert_eq!(arguments["location"], "Tokyo");
}

#[tokio::test]
async fn test_possible_tool_call_annotation_serialization() {
    let annotation = PossibleToolCallAnnotation {
        possible_tokens: 5,
        possible_content: "test content".to_string(),
        parser_used: Some("nemotron_deci".to_string()),
    };

    let annotated_result = annotation.to_annotation::<NvCreateChatCompletionStreamResponse>();
    assert!(
        annotated_result.is_ok(),
        "Should be able to create annotation"
    );

    let annotated = annotated_result.unwrap();
    assert_eq!(
        annotated.event,
        Some(ANNOTATION_POSSIBLE_TOOL_CALL.to_string())
    );
    assert!(annotated.comment.is_some(), "Should have comment");

    // Test deserialization
    let parsed_annotation = PossibleToolCallAnnotation::from_annotation(&annotated);
    assert!(
        parsed_annotation.is_ok(),
        "Should be able to parse annotation"
    );

    let parsed = parsed_annotation.unwrap();
    assert!(parsed.is_some(), "Should have parsed annotation");

    let parsed = parsed.unwrap();
    assert_eq!(parsed.possible_tokens, 5);
    assert_eq!(parsed.possible_content, "test content");
    assert_eq!(parsed.parser_used, Some("nemotron_deci".to_string()));
}

#[tokio::test]
async fn test_apply_tool_calling_jail_internal_mistral_parser_with_no_tool_call_start_token() {
    let mock_context = Arc::new(MockAsyncEngineContext::new(
        "test-request-id-mistral".to_string(),
    ));

    let chunks = vec![
        create_mock_response_chunk("Hey How".to_string(), 0),
        create_mock_response_chunk("are you? ".to_string(), 0),
        create_mock_response_chunk(r#"[{"name": "get_weather", "arguments":"#.to_string(), 0),
        create_mock_response_chunk(
            r#"{"location": "San Francisco", "unit": "fahrenheit"}}]"#.to_string(),
            0,
        ),
        create_final_response_chunk(0),
    ];

    let input_stream = stream::iter(chunks);
    let response_stream = ResponseStream::new(Box::pin(input_stream), mock_context.clone());

    let jailed_stream =
466
        apply_tool_calling_jail_internal(response_stream, Some("mistral".to_string())).await;
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

    let results: Vec<_> = jailed_stream.collect().await;

    assert!(
        !results.is_empty(),
        "Should have results for mistral parser"
    );
    // Results should be of length 4
    // First Stream : Hey How
    // Second Stream : are you?
    // Third Stream : None (final response chunk)
    // Fourth Stream : [{"name": "get_weather", "arguments":"{"location": "San Francisco", "unit": "fahrenheit"}}]" (jailed)
    assert_eq!(results.len(), 4);

    // First two normal text
    assert_eq!(
        results[0].data.as_ref().unwrap().choices[0].delta.content,
        Some("Hey How".to_string())
    );
    assert_eq!(
        results[1].data.as_ref().unwrap().choices[0].delta.content,
        Some("are you? ".to_string())
    );
    assert_eq!(
        results[2].data.as_ref().unwrap().choices[0].delta.content,
        None
    );

    // Final tool call
    assert!(
        results[3].data.as_ref().unwrap().choices[0]
            .delta
            .tool_calls
            .is_some()
    );
    let tools = results[3].data.as_ref().unwrap().choices[0]
        .delta
        .tool_calls
        .as_ref()
        .unwrap();
    assert_eq!(tools.len(), 1);
    let name = tools[0].function.as_ref().unwrap().name.as_ref().unwrap();
    let arguments = serde_json::from_str::<serde_json::Value>(
        tools[0]
            .function
            .as_ref()
            .unwrap()
            .arguments
            .as_ref()
            .unwrap(),
    )
    .unwrap();
    assert_eq!(name, "get_weather");
    assert_eq!(arguments["location"], "San Francisco");
    assert_eq!(arguments["unit"], "fahrenheit");
}

#[tokio::test]
async fn test_apply_tool_calling_jail_internal_mistral_parser_with_false_positive_tool_start() {
    let mock_context = Arc::new(MockAsyncEngineContext::new(
        "test-request-id-mistral".to_string(),
    ));

    let chunks = vec![
        create_mock_response_chunk("Hey How".to_string(), 0),
        create_mock_response_chunk("are { you? ".to_string(), 0),
        create_final_response_chunk(0),
    ];

    let input_stream = stream::iter(chunks);
    let response_stream = ResponseStream::new(Box::pin(input_stream), mock_context.clone());

    let jailed_stream =
540
        apply_tool_calling_jail_internal(response_stream, Some("mistral".to_string())).await;
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
    let results: Vec<_> = jailed_stream.collect().await;

    assert!(
        !results.is_empty(),
        "Should have results for mistral parser"
    );
    // Results should be of length 3
    // First Stream : Hey How
    // Second Stream : None (final response chunk)
    // Third Stream : are { you? (normal text field from tool-call-parse-aggregate)
    assert_eq!(results.len(), 3);
    assert_eq!(
        results[0].data.as_ref().unwrap().choices[0].delta.content,
        Some("Hey How".to_string())
    );
    assert_eq!(
        results[1].data.as_ref().unwrap().choices[0].delta.content,
        None
    );
    assert_eq!(
        results[2].data.as_ref().unwrap().choices[0].delta.content,
        Some("are { you?".to_string())
    );
}

#[tokio::test]
async fn test_apply_tool_calling_jail_internal_mistral_parser_with_false_positive_tool_start_and_tool_call_token()
 {
    let mock_context = Arc::new(MockAsyncEngineContext::new(
        "test-request-id-mistral".to_string(),
    ));

    let chunks = vec![
        create_mock_response_chunk("Hey How".to_string(), 0),
        create_mock_response_chunk("are { you? ".to_string(), 0),
        create_mock_response_chunk(
            r#"[TOOL_CALLS][{"name": "get_weather", "arguments":"#.to_string(),
            0,
        ),
        create_mock_response_chunk(
            r#"{"location": "San Francisco", "unit": "fahrenheit"}}]"#.to_string(),
            0,
        ),
        create_final_response_chunk(0),
    ];

    let input_stream = stream::iter(chunks);
    let response_stream = ResponseStream::new(Box::pin(input_stream), mock_context.clone());

    let jailed_stream =
591
        apply_tool_calling_jail_internal(response_stream, Some("mistral".to_string())).await;
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
    let results: Vec<_> = jailed_stream.collect().await;

    assert!(
        !results.is_empty(),
        "Should have results for mistral parser"
    );

    // Results should be of length 3
    // First Stream : Hey How
    // Second Stream : None (final response chunk)
    // Third Stream : Content: are { you? , Tool Calls: [{"name": "get_weather", "arguments":"{"location": "San Francisco", "unit": "fahrenheit"}}]"
    assert_eq!(results.len(), 3);
    assert_eq!(
        results[0].data.as_ref().unwrap().choices[0].delta.content,
        Some("Hey How".to_string())
    );
    assert_eq!(
        results[1].data.as_ref().unwrap().choices[0].delta.content,
        None
    );
    assert_eq!(
        results[2].data.as_ref().unwrap().choices[0].delta.content,
        Some("are { you?".to_string())
    );
    assert!(
        results[2].data.as_ref().unwrap().choices[0]
            .delta
            .tool_calls
            .is_some()
    );
    let tools = results[2].data.as_ref().unwrap().choices[0]
        .delta
        .tool_calls
        .as_ref()
        .unwrap();
    assert_eq!(tools.len(), 1);
    let name = tools[0].function.as_ref().unwrap().name.as_ref().unwrap();
    let arguments = serde_json::from_str::<serde_json::Value>(
        tools[0]
            .function
            .as_ref()
            .unwrap()
            .arguments
            .as_ref()
            .unwrap(),
    )
    .unwrap();
    assert_eq!(name, "get_weather");
    assert_eq!(arguments["location"], "San Francisco");
    assert_eq!(arguments["unit"], "fahrenheit");
}
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716

#[tokio::test]
async fn test_tool_calling_jail_internal_with_harmony_parser() {
    let mock_context = Arc::new(MockAsyncEngineContext::new(
        "test-request-id-harmony".to_string(),
    ));

    // Harmony Format:
    // <|channel|>analysis<|message|>Need to use function get_current_weather.<|end|>
    // <|start|>assistant<|channel|>commentary to=functions.get_current_weather <|constrain|>json
    // <|message|>{"location":"San Francisco"}<|call|>
    let chunks = vec![
        create_mock_response_chunk(
            "<|channel|>analysis<|message|>Need to use function get_current_weather.<|end|>"
                .to_string(),
            0,
        ),
        create_mock_response_chunk("<|start|>".to_string(), 0),
        create_mock_response_chunk("assistant".to_string(), 0),
        create_mock_response_chunk("<|channel|>".to_string(), 0),
        create_mock_response_chunk(
            "commentary to=functions.get_current_weather <|constrain|>json".to_string(),
            0,
        ),
        create_mock_response_chunk(
            "<|message|>{\"location\":\"San Francisco\"}<|call|>".to_string(),
            0,
        ),
        create_final_response_chunk(0),
    ];

    let input_stream = stream::iter(chunks);
    let response_stream = ResponseStream::new(Box::pin(input_stream), mock_context.clone());

    let jailed_stream =
        apply_tool_calling_jail_internal(response_stream, Some("harmony".to_string())).await;
    let results: Vec<_> = jailed_stream.collect().await;

    assert!(
        !results.is_empty(),
        "Should have results for harmony parser"
    );

    assert_eq!(results.len(), 2);
    assert_eq!(
        results[1].data.as_ref().unwrap().choices[0].delta.content,
        Some("Need to use function get_current_weather.".to_string())
    );
    assert!(
        results[1].data.as_ref().unwrap().choices[0]
            .delta
            .tool_calls
            .is_some()
    );
    let tools = results[1].data.as_ref().unwrap().choices[0]
        .delta
        .tool_calls
        .as_ref()
        .unwrap();
    assert_eq!(tools.len(), 1);
    let name = tools[0].function.as_ref().unwrap().name.as_ref().unwrap();
    let arguments = serde_json::from_str::<serde_json::Value>(
        tools[0]
            .function
            .as_ref()
            .unwrap()
            .arguments
            .as_ref()
            .unwrap(),
    )
    .unwrap();
    assert_eq!(name, "get_current_weather");
    assert_eq!(arguments["location"], "San Francisco");
}
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763

#[test]
fn test_enable_tool_call() {
    let request = NvCreateChatCompletionRequest {
        inner: CreateChatCompletionRequest {
            tool_choice: Some(ChatCompletionToolChoiceOption::Auto),
            ..Default::default()
        },
        common: Default::default(),
        nvext: None,
        chat_template_args: None,
    };
    assert!(maybe_enable_tool_call(Some("nemotron_deci"), &request));

    let request = NvCreateChatCompletionRequest {
        inner: CreateChatCompletionRequest {
            tool_choice: Some(ChatCompletionToolChoiceOption::None),
            ..Default::default()
        },
        common: Default::default(),
        nvext: None,
        chat_template_args: None,
    };
    assert!(!maybe_enable_tool_call(Some("nemotron_deci"), &request));

    let request = NvCreateChatCompletionRequest {
        inner: CreateChatCompletionRequest {
            tool_choice: Some(ChatCompletionToolChoiceOption::Required),
            ..Default::default()
        },
        common: Default::default(),
        nvext: None,
        chat_template_args: None,
    };
    assert!(maybe_enable_tool_call(Some("nemotron_deci"), &request));

    let request = NvCreateChatCompletionRequest {
        inner: CreateChatCompletionRequest {
            tool_choice: Some(ChatCompletionToolChoiceOption::Auto),
            ..Default::default()
        },
        common: Default::default(),
        nvext: None,
        chat_template_args: None,
    };
    assert!(!maybe_enable_tool_call(None, &request));
}