Skip to main content

vtcode_llm/providers/shared/
stream.rs

1//! OpenAI-compatible stream assembly, ordered deltas, and tool-call accumulation.
2
3use crate::error_display;
4use crate::provider::{LLMError, LLMResponse, LLMStreamEvent, ToolCall};
5use crate::providers::common::{extract_reasoning_text_from_serialized_details, map_finish_reason_common};
6use crate::providers::split_reasoning_from_text;
7use serde_json::{Map, Value};
8
9use super::sse::find_sse_boundary;
10use super::{
11    ReasoningBuffer, TagStreamSanitizer, Utf8StreamDecoder, check_sse_tail_bound, extract_data_payload,
12    find_sse_boundary_bytes,
13};
14
15#[derive(Debug, thiserror::Error)]
16pub enum StreamAssemblyError {
17    #[error("missing field `{0}` in stream payload")]
18    MissingField(&'static str),
19    #[error("invalid stream payload: {0}")]
20    InvalidPayload(String),
21}
22
23impl StreamAssemblyError {
24    #[cold]
25    pub(crate) fn into_llm_error(self, provider: &str) -> LLMError {
26        let message = self.to_string();
27        let formatted = error_display::format_llm_error(provider, &message);
28        LLMError::Provider { message: formatted, metadata: None }
29    }
30}
31
32pub trait StreamTelemetry: Send + Sync {
33    fn on_content_delta(&self, _delta: &str) {}
34    fn on_reasoning_delta(&self, _delta: &str) {}
35    fn on_reasoning_stage(&self, _stage: &str) {}
36    fn on_tool_call_delta(&self) {}
37}
38
39#[derive(Default)]
40pub struct NoopStreamTelemetry;
41
42impl StreamTelemetry for NoopStreamTelemetry {}
43
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub enum StreamFragment {
46    Content(String),
47    Reasoning(String),
48}
49
50#[derive(Default, Debug)]
51pub struct StreamDelta {
52    fragments: Vec<StreamFragment>,
53}
54
55impl StreamDelta {
56    pub(crate) fn push_content(&mut self, text: &str) {
57        if text.is_empty() {
58            return;
59        }
60
61        match self.fragments.last_mut() {
62            Some(StreamFragment::Content(existing)) => existing.push_str(text),
63            _ => self.fragments.push(StreamFragment::Content(text.to_string())),
64        }
65    }
66
67    pub(crate) fn push_reasoning(&mut self, text: &str) {
68        if text.is_empty() {
69            return;
70        }
71
72        match self.fragments.last_mut() {
73            Some(StreamFragment::Reasoning(existing)) => existing.push_str(text),
74            _ => self.fragments.push(StreamFragment::Reasoning(text.to_string())),
75        }
76    }
77
78    pub(crate) fn is_empty(&self) -> bool {
79        self.fragments.is_empty()
80    }
81
82    pub(crate) fn into_fragments(self) -> Vec<StreamFragment> {
83        self.fragments
84    }
85
86    pub fn extend(&mut self, other: StreamDelta) {
87        self.fragments.extend(other.fragments);
88    }
89}
90
91/// Generate a globally unique fallback id for tool calls whose provider
92/// omitted one. Index-based fallbacks (`tool_call_{index}`) reset every
93/// response, so the same id recurs across assistant messages and corrupts
94/// id-keyed history correlation downstream. Uniqueness across responses and
95/// process restarts (resumed sessions replay ids from checkpoints) is
96/// required, hence a random uuid rather than a counter.
97pub(crate) fn generate_tool_call_id() -> String {
98    format!("call_{}", uuid::Uuid::new_v4().simple())
99}
100
101#[derive(Default, Clone)]
102pub struct ToolCallBuilder {
103    id: Option<String>,
104    namespace: Option<String>,
105    name: Option<String>,
106    arguments: String,
107}
108
109impl ToolCallBuilder {
110    pub(crate) fn apply_delta(&mut self, delta: &Value) {
111        if let Some(id) = delta.get("id").and_then(|value| value.as_str()) {
112            self.id = Some(id.to_string());
113        }
114
115        if let Some(namespace) = delta.get("namespace").and_then(|value| value.as_str()) {
116            self.namespace = Some(namespace.to_string());
117        }
118
119        if let Some(function) = delta.get("function") {
120            if let Some(namespace) = function.get("namespace").and_then(|value| value.as_str()) {
121                self.namespace = Some(namespace.to_string());
122            }
123
124            if let Some(name) = function.get("name").and_then(|value| value.as_str()) {
125                self.name = Some(name.to_string());
126            }
127
128            if let Some(arguments_value) = function.get("arguments") {
129                if let Some(arguments) = arguments_value.as_str() {
130                    self.arguments.push_str(arguments);
131                } else if arguments_value.is_object() || arguments_value.is_array() {
132                    self.arguments.push_str(&arguments_value.to_string());
133                }
134            }
135        }
136    }
137
138    fn finalize(self) -> Option<ToolCall> {
139        let name = self.name?;
140        let id = self.id.unwrap_or_else(generate_tool_call_id);
141        let arguments = if self.arguments.is_empty() {
142            "{}".to_string()
143        } else {
144            self.arguments
145        };
146
147        Some(ToolCall::function_with_namespace(id, self.namespace, name, arguments))
148    }
149}
150
151fn update_tool_calls(builders: &mut Vec<ToolCallBuilder>, deltas: &[Value]) {
152    for (position, delta) in deltas.iter().enumerate() {
153        let index = delta
154            .get("index")
155            .and_then(|value| value.as_u64())
156            .map(|value| value as usize)
157            .unwrap_or(position);
158
159        if builders.len() <= index {
160            builders.resize_with(index + 1, ToolCallBuilder::default);
161        }
162        let Some(builder) = builders.get_mut(index) else {
163            continue;
164        };
165
166        builder.apply_delta(delta);
167    }
168}
169
170fn finalize_tool_calls(builders: Vec<ToolCallBuilder>) -> Option<Vec<ToolCall>> {
171    let calls: Vec<ToolCall> = builders.into_iter().filter_map(ToolCallBuilder::finalize).collect();
172
173    (!calls.is_empty()).then_some(calls)
174}
175
176/// Helper to aggregate streaming events and produce a final LLMResponse.
177pub(crate) struct StreamAggregator {
178    model: String,
179    pub(crate) content: String,
180    pub(crate) reasoning: String,
181    reasoning_details: Vec<String>,
182    reasoning_buffer: ReasoningBuffer,
183    pub(crate) tool_builders: Vec<ToolCallBuilder>,
184    pub(crate) usage: Option<crate::provider::Usage>,
185    finish_reason: crate::provider::FinishReason,
186    pub(crate) sanitizer: TagStreamSanitizer,
187    pub(crate) compaction: Option<String>,
188}
189
190#[derive(Clone, Copy, Debug, PartialEq, Eq)]
191pub enum OpenAiDeltaOrder {
192    ReasoningFirst,
193    ContentFirst,
194}
195
196fn emit_reasoning_delta(
197    aggregator: &mut StreamAggregator,
198    tx: &tokio::sync::mpsc::UnboundedSender<Result<LLMStreamEvent, LLMError>>,
199    delta: &Value,
200    reasoning_fields: &[&'static str],
201) {
202    // Pick the first non-empty reasoning field, allowing providers to declare a
203    // fallback order (e.g. `["reasoning", "reasoning_content"]`).
204    // Empty strings are skipped so that a present-but-empty primary field
205    // does not block fallback to the next candidate.
206    let Some(reasoning) = reasoning_fields
207        .iter()
208        .find_map(|field| delta.get(*field).and_then(Value::as_str).filter(|s| !s.is_empty()))
209    else {
210        return;
211    };
212    let Some(delta) = aggregator.handle_reasoning(reasoning) else {
213        return;
214    };
215    let _ = tx.send(Ok(LLMStreamEvent::Reasoning { delta }));
216}
217
218fn emit_content_delta(
219    aggregator: &mut StreamAggregator,
220    tx: &tokio::sync::mpsc::UnboundedSender<Result<LLMStreamEvent, LLMError>>,
221    delta: &Value,
222) {
223    let Some(content) = delta.get("content").and_then(Value::as_str) else {
224        return;
225    };
226    for event in aggregator.handle_content(content) {
227        let _ = tx.send(Ok(event));
228    }
229}
230
231pub(crate) fn handle_openai_compatible_chunk(
232    value: &Value,
233    aggregator: &mut StreamAggregator,
234    tx: &tokio::sync::mpsc::UnboundedSender<Result<LLMStreamEvent, LLMError>>,
235    reasoning_fields: &[&'static str],
236    delta_order: OpenAiDeltaOrder,
237    include_cache_metrics: bool,
238) {
239    if let Some(choices) = value.get("choices").and_then(Value::as_array)
240        && let Some(choice) = choices.first()
241    {
242        if let Some(delta) = choice.get("delta") {
243            match delta_order {
244                OpenAiDeltaOrder::ReasoningFirst => {
245                    emit_reasoning_delta(aggregator, tx, delta, reasoning_fields);
246                    emit_content_delta(aggregator, tx, delta);
247                }
248                OpenAiDeltaOrder::ContentFirst => {
249                    emit_content_delta(aggregator, tx, delta);
250                    emit_reasoning_delta(aggregator, tx, delta, reasoning_fields);
251                }
252            }
253
254            if let Some(tool_calls) = delta.get("tool_calls").and_then(Value::as_array) {
255                aggregator.handle_tool_calls(tool_calls);
256            }
257        }
258
259        if let Some(reason) = choice.get("finish_reason").and_then(Value::as_str) {
260            aggregator.set_finish_reason(map_finish_reason_common(reason));
261        }
262    }
263
264    if let Some(_usage_value) = value.get("usage")
265        && let Some(usage) = crate::providers::common::parse_usage_openai_format(value, include_cache_metrics)
266    {
267        aggregator.set_usage(usage);
268    }
269}
270
271impl StreamAggregator {
272    pub(crate) fn new(model: String) -> Self {
273        Self {
274            model,
275            content: String::new(),
276            reasoning: String::new(),
277            reasoning_details: Vec::new(),
278            reasoning_buffer: ReasoningBuffer::default(),
279            tool_builders: Vec::new(),
280            usage: None,
281            finish_reason: crate::provider::FinishReason::Stop,
282            sanitizer: TagStreamSanitizer::new(),
283            compaction: None,
284        }
285    }
286
287    /// Process a content delta, applying sanitization for reasoning tags.
288    pub(crate) fn handle_content(&mut self, delta: &str) -> Vec<LLMStreamEvent> {
289        self.content.push_str(delta);
290        self.sanitizer.process_chunk(delta)
291    }
292
293    /// Process a reasoning delta from a dedicated field.
294    pub(crate) fn handle_reasoning(&mut self, delta: &str) -> Option<String> {
295        let result = self.reasoning_buffer.push(delta);
296        if let Some(ref d) = result {
297            self.reasoning.push_str(d);
298        }
299        result
300    }
301
302    /// Store structured reasoning details received from streaming deltas.
303    pub(crate) fn set_reasoning_details(&mut self, details: &[Value]) {
304        if details.is_empty() {
305            return;
306        }
307
308        self.reasoning_details = details
309            .iter()
310            .map(|detail| detail.as_str().map(ToOwned::to_owned).unwrap_or_else(|| detail.to_string()))
311            .collect();
312    }
313
314    /// Append a completed structured item received from a streaming
315    /// output-item event.
316    pub(crate) fn append_reasoning_detail(&mut self, detail: &Value) {
317        let serialized = detail.as_str().map(ToOwned::to_owned).unwrap_or_else(|| detail.to_string());
318        if !self.reasoning_details.iter().any(|existing| existing == &serialized) {
319            self.reasoning_details.push(serialized);
320        }
321    }
322
323    /// Process tool call deltas.
324    pub(crate) fn handle_tool_calls(&mut self, deltas: &[Value]) {
325        update_tool_calls(&mut self.tool_builders, deltas);
326    }
327
328    /// Set usage metrics.
329    pub(crate) fn set_usage(&mut self, usage: crate::provider::Usage) {
330        self.usage = Some(usage);
331    }
332
333    /// Set finish reason.
334    pub(crate) fn set_finish_reason(&mut self, reason: crate::provider::FinishReason) {
335        self.finish_reason = reason;
336    }
337
338    /// Finalize and produce the completed LLMResponse.
339    pub(crate) fn finalize(mut self) -> LLMResponse {
340        // Collect any leftover bits from sanitizer
341        for event in self.sanitizer.finalize() {
342            match event {
343                LLMStreamEvent::Token { delta } => {
344                    self.content.push_str(&delta);
345                }
346                LLMStreamEvent::Reasoning { delta } => {
347                    self.reasoning.push_str(&delta);
348                }
349                _ => {}
350            }
351        }
352
353        let reasoning_details = if self.reasoning_details.is_empty() {
354            None
355        } else {
356            Some(self.reasoning_details)
357        };
358        let mut reasoning = if self.reasoning.is_empty() {
359            self.reasoning_buffer.finalize()
360        } else {
361            Some(self.reasoning)
362        };
363        if reasoning.is_none() {
364            reasoning = reasoning_details
365                .as_ref()
366                .and_then(|details| extract_reasoning_text_from_serialized_details(details));
367        }
368
369        LLMResponse {
370            content: if self.content.is_empty() {
371                None
372            } else {
373                Some(self.content)
374            },
375            tool_calls: finalize_tool_calls(self.tool_builders),
376            model: self.model,
377            usage: self.usage,
378            finish_reason: self.finish_reason,
379            reasoning,
380            reasoning_details,
381            tool_references: Vec::new(),
382            request_id: None,
383            organization_id: None,
384            compaction: self.compaction,
385        }
386    }
387}
388
389/// Common helper for processing OpenAI-compatible SSE streams.
390///
391/// This simplifies stream implementations across providers like DeepSeek, ZAI, Moonshot, etc.
392/// Especially optimized for high-performance models like Gemini 3 and GLM-5.
393pub(crate) async fn process_openai_stream<S, E, F>(
394    mut byte_stream: S,
395    provider_name: &'static str,
396    model: String,
397    mut on_chunk: F,
398) -> Result<LLMResponse, LLMError>
399where
400    S: futures::Stream<Item = Result<bytes::Bytes, E>> + Unpin,
401    E: std::fmt::Display,
402    F: FnMut(Value) -> Result<(), LLMError>,
403{
404    use crate::providers::error_handling::format_network_error;
405    use futures::StreamExt;
406
407    let mut buf: Vec<u8> = Vec::new();
408    let mut offset = 0usize;
409    let mut decoder = Utf8StreamDecoder::new();
410    let mut last_response_value = None;
411
412    while let Some(chunk_result) = byte_stream.next().await {
413        let chunk_bytes = chunk_result.map_err(|e| format_network_error(provider_name, &e.to_string()))?;
414        decoder.push_bytes(&chunk_bytes, &mut buf);
415
416        while let Some((boundary_idx, boundary_len)) = find_sse_boundary_bytes(&buf, offset) {
417            let event = std::str::from_utf8(&buf[offset..boundary_idx]).expect("valid utf-8 stream data");
418            offset = boundary_idx + boundary_len;
419
420            if let Some(data) = extract_data_payload(event) {
421                if data == "[DONE]" {
422                    break;
423                }
424
425                for line in data.lines() {
426                    let trimmed = line.trim();
427                    if trimmed.is_empty() {
428                        continue;
429                    }
430
431                    if let Ok(value) = serde_json::from_str::<Value>(trimmed) {
432                        on_chunk(value.clone())?;
433                        last_response_value = Some(value);
434                    }
435                }
436            }
437        }
438
439        // Drain the consumed prefix so `buf` stays bounded to the unprocessed
440        // tail rather than growing for the entire stream lifetime.
441        if offset > 0 {
442            buf.drain(..offset);
443            offset = 0;
444        }
445
446        // Fail closed: a peer that never emits an event boundary must not
447        // grow the retained tail without bound. Measured after the drain so
448        // one large-but-complete event still parses.
449        if let Err(overflow) = check_sse_tail_bound(buf.len()) {
450            let message = error_display::format_llm_error(provider_name, &overflow.to_string());
451            return Err(LLMError::Provider { message, metadata: None });
452        }
453    }
454
455    // Attempt to extract final response metadata (usage, etc) from last chunk if not already done
456    let mut final_response = LLMResponse {
457        content: None,
458        tool_calls: None,
459        model,
460        usage: None,
461        finish_reason: crate::provider::FinishReason::Stop,
462        reasoning: None,
463        reasoning_details: None,
464        tool_references: Vec::new(),
465        request_id: None,
466        organization_id: None,
467        compaction: None,
468    };
469
470    if let Some(value) = last_response_value
471        && value.get("usage").is_some()
472    {
473        final_response.usage = crate::providers::common::parse_usage_openai_format(&value, true);
474    }
475
476    Ok(final_response)
477}
478
479pub(crate) fn parse_openai_tool_calls(calls: &[Value]) -> Vec<ToolCall> {
480    calls
481        .iter()
482        .filter_map(|call| {
483            let id = call.get("id").and_then(|v| v.as_str())?;
484            let function = call.get("function")?;
485            let namespace = call
486                .get("namespace")
487                .and_then(|v| v.as_str())
488                .or_else(|| function.get("namespace").and_then(|v| v.as_str()))
489                .map(ToOwned::to_owned);
490            let name = function.get("name").and_then(|v| v.as_str())?;
491            let arguments = function.get("arguments");
492            let serialized = arguments.map_or_else(
493                || "{}".to_string(),
494                |value| {
495                    if value.is_string() {
496                        value.as_str().unwrap_or("").to_string()
497                    } else {
498                        value.to_string()
499                    }
500                },
501            );
502            Some(ToolCall::function_with_namespace(id.to_string(), namespace, name.to_string(), serialized))
503        })
504        .collect()
505}
506
507fn push_unique_tool_reference(tool_references: &mut Vec<String>, tool_name: &str) {
508    if !tool_references.iter().any(|existing| existing == tool_name) {
509        tool_references.push(tool_name.to_string());
510    }
511}
512
513pub(crate) fn collect_tool_references_from_tool_search_output(value: &Value, tool_references: &mut Vec<String>) {
514    match value {
515        Value::Array(items) => {
516            for item in items {
517                collect_tool_references_from_tool_search_output(item, tool_references);
518            }
519        }
520        Value::Object(object) => {
521            if let Some(tools) = object.get("tools").and_then(Value::as_array) {
522                for tool in tools {
523                    collect_tool_references_from_tool_search_output(tool, tool_references);
524                }
525            } else if let Some(tool_name) = object.get("tool_name").and_then(Value::as_str) {
526                push_unique_tool_reference(tool_references, tool_name);
527            } else if let Some(function) = object.get("function").and_then(Value::as_object)
528                && let Some(tool_name) = function.get("name").and_then(Value::as_str)
529            {
530                push_unique_tool_reference(tool_references, tool_name);
531            } else if let Some(tool_name) = object.get("name").and_then(Value::as_str) {
532                push_unique_tool_reference(tool_references, tool_name);
533            }
534
535            if let Some(tool_refs) = object.get("tool_references").and_then(Value::as_array) {
536                for tool_ref in tool_refs {
537                    collect_tool_references_from_tool_search_output(tool_ref, tool_references);
538                }
539            }
540        }
541        _ => {}
542    }
543}
544
545fn append_text_with_reasoning(
546    text: &str,
547    aggregated_content: &mut String,
548    reasoning: &mut ReasoningBuffer,
549    deltas: &mut StreamDelta,
550    telemetry: &impl StreamTelemetry,
551) {
552    let (segments, cleaned) = split_reasoning_from_text(text);
553
554    if segments.is_empty() && cleaned.is_none() {
555        if !text.is_empty() {
556            aggregated_content.push_str(text);
557            deltas.push_content(text);
558            telemetry.on_content_delta(text);
559        }
560        return;
561    }
562
563    for segment in segments {
564        if let Some(stage) = &segment.stage {
565            telemetry.on_reasoning_stage(stage);
566        }
567        if let Some(delta) = reasoning.push(&segment.text) {
568            telemetry.on_reasoning_delta(&delta);
569            deltas.push_reasoning(&delta);
570        }
571    }
572
573    if let Some(cleaned_text) = cleaned
574        && !cleaned_text.is_empty()
575    {
576        aggregated_content.push_str(&cleaned_text);
577        telemetry.on_content_delta(&cleaned_text);
578        deltas.push_content(&cleaned_text);
579    }
580}
581
582fn apply_tool_call_delta_from_content(
583    builders: &mut Vec<ToolCallBuilder>,
584    container: &Map<String, Value>,
585    telemetry: &impl StreamTelemetry,
586) {
587    apply_tool_call_delta_with_index(builders, container, telemetry, None, None);
588}
589
590fn apply_tool_call_delta_with_index(
591    builders: &mut Vec<ToolCallBuilder>,
592    container: &Map<String, Value>,
593    telemetry: &impl StreamTelemetry,
594    fallback_index: Option<usize>,
595    fallback_id: Option<Value>,
596) {
597    fn extract_tool_call_id(container: &Map<String, Value>) -> Option<Value> {
598        container.get("id").cloned().or_else(|| {
599            container
600                .get("tool_call")
601                .and_then(|value| value.as_object())
602                .and_then(|inner| inner.get("id"))
603                .cloned()
604        })
605    }
606
607    let explicit_index = container
608        .get("tool_call")
609        .and_then(|value| value.as_object())
610        .and_then(|tool_call| tool_call.get("index"))
611        .and_then(|value| value.as_u64())
612        .or_else(|| container.get("index").and_then(|value| value.as_u64()));
613
614    let index = explicit_index.map(|value| value as usize).or(fallback_index).unwrap_or(0);
615
616    let current_id = extract_tool_call_id(container).or_else(|| fallback_id.clone());
617
618    if let Some(nested) = container.get("delta").and_then(|value| value.as_object()) {
619        apply_tool_call_delta_with_index(builders, nested, telemetry, Some(index), current_id.clone());
620    }
621
622    let delta_source = container
623        .get("tool_call")
624        .and_then(|value| value.as_object())
625        .unwrap_or(container);
626
627    let mut delta_map = Map::new();
628
629    if let Some(id_value) = extract_tool_call_id(delta_source).or_else(|| current_id.clone()) {
630        delta_map.insert("id".to_string(), id_value);
631    }
632
633    if let Some(function_value) = delta_source.get("function").or_else(|| container.get("function")) {
634        delta_map.insert("function".to_string(), function_value.clone());
635    }
636
637    if delta_map.is_empty() {
638        return;
639    }
640
641    if builders.len() <= index {
642        builders.resize_with(index + 1, ToolCallBuilder::default);
643    }
644
645    let mut deltas = vec![Value::Null; index + 1];
646    deltas[index] = Value::Object(delta_map);
647    update_tool_calls(builders, &deltas);
648    telemetry.on_tool_call_delta();
649}
650
651#[cfg(test)]
652mod tests;