jail.rs 54.8 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
Ryan Olson's avatar
Ryan Olson committed
2
3
4
// SPDX-License-Identifier: Apache-2.0

use async_stream::stream;
5
use dynamo_protocols::types::{
6
    ChatChoiceLogprobs, ChatChoiceStream, ChatCompletionMessageToolCallChunk,
7
    ChatCompletionStreamResponseDelta, FinishReason, FunctionCallStream, FunctionType, Role,
Ryan Olson's avatar
Ryan Olson committed
8
9
10
};

use dynamo_parsers::tool_calling::parsers::get_tool_parser_map;
11
12
13
use dynamo_parsers::tool_calling::{
    detect_tool_call_start, find_tool_call_end_position, try_tool_call_parse_aggregate,
};
Ryan Olson's avatar
Ryan Olson committed
14
15
use dynamo_runtime::protocols::annotated::Annotated;
use futures::{Stream, StreamExt};
16
use std::collections::HashMap;
17
use uuid::Uuid;
Ryan Olson's avatar
Ryan Olson committed
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

use crate::utils::{MarkerMatcher, MatchResult};

use super::NvCreateChatCompletionStreamResponse;

/// Represents what a choice wants to emit after processing content
#[derive(Debug, Clone)]
pub enum ChoiceEmission {
    /// Pass through content unchanged (choice is not jailed)
    PassThrough(ChatChoiceStream),
    /// Emit parsed tool calls (choice finished jailing with tool calls)
    ToolCall(ChatChoiceStream),
    /// Emit accumulated content (choice finished jailing without tool calls)
    Content(ChatChoiceStream),
    /// Emit trailing content after tool call end (choice has trailing after unjail)
    Trailing(ChatChoiceStream),
}

impl ChoiceEmission {
    /// Extract the ChatChoiceStream from any emission type
    pub fn into_choice(self) -> ChatChoiceStream {
        match self {
            ChoiceEmission::PassThrough(choice) => choice,
            ChoiceEmission::ToolCall(choice) => choice,
            ChoiceEmission::Content(choice) => choice,
            ChoiceEmission::Trailing(choice) => choice,
        }
    }

    /// Get the choice index
    pub fn index(&self) -> u32 {
        match self {
            ChoiceEmission::PassThrough(choice) => choice.index,
            ChoiceEmission::ToolCall(choice) => choice.index,
            ChoiceEmission::Content(choice) => choice.index,
            ChoiceEmission::Trailing(choice) => choice.index,
        }
    }
56
57
58
59
60
61
62
63
64
65

    /// Get mutable access to the underlying choice.
    fn choice_mut(&mut self) -> &mut ChatChoiceStream {
        match self {
            ChoiceEmission::PassThrough(choice) => choice,
            ChoiceEmission::ToolCall(choice) => choice,
            ChoiceEmission::Content(choice) => choice,
            ChoiceEmission::Trailing(choice) => choice,
        }
    }
Ryan Olson's avatar
Ryan Olson committed
66
67
68
69
70
71
72
73
74
75
}

/// Configuration for jail detection and parsing
#[derive(Debug, Clone)]
pub struct JailConfig<'a> {
    pub jail_start_sequences: &'a [String],
    pub jail_end_sequences: &'a [String],
    pub tool_call_parser: Option<&'a str>,
}

76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/// Jail activation mode
#[derive(Debug, Clone, PartialEq)]
pub enum JailMode {
    /// Traditional: wait for start marker, then jail
    MarkerBased,
    /// Immediate: start jailed from first token (for tool_choice)
    Immediate { format: ToolChoiceFormat },
}

/// Format for tool_choice immediate jail mode
#[derive(Debug, Clone, PartialEq)]
pub enum ToolChoiceFormat {
    /// tool_choice=named: expect single object {"location": "Paris", ...}
    SingleObject { tool_name: String },
    /// tool_choice=required: expect array [{name:"search", parameters:{...}}, ...]
    ArrayOfTools,
}

Ryan Olson's avatar
Ryan Olson committed
94
95
96
97
98
99
100
101
102
103
104
/// State tracking for an individual choice during jail processing
#[derive(Debug, Clone)]
struct ChoiceJailState {
    /// The choice index (0, 1, 2, ...)
    index: u32,
    /// Whether this choice is currently jailed
    is_jailed: bool,
    /// Accumulated content for this choice while jailed
    accumulated_content: String,
    /// Buffer for partial marker matches across chunks
    partial_match_buffer: String,
105
106
    /// Stream finish reason
    stream_finish_reason: Option<FinishReason>,
107
108
    /// Number of tool calls already emitted for this choice
    emitted_tool_calls_count: usize,
109
110
    /// Reasoning content collected while waiting for a suitable emission.
    pending_reasoning_content: Option<String>,
Ryan Olson's avatar
Ryan Olson committed
111
112
}

113
114
115
116
117
118
fn create_choice_stream(
    index: u32,
    role: Option<Role>,
    content: &str,
    tool_calls: Option<Vec<ChatCompletionMessageToolCallChunk>>,
    finish_reason: Option<FinishReason>,
119
    stop_reason: Option<dynamo_protocols::types::StopReason>,
120
121
122
123
124
125
126
    logprobs: Option<ChatChoiceLogprobs>,
) -> ChatChoiceStream {
    #[allow(deprecated)]
    ChatChoiceStream {
        index,
        delta: ChatCompletionStreamResponseDelta {
            role,
127
128
129
            content: Some(dynamo_protocols::types::ChatCompletionMessageContent::Text(
                content.to_string(),
            )),
130
131
132
133
134
135
            tool_calls,
            function_call: None,
            refusal: None,
            reasoning_content: None,
        },
        finish_reason,
136
        stop_reason,
137
138
139
140
        logprobs,
    }
}

Ryan Olson's avatar
Ryan Olson committed
141
142
impl ChoiceJailState {
    /// Create a new jail state for a choice
143
    fn new(index: u32, starts_jailed: bool) -> Self {
Ryan Olson's avatar
Ryan Olson committed
144
145
        Self {
            index,
146
            is_jailed: starts_jailed,
Ryan Olson's avatar
Ryan Olson committed
147
148
            accumulated_content: String::new(),
            partial_match_buffer: String::new(),
149
            stream_finish_reason: None,
150
            emitted_tool_calls_count: 0,
151
            pending_reasoning_content: None,
Ryan Olson's avatar
Ryan Olson committed
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
        }
    }

    /// Add content to this choice's accumulation
    fn accumulate(&mut self, content: &str) {
        if self.is_jailed {
            self.accumulated_content.push_str(content);
        }
    }

    /// End jailing and return the accumulated content
    fn end_jail(&mut self) -> String {
        self.is_jailed = false;
        std::mem::take(&mut self.accumulated_content)
    }

    /// Process incoming content and return what should be emitted (if anything)
    async fn process_content(
        &mut self,
        choice: &ChatChoiceStream,
        content: &str,
        jail_stream: &JailedStream,
    ) -> Vec<ChoiceEmission> {
        let mut emissions = Vec::new();
        if !self.is_jailed {
            // Use the marker matcher to detect complete/partial markers
178
            let match_result = jail_stream
Ryan Olson's avatar
Ryan Olson committed
179
                .marker_matcher
180
181
182
                .process_chunk(content, &self.partial_match_buffer);

            match match_result {
Ryan Olson's avatar
Ryan Olson committed
183
184
185
186
187
188
189
190
191
                MatchResult::Complete {
                    prefix,
                    marker,
                    suffix,
                    ..
                } => {
                    // Emit prefix if any
                    if !prefix.is_empty() {
                        #[allow(deprecated)]
192
193
194
195
196
                        let prefix_choice = create_choice_stream(
                            choice.index,
                            choice.delta.role,
                            &prefix,
                            None,
197
                            choice.finish_reason,
198
                            None,
199
200
                            choice.logprobs.clone(),
                        );
Ryan Olson's avatar
Ryan Olson committed
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
                        emissions.push(ChoiceEmission::PassThrough(prefix_choice));
                    }

                    // Build the potential full content
                    let full_content = format!("{}{}", marker, suffix);

                    // Check if this already contains the end marker
                    let (should_end, split_pos) = jail_stream.should_end_jail(&full_content).await;

                    if should_end {
                        // Complete tool call found in this chunk
                        let (jailed_part, trailing_part) = full_content.split_at(split_pos);

                        // Create the tool call choice
                        let tool_choice = jail_stream
216
217
218
219
220
221
                            .create_tool_call_choice(
                                choice.index,
                                jailed_part,
                                choice,
                                self.emitted_tool_calls_count,
                            )
Ryan Olson's avatar
Ryan Olson committed
222
223
224
                            .await;

                        if tool_choice.delta.tool_calls.is_some() {
225
226
227
                            if let Some(ref tool_calls) = tool_choice.delta.tool_calls {
                                self.emitted_tool_calls_count += tool_calls.len();
                            }
Ryan Olson's avatar
Ryan Olson committed
228
229
230
231
232
233
234
235
                            emissions.push(ChoiceEmission::ToolCall(tool_choice));
                        } else {
                            emissions.push(ChoiceEmission::Content(tool_choice));
                        }

                        // Handle trailing content if any
                        if !trailing_part.is_empty() {
                            #[allow(deprecated)]
236
237
238
239
240
                            let trailing_choice = create_choice_stream(
                                choice.index,
                                choice.delta.role,
                                trailing_part,
                                None,
241
                                choice.finish_reason,
242
                                None,
243
244
                                choice.logprobs.clone(),
                            );
Ryan Olson's avatar
Ryan Olson committed
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
                            emissions.push(ChoiceEmission::Trailing(trailing_choice));
                        }
                    } else {
                        // Start jailing with the marker and suffix
                        self.is_jailed = true;
                        self.accumulated_content = full_content;
                    }

                    self.partial_match_buffer.clear();
                }

                MatchResult::Partial {
                    prefix,
                    partial,
                    possible_patterns,
                } => {
                    // Emit the safe prefix
                    if !prefix.is_empty() {
                        #[allow(deprecated)]
264
265
266
267
268
                        let prefix_choice = create_choice_stream(
                            choice.index,
                            choice.delta.role,
                            &prefix,
                            None,
269
                            choice.finish_reason,
270
                            None,
271
272
                            choice.logprobs.clone(),
                        );
Ryan Olson's avatar
Ryan Olson committed
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
                        emissions.push(ChoiceEmission::PassThrough(prefix_choice));
                    }

                    // Hold the partial for next chunk
                    self.partial_match_buffer = partial;

                    tracing::trace!(
                        "Choice {} holding partial '{}' for patterns: {:?}",
                        choice.index,
                        self.partial_match_buffer,
                        possible_patterns
                    );
                }

                MatchResult::None { content } => {
                    // Check if this content (combined with partial buffer) should start jailing
                    let combined_content = if self.partial_match_buffer.is_empty() {
                        content.clone()
                    } else {
                        format!("{}{}", self.partial_match_buffer, content)
                    };

                    if jail_stream.should_start_jail(&combined_content) {
                        // Start jailing with the combined content
                        self.is_jailed = true;
                        self.accumulated_content = combined_content;
                        self.partial_match_buffer.clear();
                    } else {
                        // No markers - emit everything
                        if !content.is_empty() {
                            #[allow(deprecated)]
304
305
306
307
308
                            let pass_through_choice = create_choice_stream(
                                choice.index,
                                choice.delta.role,
                                &content,
                                None,
309
                                choice.finish_reason,
310
                                None,
311
312
                                choice.logprobs.clone(),
                            );
Ryan Olson's avatar
Ryan Olson committed
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
                            emissions.push(ChoiceEmission::PassThrough(pass_through_choice));
                        }
                        self.partial_match_buffer.clear();
                    }
                }
            }
        } else {
            // Already jailed - accumulate and check for unjail
            self.accumulate(content);

            let (should_end, split_pos) =
                jail_stream.should_end_jail(&self.accumulated_content).await;

            if should_end {
                // Split the content
                let (jailed_part, trailing_part) = self.accumulated_content.split_at(split_pos);

                // Create the unjailed choice
                let unjailed_choice = jail_stream
332
333
334
335
336
337
                    .create_tool_call_choice(
                        choice.index,
                        jailed_part,
                        choice,
                        self.emitted_tool_calls_count,
                    )
Ryan Olson's avatar
Ryan Olson committed
338
339
340
341
                    .await;

                // Determine emission type based on whether tool calls were parsed
                if unjailed_choice.delta.tool_calls.is_some() {
342
343
344
                    if let Some(ref tool_calls) = unjailed_choice.delta.tool_calls {
                        self.emitted_tool_calls_count += tool_calls.len();
                    }
Ryan Olson's avatar
Ryan Olson committed
345
346
347
348
349
350
351
352
                    emissions.push(ChoiceEmission::ToolCall(unjailed_choice));
                } else {
                    emissions.push(ChoiceEmission::Content(unjailed_choice));
                }

                // Handle trailing content if any
                if !trailing_part.is_empty() {
                    #[allow(deprecated)]
353
354
355
356
357
                    let trailing_choice = create_choice_stream(
                        choice.index,
                        choice.delta.role,
                        trailing_part,
                        None,
358
                        choice.finish_reason,
359
                        None,
360
361
                        choice.logprobs.clone(),
                    );
Ryan Olson's avatar
Ryan Olson committed
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
                    emissions.push(ChoiceEmission::Trailing(trailing_choice));
                }

                // End jailing
                self.end_jail();
            }
            // If not unjailing, don't emit anything (still accumulating)
        }
        emissions
    }

    /// Finalize any remaining content when stream ends
    async fn finalize(&mut self, jail_stream: &JailedStream) -> Option<ChoiceEmission> {
        if self.is_jailed && !self.accumulated_content.is_empty() {
            // Create a dummy choice for the method call
            #[allow(deprecated)]
378
379
380
381
382
            let dummy_choice = create_choice_stream(
                self.index,
                Some(Role::Assistant),
                &self.accumulated_content,
                None,
383
                self.stream_finish_reason, // For the accumulated content, assign the original stream finish reason, otherwise it will get lost
384
                None,
385
                None,
386
            );
Ryan Olson's avatar
Ryan Olson committed
387

388
            let mut final_choice = jail_stream
389
390
391
392
393
394
                .create_tool_call_choice(
                    self.index,
                    &self.accumulated_content,
                    &dummy_choice,
                    self.emitted_tool_calls_count,
                )
Ryan Olson's avatar
Ryan Olson committed
395
396
                .await;

397
398
399
400
401
402
403
404
405
            // Preserve any pending reasoning content collected while jailed.
            if let Some(pending_reasoning) = self.pending_reasoning_content.take() {
                if let Some(existing_reasoning) = final_choice.delta.reasoning_content.as_mut() {
                    existing_reasoning.push_str(&pending_reasoning);
                } else {
                    final_choice.delta.reasoning_content = Some(pending_reasoning);
                }
            }

406
407
408
409
            if let Some(ref tool_calls) = final_choice.delta.tool_calls {
                self.emitted_tool_calls_count += tool_calls.len();
            }

Ryan Olson's avatar
Ryan Olson committed
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
            // End jailing
            self.end_jail();

            // Determine emission type
            if final_choice.delta.tool_calls.is_some() {
                Some(ChoiceEmission::ToolCall(final_choice))
            } else {
                Some(ChoiceEmission::Content(final_choice))
            }
        } else {
            None
        }
    }
}

/// Collection of choice jail states with deterministic ordering
#[derive(Debug, Clone)]
struct ChoiceJailStateCollection {
    /// Vec of states, always kept sorted by choice index for deterministic iteration
    states: Vec<ChoiceJailState>,
}

impl ChoiceJailStateCollection {
    /// Create a new empty collection
    fn new() -> Self {
        Self { states: Vec::new() }
    }

    /// Get or create state for a choice index
439
    fn get_or_create_state(&mut self, index: u32, starts_jailed: bool) -> &mut ChoiceJailState {
Ryan Olson's avatar
Ryan Olson committed
440
441
442
443
444
445
446
447
        // Find the position where this index should be
        match self.states.binary_search_by_key(&index, |s| s.index) {
            Ok(pos) => {
                // Found existing state
                &mut self.states[pos]
            }
            Err(insert_pos) => {
                // Need to create new state
448
                let new_state = ChoiceJailState::new(index, starts_jailed);
Ryan Olson's avatar
Ryan Olson committed
449
450
451
452
453
454
455
456
                self.states.insert(insert_pos, new_state);
                &mut self.states[insert_pos]
            }
        }
    }
}

/// Emission mode for handling multiple choices
457
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
Ryan Olson's avatar
Ryan Olson committed
458
459
pub enum EmissionMode {
    /// Pack multiple choices in the same chunk (default, matches original behavior)
460
    #[default]
Ryan Olson's avatar
Ryan Olson committed
461
462
463
464
465
466
467
468
469
470
471
472
    Packed,
    /// Emit one choice per chunk for OpenAI compatibility
    SingleChoicePerChunk,
}

/// A stream transformer that can "jail" tokens based on configurable start/end sequences
/// When jailed, tokens are accumulated rather than yielded immediately
/// When the jail ends (via end sequence or stream completion), accumulated content is processed and released
pub struct JailedStream {
    jail_start_sequences: Vec<String>,
    jail_end_sequences: Vec<String>,
    tool_call_parser: Option<String>,
473
474
475
    /// When set, only tool calls with this name are emitted (enforces tool_choice=named
    /// when a tool_call_parser is active and the parser-aware MarkerBased path is used).
    named_tool_name: Option<String>,
476
    tool_definitions: Option<Vec<dynamo_parsers::tool_calling::ToolDefinition>>,
Ryan Olson's avatar
Ryan Olson committed
477
478
    emission_mode: EmissionMode,
    marker_matcher: MarkerMatcher,
479
    jail_mode: JailMode,
Ryan Olson's avatar
Ryan Olson committed
480
481
482
483
484
485
486
487
}

impl JailedStream {
    /// Create a new builder for configuring a JailedStream
    pub fn builder() -> JailedStreamBuilder {
        JailedStreamBuilder::new()
    }

488
489
490
491
492
493
494
495
496
    /// Apply jail stream transformation with finish_reason fix
    /// This is a convenience method that applies both apply() and fix_finish_reason()
    pub fn apply_with_finish_reason<S>(
        self,
        stream: S,
    ) -> impl Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send
    where
        S: Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static,
    {
497
        let jail_mode = self.jail_mode.clone();
498
        let named_tool_active = self.named_tool_name.is_some();
499
        let jailed_stream = self.apply(stream);
500
        JailedStream::fix_finish_reason(jailed_stream, jail_mode, named_tool_active)
501
502
    }

Ryan Olson's avatar
Ryan Olson committed
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
    /// Apply the jail transformation to a stream of chat completion responses
    /// Consumes self and returns the transformed stream
    pub fn apply<S>(
        self,
        stream: S,
    ) -> impl Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send
    where
        S: Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static,
    {
        // Use the stream! macro for cleaner async stream processing
        stream! {
            // State variables - clean architecture with choice state collection
            let mut choice_states = ChoiceJailStateCollection::new();
            // Track Annotated metadata for preservation
            let mut last_annotated_id: Option<String> = None;
            let mut last_annotated_event: Option<String> = None;
            let mut last_annotated_comment: Option<Vec<String>> = None;
520
521
522
523
            // Track stream response metadata so finalization chunks carry real values
            let mut last_stream_id = String::new();
            let mut last_stream_model = String::new();
            let mut last_stream_created: u32 = 0;
Ryan Olson's avatar
Ryan Olson committed
524
525
526
527

            // Pin the stream for iteration (stack pinning is more efficient)
            tokio::pin!(stream);

528

Ryan Olson's avatar
Ryan Olson committed
529
530
531
            // Process each item in the stream
            while let Some(response) = stream.next().await {
                if let Some(chat_response) = response.data.as_ref() {
532
533
534
                    last_stream_id.clone_from(&chat_response.inner.id);
                    last_stream_model.clone_from(&chat_response.inner.model);
                    last_stream_created = chat_response.inner.created;
535

Ryan Olson's avatar
Ryan Olson committed
536
537
                    let mut all_emissions = Vec::new();

538
                    if chat_response.inner.choices.is_empty() {
539
540
541
542
543
544
                        // No choices processed (e.g., usage-only chunk)
                        // Pass through as-is to preserve usage and other metadata
                        yield response;
                        continue;
                    }

Ryan Olson's avatar
Ryan Olson committed
545
                    // Process each choice independently using the new architecture
546
                    for choice in &chat_response.inner.choices {
Ryan Olson's avatar
Ryan Olson committed
547
                        if let Some(ref content) = choice.delta.content {
548
549
                            // Jailing only applies to text content
                            let text_content = match content {
550
551
                                dynamo_protocols::types::ChatCompletionMessageContent::Text(text) => Some(text.as_str()),
                                dynamo_protocols::types::ChatCompletionMessageContent::Parts(_) => None,
552
553
554
555
556
557
                            };

                            if let Some(text) = text_content {
                                let starts_jailed = matches!(self.jail_mode, JailMode::Immediate { .. });
                                let choice_state = choice_states.get_or_create_state(choice.index, starts_jailed);

558
559
560
561
562
563
564
                                if let Some(reasoning_content) = &choice.delta.reasoning_content {
                                    let pending = choice_state
                                        .pending_reasoning_content
                                        .get_or_insert_with(String::new);
                                    pending.push_str(reasoning_content);
                                }

565
566
567
568
569
570
571
572
573
574
575
576
                                // Store metadata when any choice becomes jailed (first time only)
                                if !choice_state.is_jailed && self.should_start_jail(text)
                                    && last_annotated_id.is_none() {
                                        last_annotated_id = response.id.clone();
                                        last_annotated_event = response.event.clone();
                                        last_annotated_comment = response.comment.clone();
                                    }

                                // Track actual stream finish reason in the choice state
                                choice_state.stream_finish_reason = choice.finish_reason;

                                // Process this choice and get emissions
577
578
579
580
581
582
583
                                let mut emissions = choice_state.process_content(choice, text, &self).await;
                                if !emissions.is_empty()
                                    && let Some(reasoning) = choice_state.pending_reasoning_content.take()
                                    && let Some(first) = emissions.first_mut()
                                {
                                    first.choice_mut().delta.reasoning_content = Some(reasoning);
                                }
584
585
586
                                all_emissions.extend(emissions);
                            }
                            // For multimodal content, pass through unchanged (no jailing)
Ryan Olson's avatar
Ryan Olson committed
587
588
                        } else {
                            // Handle choices without content (e.g., final chunks with finish_reason)
589
590
591
592
593
594
595
596
597
598
599
600
601
602
                            // Only filter out if this choice was ever jailed and lacks role
                            // (to avoid aggregator issues with deltas missing role after unjail)
                            let choice_state = choice_states.get_or_create_state(choice.index, false);
                            let was_ever_jailed = !choice_state.accumulated_content.is_empty() || choice_state.is_jailed;

                            let should_emit = choice.delta.role.is_some()
                                || choice.delta.tool_calls.is_some()
                                || !was_ever_jailed; // Always pass through if never jailed

                            if should_emit {
                                let pass_through_choice = ChatChoiceStream {
                                    index: choice.index,
                                    delta: choice.delta.clone(),
                                    finish_reason: choice.finish_reason,
603
                                    stop_reason: choice.stop_reason.clone(),
604
605
606
607
                                    logprobs: choice.logprobs.clone(),
                                };
                                all_emissions.push(ChoiceEmission::PassThrough(pass_through_choice));
                            }
Ryan Olson's avatar
Ryan Olson committed
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
                        }
                    }

                    // Emit all results based on emission mode
                    if !all_emissions.is_empty() {
                        // Group emissions by type for proper ordering and separation
                        let mut tool_content_emissions = Vec::new();
                        let mut trailing_emissions = Vec::new();
                        let mut passthrough_emissions = Vec::new();

                        for emission in all_emissions {
                            match emission {
                                ChoiceEmission::PassThrough(_) => passthrough_emissions.push(emission),
                                ChoiceEmission::ToolCall(_) | ChoiceEmission::Content(_) => {
                                    tool_content_emissions.push(emission);
                                }
                                ChoiceEmission::Trailing(_) => {
                                    trailing_emissions.push(emission);
                                }
                            }
                        }

                        // Emit tool calls and content with preserved metadata
                        if !tool_content_emissions.is_empty() {
                            let preserved_metadata = (
                                last_annotated_id.clone(),
                                last_annotated_event.clone(),
                                last_annotated_comment.clone(),
                            );
                            let responses = self.emit_choice_emissions(tool_content_emissions, chat_response, preserved_metadata);
                            for emitted_response in responses {
                                yield emitted_response;
                            }
                        }

                        // Emit trailing content separately (always as individual chunks)
                        if !trailing_emissions.is_empty() {
                            let preserved_metadata = (
                                last_annotated_id.clone(),
                                last_annotated_event.clone(),
                                last_annotated_comment.clone(),
                            );
                            let responses = self.emit_choice_emissions(trailing_emissions, chat_response, preserved_metadata);
                            for emitted_response in responses {
                                yield emitted_response;
                            }
                        }

                        // Emit pass-through content with current metadata
                        if !passthrough_emissions.is_empty() {
                            let current_metadata = (response.id.clone(), response.event.clone(), response.comment.clone());
                            let responses = self.emit_choice_emissions(passthrough_emissions, chat_response, current_metadata);
                            for emitted_response in responses {
                                yield emitted_response;
                            }
                        }
                    }
                } else {
                    // No response data, pass through as-is
                    yield response;
                }
            }

            // Stream ended - finalize any remaining jailed choices
            let mut final_emissions = Vec::new();
            for state in choice_states.states.iter_mut() {
                if let Some(emission) = state.finalize(&self).await {
                    final_emissions.push(emission);
                }
            }

            if !final_emissions.is_empty() {
                tracing::debug!("Stream ended while jailed, releasing accumulated content");
681
                // Create a finalization response carrying forward real stream metadata
Ryan Olson's avatar
Ryan Olson committed
682
                let dummy_response = NvCreateChatCompletionStreamResponse {
683
                    inner: dynamo_protocols::types::CreateChatCompletionStreamResponse {
684
685
686
687
688
689
690
691
692
                        id: last_stream_id,
                        object: "chat.completion.chunk".to_string(),
                        created: last_stream_created,
                        model: last_stream_model,
                        choices: Vec::new(),
                        usage: None,
                        service_tier: None,
                        system_fingerprint: None,
                    },
693
                    nvext: None,
Ryan Olson's avatar
Ryan Olson committed
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
                };

                let final_metadata = (last_annotated_id, last_annotated_event, last_annotated_comment);
                let responses = self.emit_choice_emissions(final_emissions, &dummy_response, final_metadata);
                for emitted_response in responses {
                    yield emitted_response;
                }
            }
        }
    }

    /// Emit choice emissions based on the configured emission mode
    fn emit_choice_emissions(
        &self,
        emissions: Vec<ChoiceEmission>,
        base_response: &NvCreateChatCompletionStreamResponse,
        annotated_metadata: (Option<String>, Option<String>, Option<Vec<String>>),
    ) -> Vec<Annotated<NvCreateChatCompletionStreamResponse>> {
        if emissions.is_empty() {
            return Vec::new();
        }

        let (id, event, comment) = annotated_metadata;

        match self.emission_mode {
            EmissionMode::Packed => {
                // Pack all choices into a single response
                let mut response = base_response.clone();
722
                response.inner.choices = emissions.into_iter().map(|e| e.into_choice()).collect();
Ryan Olson's avatar
Ryan Olson committed
723
724
725
726
727
728

                vec![Annotated {
                    data: Some(response),
                    id,
                    event,
                    comment,
729
                    error: None,
Ryan Olson's avatar
Ryan Olson committed
730
731
732
733
734
735
736
737
                }]
            }
            EmissionMode::SingleChoicePerChunk => {
                // Emit each choice in a separate response
                emissions
                    .into_iter()
                    .map(|emission| {
                        let mut response = base_response.clone();
738
                        response.inner.choices = vec![emission.into_choice()];
Ryan Olson's avatar
Ryan Olson committed
739
740
741
742
743
744

                        Annotated {
                            data: Some(response),
                            id: id.clone(),
                            event: event.clone(),
                            comment: comment.clone(),
745
                            error: None,
Ryan Olson's avatar
Ryan Olson committed
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
                        }
                    })
                    .collect()
            }
        }
    }

    /// Check if content matches any jail start patterns
    fn should_start_jail(&self, content: &str) -> bool {
        // Path 1: Check configured start sequences
        let sequence_match = !self.jail_start_sequences.is_empty()
            && self
                .jail_start_sequences
                .iter()
                .any(|seq| content.contains(seq));

        // Path 2: Check for tool call start pattern
        let tool_call_match = self.tool_call_parser.is_some()
            && detect_tool_call_start(content, self.tool_call_parser.as_deref()).unwrap_or(false);

        sequence_match || tool_call_match
    }

    /// Check if accumulated content should end jail
    async fn should_end_jail(&self, accumulated_content: &str) -> (bool, usize) {
771
772
        match &self.jail_mode {
            JailMode::MarkerBased => {
773
                // Path 1: End sequence detected via naive string search.
774
775
776
777
778
779
780
781
782
                let end_marker_info = if !self.jail_end_sequences.is_empty() {
                    self.jail_end_sequences.iter().find_map(|seq| {
                        accumulated_content
                            .find(seq)
                            .map(|pos| (pos + seq.len(), seq.clone()))
                    })
                } else {
                    None
                };
Ryan Olson's avatar
Ryan Olson committed
783

784
785
                // Path 2: Complete tool call(s) can be parsed (early exit)
                let early_exit = self.should_exit_jail_early(accumulated_content).await;
Ryan Olson's avatar
Ryan Olson committed
786

787
788
789
790
791
                // When a tool_call_parser is active, prefer Path 2 over Path 1 so
                // that `find_tool_call_end_position` advances past all consecutive
                // parallel tool calls instead of splitting at the first end tag.
                // Fall back to Path 1 when parsing fails (e.g. malformed content).
                if early_exit {
792
793
                    // For early exit, find where the complete tool call ends
                    if let Some(parser) = &self.tool_call_parser {
794
795
796
797
798
799
800
                        let tools_slice = self.tool_definitions.as_deref();
                        if let Ok((_, _)) = try_tool_call_parse_aggregate(
                            accumulated_content,
                            Some(parser),
                            tools_slice,
                        )
                        .await
801
802
803
804
805
806
807
808
809
810
                        {
                            let split_pos =
                                find_tool_call_end_position(accumulated_content, Some(parser));
                            (true, split_pos)
                        } else {
                            (false, accumulated_content.len())
                        }
                    } else {
                        (false, accumulated_content.len())
                    }
811
812
                } else if let Some((end_pos, _)) = end_marker_info {
                    (true, end_pos)
Ryan Olson's avatar
Ryan Olson committed
813
814
815
816
                } else {
                    (false, accumulated_content.len())
                }
            }
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
            JailMode::Immediate { format } => {
                // For tool_choice, check if we have valid complete JSON
                match format {
                    ToolChoiceFormat::SingleObject { .. } => {
                        // Expect single object: {"location": "Paris", "unit": "celsius"}
                        if let Ok(value) =
                            serde_json::from_str::<serde_json::Value>(accumulated_content)
                            && value.is_object()
                        {
                            return (true, accumulated_content.len());
                        }
                        (false, accumulated_content.len())
                    }
                    ToolChoiceFormat::ArrayOfTools => {
                        // Expect array: [{"name":"search","parameters":{...}}, ...]
                        if let Ok(value) =
                            serde_json::from_str::<serde_json::Value>(accumulated_content)
                            && let Some(arr) = value.as_array()
                            && !arr.is_empty()
                        {
                            return (true, accumulated_content.len());
                        }
                        (false, accumulated_content.len())
                    }
                }
            }
Ryan Olson's avatar
Ryan Olson committed
843
844
845
846
847
848
849
850
851
        }
    }

    /// Parse tool calls from accumulated content and create choice
    async fn create_tool_call_choice(
        &self,
        choice_index: u32,
        accumulated_content: &str,
        base_choice: &ChatChoiceStream,
852
        tool_call_offset: usize,
Ryan Olson's avatar
Ryan Olson committed
853
    ) -> ChatChoiceStream {
854
855
856
        match &self.jail_mode {
            JailMode::MarkerBased => {
                // Traditional marker-based tool call parsing
857
                let tools_slice = self.tool_definitions.as_deref();
858
                let parse_result = try_tool_call_parse_aggregate(
859
860
                    accumulated_content,
                    self.tool_call_parser.as_deref(),
861
                    tools_slice,
862
                )
863
864
                .await;
                if let Ok((tool_calls, normal_text)) = parse_result
865
866
                    && !tool_calls.is_empty()
                {
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
                    // If a named tool filter is set (tool_choice=named + parser path), reject
                    // tool calls that don't match the required tool name.
                    let tool_calls = if let Some(ref required_name) = self.named_tool_name {
                        let filtered: Vec<_> = tool_calls
                            .into_iter()
                            .filter(|tc| tc.function.name == *required_name)
                            .collect();
                        if filtered.is_empty() {
                            tracing::warn!(
                                required = %required_name,
                                "tool_choice=named: parser emitted no matching tool calls; dropping jail output"
                            );
                        }
                        filtered
                    } else {
                        tool_calls
                    };

                    if tool_calls.is_empty() {
                        // All parsed calls were for the wrong tool — return content choice
                        return create_choice_stream(
                            choice_index,
                            Some(Role::Assistant),
                            accumulated_content,
                            None,
                            base_choice.finish_reason,
                            base_choice.stop_reason.clone(),
                            base_choice.logprobs.clone(),
                        );
                    }

898
899
900
901
902
903
904
                    // Convert to streaming format
                    let tool_call_chunks: Vec<ChatCompletionMessageToolCallChunk> = tool_calls
                        .into_iter()
                        .enumerate()
                        .map(|(idx, tool_call)| ChatCompletionMessageToolCallChunk {
                            index: (tool_call_offset + idx) as u32,
                            id: Some(tool_call.id),
905
                            r#type: Some(FunctionType::Function),
906
907
908
909
910
911
912
913
914
915
916
917
918
919
                            function: Some(FunctionCallStream {
                                name: Some(tool_call.function.name),
                                arguments: Some(tool_call.function.arguments),
                            }),
                        })
                        .collect();
                    // Create choice with tool calls
                    let choice = create_choice_stream(
                        choice_index,
                        Some(Role::Assistant),
                        normal_text.as_deref().unwrap_or(""),
                        Some(tool_call_chunks),
                        None,
                        None,
920
                        None,
921
922
923
924
925
926
927
928
929
930
931
                    );
                    return choice;
                }

                // No tool calls found or parsing failed, return content choice
                create_choice_stream(
                    choice_index,
                    Some(Role::Assistant),
                    accumulated_content,
                    None,
                    base_choice.finish_reason,
932
                    base_choice.stop_reason.clone(),
933
934
935
936
937
938
939
940
941
942
943
944
                    base_choice.logprobs.clone(),
                )
            }
            JailMode::Immediate { format } => {
                // tool_choice mode: parse JSON and convert to tool calls
                match self.parse_tool_choice_json(accumulated_content, format) {
                    Ok(tool_call_chunks) if !tool_call_chunks.is_empty() => create_choice_stream(
                        choice_index,
                        Some(Role::Assistant),
                        "",
                        Some(tool_call_chunks),
                        base_choice.finish_reason,
945
                        None,
946
947
948
949
950
951
952
953
954
955
                        base_choice.logprobs.clone(),
                    ),
                    Ok(_) | Err(_) => {
                        // Parsing failed, return as content
                        create_choice_stream(
                            choice_index,
                            Some(Role::Assistant),
                            accumulated_content,
                            None,
                            base_choice.finish_reason,
956
                            base_choice.stop_reason.clone(),
957
958
959
960
961
                            base_choice.logprobs.clone(),
                        )
                    }
                }
            }
Ryan Olson's avatar
Ryan Olson committed
962
        }
963
    }
Ryan Olson's avatar
Ryan Olson committed
964

965
966
967
968
969
970
971
972
973
    /// Helper to create a ChatCompletionMessageToolCallChunk
    fn create_tool_call_chunk(
        index: u32,
        name: String,
        arguments: String,
    ) -> ChatCompletionMessageToolCallChunk {
        ChatCompletionMessageToolCallChunk {
            index,
            id: Some(format!("call-{}", Uuid::new_v4())),
974
            r#type: Some(FunctionType::Function),
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
            function: Some(FunctionCallStream {
                name: Some(name),
                arguments: Some(arguments),
            }),
        }
    }

    /// Parse tool_choice JSON output into tool call chunks
    fn parse_tool_choice_json(
        &self,
        json_content: &str,
        format: &ToolChoiceFormat,
    ) -> anyhow::Result<Vec<ChatCompletionMessageToolCallChunk>> {
        let parsed = serde_json::from_str::<serde_json::Value>(json_content)?;

        match format {
            ToolChoiceFormat::SingleObject { tool_name } => {
                // For named tool choice: JSON is the parameters object
                if parsed.is_object() {
                    Ok(vec![Self::create_tool_call_chunk(
                        0,
                        tool_name.clone(),
                        json_content.to_string(),
                    )])
                } else {
                    Ok(vec![])
                }
            }
            ToolChoiceFormat::ArrayOfTools => {
                // For required tool choice: JSON is array of {name, parameters}
                if let Some(array) = parsed.as_array() {
                    let chunks: Vec<ChatCompletionMessageToolCallChunk> = array
                        .iter()
                        .enumerate()
                        .filter_map(|(idx, entry)| {
                            let name = entry.get("name")?.as_str()?.to_string();
                            let parameters = entry.get("parameters")?;
                            let args = serde_json::to_string(parameters).ok()?;
                            Some(Self::create_tool_call_chunk(idx as u32, name, args))
                        })
                        .collect();
                    Ok(chunks)
                } else {
                    Ok(vec![])
                }
            }
        }
Ryan Olson's avatar
Ryan Olson committed
1022
1023
1024
1025
1026
1027
1028
    }

    /// Check if accumulated content contains complete tool calls that can be parsed
    /// Returns true if we should exit the jail early
    async fn should_exit_jail_early(&self, accumulated: &str) -> bool {
        if let Some(ref parser) = self.tool_call_parser {
            // Try to parse - if successful and we have complete tool calls, exit early
1029
1030
            let tools_slice = self.tool_definitions.as_deref();
            match try_tool_call_parse_aggregate(accumulated, Some(parser), tools_slice).await {
1031
1032
1033
1034
1035
                Ok((tool_calls, _normal_text)) => {
                    let result = !tool_calls.is_empty();
                    return result;
                }
                Err(_e) => {}
Ryan Olson's avatar
Ryan Olson committed
1036
1037
1038
1039
            }
        }
        false
    }
1040
1041
1042

    /// Post-processor that sets finish_reason to ToolCalls when tool calls were emitted
    /// This should be called after apply() to fix the finish_reason for tool call chunks
1043
    fn fix_finish_reason<S>(
1044
        input_stream: S,
1045
        jail_mode: JailMode,
1046
        named_tool_active: bool,
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
    ) -> impl Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send
    where
        S: Stream<Item = Annotated<NvCreateChatCompletionStreamResponse>> + Send + 'static,
    {
        stream! {
            tokio::pin!(input_stream);
            let mut has_tool_calls_per_choice: HashMap<u32, bool> = HashMap::new();

            while let Some(mut response) = input_stream.next().await {
                // Track if any choice emitted tool calls
                if let Some(ref data) = response.data {
1058
                    for choice in &data.inner.choices {
1059
1060
1061
1062
1063
1064
                        if choice.delta.tool_calls.is_some() {
                            has_tool_calls_per_choice.insert(choice.index, true);
                        }
                    }
                }

1065
                // Fix finish_reason based on jail mode and whether tool calls were emitted
1066
                if let Some(ref mut data) = response.data {
1067
                    for choice in &mut data.inner.choices {
1068
1069
1070
1071
1072
1073
1074
                        if let Some(finish) = choice.finish_reason {
                            // Only modify Stop finish reason, preserve Length/ContentFilter
                            if finish == FinishReason::Stop {
                                let has_tool_calls = has_tool_calls_per_choice.get(&choice.index).copied().unwrap_or(false);

                                match &jail_mode {
                                    JailMode::MarkerBased => {
1075
                                        if has_tool_calls && !named_tool_active {
1076
1077
                                            choice.finish_reason = Some(FinishReason::ToolCalls);
                                        }
1078
                                        // When named_tool_active, keep Stop (OpenAI spec for tool_choice=named)
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
                                    }
                                    JailMode::Immediate { format } => {
                                        // tool_choice mode: apply specific finish_reason logic
                                        match format {
                                            ToolChoiceFormat::SingleObject { .. } => {
                                                // Named tool choice: keep Stop
                                                // (already Stop, no change needed)
                                            }
                                            ToolChoiceFormat::ArrayOfTools => {
                                                // Required tool choice: change to ToolCalls
                                                if has_tool_calls {
                                                    choice.finish_reason = Some(FinishReason::ToolCalls);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            // Length and ContentFilter are preserved as-is
1098
1099
1100
1101
1102
1103
1104
1105
                        }
                    }
                }

                yield response;
            }
        }
    }
Ryan Olson's avatar
Ryan Olson committed
1106
1107
1108
1109
1110
1111
1112
}

/// Builder for configuring a JailedStream
pub struct JailedStreamBuilder {
    jail_start_sequences: Vec<String>,
    jail_end_sequences: Vec<String>,
    tool_call_parser: Option<String>,
1113
1114
1115
    /// When set, only tool calls with this name are emitted (enforces tool_choice=named
    /// when a tool_call_parser is active and the parser-aware MarkerBased path is used).
    named_tool_name: Option<String>,
1116
    tool_definitions: Option<Vec<dynamo_parsers::tool_calling::ToolDefinition>>,
Ryan Olson's avatar
Ryan Olson committed
1117
    emission_mode: EmissionMode,
1118
    jail_mode: JailMode,
Ryan Olson's avatar
Ryan Olson committed
1119
1120
1121
1122
1123
1124
1125
1126
1127
}

impl JailedStreamBuilder {
    /// Create a new builder with default settings
    pub fn new() -> Self {
        Self {
            jail_start_sequences: Vec::new(),
            jail_end_sequences: Vec::new(),
            tool_call_parser: None,
1128
            named_tool_name: None,
1129
            tool_definitions: None,
Ryan Olson's avatar
Ryan Olson committed
1130
            emission_mode: EmissionMode::default(),
1131
            jail_mode: JailMode::MarkerBased,
Ryan Olson's avatar
Ryan Olson committed
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
        }
    }

    /// Add a sequence that triggers jailing when detected
    pub fn jail_start_sequence(mut self, sequence: impl Into<String>) -> Self {
        self.jail_start_sequences.push(sequence.into());
        self
    }

    /// Add multiple sequences that trigger jailing when detected
    pub fn jail_start_sequences(
        mut self,
        sequences: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.jail_start_sequences
            .extend(sequences.into_iter().map(Into::into));
        self
    }

    /// Add a sequence that ends jailing when detected
    pub fn jail_end_sequence(mut self, sequence: impl Into<String>) -> Self {
        self.jail_end_sequences.push(sequence.into());
        self
    }

    /// Add multiple sequences that end jailing when detected
    pub fn jail_end_sequences(
        mut self,
        sequences: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.jail_end_sequences
            .extend(sequences.into_iter().map(Into::into));
        self
    }

    /// Set the tool call parser to use for detection and parsing
    pub fn tool_call_parser(mut self, parser: impl Into<String>) -> Self {
        self.tool_call_parser = Some(parser.into());
        self
    }

1173
1174
1175
1176
1177
1178
1179
1180
    /// Constrain parsed output to a single named tool (for tool_choice=named + parser path).
    /// When set, tool calls emitted by the parser that don't match `tool_name` are silently
    /// filtered out, enforcing the named-tool contract even when the model emits the wrong tool.
    pub fn named_tool_filter(mut self, tool_name: impl Into<String>) -> Self {
        self.named_tool_name = Some(tool_name.into());
        self
    }

1181
1182
1183
1184
1185
1186
1187
1188
1189
    /// Set the tool definitions for runtime validation and parsing
    pub fn tool_definitions(
        mut self,
        tools: Vec<dynamo_parsers::tool_calling::ToolDefinition>,
    ) -> Self {
        self.tool_definitions = Some(tools);
        self
    }

Ryan Olson's avatar
Ryan Olson committed
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
    /// Set the emission mode for handling multiple choices
    pub fn emission_mode(mut self, mode: EmissionMode) -> Self {
        self.emission_mode = mode;
        self
    }

    /// Enable single choice per chunk emission for OpenAI compatibility
    pub fn single_choice_per_chunk(mut self) -> Self {
        self.emission_mode = EmissionMode::SingleChoicePerChunk;
        self
    }

    /// Enable packed emission mode (multiple choices per chunk)
    pub fn packed_emission(mut self) -> Self {
        self.emission_mode = EmissionMode::Packed;
        self
    }

1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
    /// Enable immediate jail mode for tool_choice=named
    pub fn tool_choice_named(mut self, tool_name: String) -> Self {
        self.jail_mode = JailMode::Immediate {
            format: ToolChoiceFormat::SingleObject { tool_name },
        };
        self
    }

    /// Enable immediate jail mode for tool_choice=required
    pub fn tool_choice_required(mut self) -> Self {
        self.jail_mode = JailMode::Immediate {
            format: ToolChoiceFormat::ArrayOfTools,
        };
        self
    }

Ryan Olson's avatar
Ryan Olson committed
1224
1225
1226
1227
1228
1229
1230
1231
    /// Build the configured JailedStream
    pub fn build(mut self) -> JailedStream {
        // Auto-populate jail sequences from parser config if not manually configured
        if let Some(ref parser_name) = self.tool_call_parser {
            let parser_map = get_tool_parser_map();
            if let Some(config) = parser_map.get(parser_name.as_str()) {
                // Auto-populate start sequences if none configured
                if self.jail_start_sequences.is_empty() {
1232
                    self.jail_start_sequences = config.parser_config.tool_call_start_tokens();
Ryan Olson's avatar
Ryan Olson committed
1233
1234
1235
1236
1237
                }

                // Auto-populate end sequences if none configured
                if self.jail_end_sequences.is_empty() {
                    self.jail_end_sequences = config
1238
1239
                        .parser_config
                        .tool_call_end_tokens()
Ryan Olson's avatar
Ryan Olson committed
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
                        .iter()
                        .filter(|&s| !s.is_empty())
                        .cloned()
                        .collect();
                }
            }
        }

        // Collect all possible marker patterns for the MarkerMatcher
        let mut all_patterns = Vec::new();

        // Add configured start sequences (now auto-populated if needed)
        all_patterns.extend(self.jail_start_sequences.clone());

        // Add patterns from tool call parser if configured (for redundancy)
        if let Some(ref parser_name) = self.tool_call_parser {
            let parser_map = get_tool_parser_map();
            if let Some(config) = parser_map.get(parser_name.as_str()) {
                // Add start tokens from the parser config
1259
                all_patterns.extend(config.parser_config.tool_call_start_tokens());
Ryan Olson's avatar
Ryan Olson committed
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
            }
        }

        // Add common tool call markers to ensure we detect all formats
        // Only include these when a specific parser is NOT configured,
        // to avoid unexpected false positives for explicit formats
        if self.tool_call_parser.is_none() {
            let common_markers = vec![
                "<TOOLCALL>".to_string(),     // nemotron_deci format
                "<tool_call>".to_string(),    // hermes format
                "[TOOL_CALLS]".to_string(),   // mistral format
                "<|python_tag|>".to_string(), // llama3_json format
                "functools[".to_string(),     // phi4 format
                // Add JSON start patterns for Mistral-style tool calls
                "[{".to_string(),
                "{".to_string(),
                // Note: Harmony parser uses JSON patterns, covered by "{" above
            ];
            for marker in common_markers {
                if !all_patterns.contains(&marker) {
                    all_patterns.push(marker);
                }
            }
        }

        // Create the marker matcher (fallback to empty patterns if none configured)
        let marker_matcher = if all_patterns.is_empty() {
            // If no patterns, create a dummy matcher that never matches
            MarkerMatcher::new(vec!["__NEVER_MATCH__".to_string()])
                .expect("Failed to create dummy MarkerMatcher")
        } else {
1291
            tracing::debug!("Creating MarkerMatcher with patterns: {:?}", all_patterns);
Ryan Olson's avatar
Ryan Olson committed
1292
1293
1294
1295
1296
1297
1298
1299
            MarkerMatcher::new(all_patterns)
                .expect("Failed to create MarkerMatcher with configured patterns")
        };

        JailedStream {
            jail_start_sequences: self.jail_start_sequences,
            jail_end_sequences: self.jail_end_sequences,
            tool_call_parser: self.tool_call_parser,
1300
            named_tool_name: self.named_tool_name,
1301
            tool_definitions: self.tool_definitions,
Ryan Olson's avatar
Ryan Olson committed
1302
1303
            emission_mode: self.emission_mode,
            marker_matcher,
1304
            jail_mode: self.jail_mode,
Ryan Olson's avatar
Ryan Olson committed
1305
1306
1307
1308
1309
1310
1311
1312
1313
        }
    }
}

impl Default for JailedStreamBuilder {
    fn default() -> Self {
        Self::new()
    }
}