Skip to main content

rig_core/providers/anthropic/
streaming.rs

1//! The Messages reply decoder, for a whole message and for the event stream
2//! alike. Each content block becomes one block, in wire order, whose
3//! provider item is the block as the provider states it complete, and only
4//! when the wire would take that item back.
5//!
6//! ```
7//! use rig_core::providers::anthropic::streaming::MessagesDecoder;
8//!
9//! let decoder = MessagesDecoder::new(false);
10//! # let _ = decoder;
11//! ```
12
13use std::collections::{BTreeMap, BTreeSet};
14
15use serde_json::{Map, Value, json};
16
17use crate::completion::FinishReason;
18use crate::error::ProviderError;
19use crate::json_utils::Lenient;
20use crate::message::{CallId, DocumentRange, Source, SourceLocation, ToolName};
21use crate::observe::ObservedError;
22use crate::operation::{Block, CallFragment, Completion, Finish};
23use crate::providers::internal::set_fields;
24use crate::providers::internal::wire;
25use crate::wire::{
26    AdapterVerdict, Decoder, Flow, ObservationSink, Out, WireCitation, WireEvent, WireFrame,
27};
28
29/// Recognized Messages event tags; any other tag classifies as unknown.
30/// `message` is the whole message a unary reply is.
31const KNOWN_EVENT_TYPES: &[&str] = &[
32    "message",
33    "message_start",
34    "content_block_start",
35    "content_block_delta",
36    "content_block_stop",
37    "message_delta",
38    "message_stop",
39    "ping",
40    "error",
41];
42
43/// One Messages event, or the whole message a unary reply is, as the
44/// provider sent it. The decoder reads each field it needs on its own, so
45/// an invented field, or a known one of another type, never fails a reply.
46#[derive(Debug, Clone, PartialEq)]
47pub struct MessagesEvent {
48    /// The event as sent.
49    pub fields: Value,
50    /// The frame's text when it is an `error` event, whose envelope is
51    /// reported verbatim.
52    raw: Option<String>,
53}
54
55impl MessagesEvent {
56    fn kind(&self) -> &str {
57        self.fields.str("type").unwrap_or_default()
58    }
59
60    /// The content block the event addresses.
61    fn index(&self) -> Result<usize, ProviderError> {
62        self.fields
63            .u64("index")
64            .and_then(|index| usize::try_from(index).ok())
65            .ok_or_else(|| {
66                ProviderError::Response(format!("Anthropic `{}` names no block index", self.kind()))
67            })
68    }
69
70    /// The block or delta under `key`, which must name its `type`.
71    fn item(&self, key: &str) -> Result<&Map<String, Value>, ProviderError> {
72        match self.fields.get(key) {
73            Some(Value::Object(item)) if item.get("type").is_some_and(Value::is_string) => Ok(item),
74            _ => Err(ProviderError::Response(format!(
75                "Anthropic `{}` carries no `{key}` with a string `type`",
76                self.kind()
77            ))),
78        }
79    }
80}
81
82/// Anthropic's usage counters, read leniently.
83#[derive(Debug, Clone, Default, PartialEq)]
84struct Counts {
85    input: Option<u64>,
86    output: Option<u64>,
87    cache_read: Option<u64>,
88    cache_creation: Option<u64>,
89    /// The per-TTL breakdown of `cache_creation`, as sent.
90    cache_creation_split: Option<Value>,
91    thinking: Option<u64>,
92}
93
94impl Counts {
95    fn of(usage: Option<&Value>) -> Self {
96        let count = |pointer: &str| usage?.at(pointer)?.as_u64_lenient();
97        Self {
98            input: count("/input_tokens"),
99            output: count("/output_tokens"),
100            cache_read: count("/cache_read_input_tokens"),
101            cache_creation: count("/cache_creation_input_tokens"),
102            cache_creation_split: usage
103                .and_then(|usage| usage.get("cache_creation"))
104                .filter(|split| split.is_object())
105                .cloned(),
106            thinking: count("/output_tokens_details/thinking_tokens"),
107        }
108    }
109
110    /// Rig's usage: its input is `input_tokens` plus the cache reads and
111    /// writes counted beside it, its output `output_tokens` (thinking
112    /// included), and its total their sum when both are known.
113    fn usage(&self) -> crate::completion::Usage {
114        let input = self.input.map(|uncached| {
115            uncached + self.cache_read.unwrap_or(0) + self.cache_creation.unwrap_or(0)
116        });
117        crate::completion::Usage {
118            input_tokens: input,
119            output_tokens: self.output,
120            cached_input_tokens: self.cache_read,
121            cache_creation_input_tokens: self.cache_creation,
122            reasoning_tokens: self.thinking,
123            total_tokens: input.zip(self.output).map(|(input, output)| input + output),
124            tool_use_prompt_tokens: None,
125            cost: None,
126        }
127    }
128}
129
130/// How a Messages `stop_reason` ends the turn, and the error a refusal
131/// reports. A reason Anthropic does not document is
132/// [`FinishReason::Other`], which fails the turn.
133fn finish_of(reason: &str, details: Option<&Value>) -> (Option<FinishReason>, Option<String>) {
134    let reason = match reason {
135        // `pause_turn` is a server-tool loop that stopped at its limit: the
136        // turn is replayed as it is to resume it (pi's rule).
137        "end_turn" | "stop_sequence" | "pause_turn" => FinishReason::Stop,
138        "max_tokens" | "model_context_window_exceeded" => FinishReason::Length,
139        "tool_use" => FinishReason::ToolCalls,
140        // A refusal fails the turn with its explanation (pi's rule).
141        "refusal" => {
142            let explanation = details
143                .and_then(|details| details.str("explanation"))
144                .filter(|explanation| !explanation.is_empty())
145                .unwrap_or("The model refused to complete the request");
146            return (
147                Some(FinishReason::ContentFilter),
148                Some(explanation.to_owned()),
149            );
150        }
151        other => FinishReason::Other(other.to_owned()),
152    };
153    (Some(reason), None)
154}
155
156/// One Messages citation as a whole-block [`WireCitation`]: Anthropic
157/// cites each text block as a whole. A location kind rig does not know, or
158/// one without the field that names its source, is `None` and stays only in
159/// the block's native item, as does `encrypted_index`. Document ranges end
160/// exclusive, pages count from 1, characters and blocks from 0.
161fn citation_of(citation: &Value) -> Option<WireCitation> {
162    let number = |key: &str| citation.u64(key).and_then(|n| u32::try_from(n).ok());
163    let range = |start: &str, end: &str| Some(number(start)?..number(end)?);
164    let location = match citation.str("type")? {
165        "char_location" => SourceLocation::Document {
166            index: number("document_index"),
167            id: citation.str("file_id").map(str::to_owned),
168            within: citation
169                .u64("start_char_index")
170                .zip(citation.u64("end_char_index"))
171                .map(|(start, end)| DocumentRange::Chars(start..end)),
172        },
173        "page_location" => SourceLocation::Document {
174            index: number("document_index"),
175            id: citation.str("file_id").map(str::to_owned),
176            within: range("start_page_number", "end_page_number").map(DocumentRange::Pages),
177        },
178        "content_block_location" => SourceLocation::Document {
179            index: number("document_index"),
180            id: citation.str("file_id").map(str::to_owned),
181            within: range("start_block_index", "end_block_index").map(DocumentRange::Blocks),
182        },
183        "search_result_location" => SourceLocation::SearchResult {
184            index: number("search_result_index")?,
185            source: citation.str("source")?.to_owned(),
186            blocks: range("start_block_index", "end_block_index"),
187        },
188        "web_search_result_location" => SourceLocation::Url {
189            url: citation.str("url")?.to_owned(),
190        },
191        _ => return None,
192    };
193    let mut source = Source::new(location);
194    if let Some(title) = citation
195        .str("document_title")
196        .or_else(|| citation.str("title"))
197    {
198        source = source.title(title);
199    }
200    if let Some(cited) = citation.str("cited_text") {
201        source = source.cited_text(cited);
202    }
203    Some(WireCitation::new(None, vec![source]))
204}
205
206/// What an open content block is, for the checks its end makes.
207#[derive(Debug, Clone, Copy, PartialEq, Eq)]
208enum Kind {
209    Text,
210    Thinking,
211    Redacted,
212    Call,
213    Opaque,
214}
215
216/// Decodes Messages replies, a whole message or a stream of events.
217/// `content_block_stop` states a block complete; a stop reason states every
218/// block still open complete, but a call whose input is not yet JSON.
219#[derive(Debug, Default)]
220pub struct MessagesDecoder {
221    /// Each open block's kind and the input JSON streamed to it.
222    open: BTreeMap<usize, (Kind, String)>,
223    /// Every index a block opened at, closed or not.
224    started: BTreeSet<usize>,
225    /// Whether a block other than a leading `fallback` marker opened.
226    opened: bool,
227    /// Whether the dialect takes thinking back without a signature.
228    unsigned_thinking: bool,
229    /// The counters `message_start` reported, for a terminal `message_delta`
230    /// that does not repeat them.
231    start: Counts,
232    message_id: Option<String>,
233    response_model: Option<String>,
234    container: Option<Value>,
235}
236
237impl MessagesDecoder {
238    /// A fresh decoder for one reply. `unsigned_thinking` is whether the
239    /// dialect takes thinking back without a signature.
240    pub fn new(unsigned_thinking: bool) -> Self {
241        Self {
242            unsigned_thinking,
243            ..Self::default()
244        }
245    }
246
247    /// Open the content block at `index` as the provider states it.
248    fn start(
249        &mut self,
250        index: usize,
251        block: Map<String, Value>,
252        out: &mut Out<'_, Completion>,
253    ) -> Result<(), ProviderError> {
254        self.started.insert(index);
255        let block = Value::Object(block);
256        let kind = block.str("type").unwrap_or_default();
257        // A leading `fallback` names the model that took over; one after
258        // output began is a fallback rig cannot represent (pi's rule).
259        if kind == "fallback" {
260            if self.opened {
261                return Err(ProviderError::Response(
262                    "Anthropic performed an unsupported mid-output model fallback".to_owned(),
263                ));
264            }
265            self.open.insert(index, (Kind::Opaque, String::new()));
266            return out.open(index, Block::Opaque { replay: false }, block);
267        }
268        self.opened = true;
269        let (opened, kind, text) = match kind {
270            "text" => (Block::Text, Kind::Text, block.str("text")),
271            "thinking" => (
272                Block::Reasoning { redacted: false },
273                Kind::Thinking,
274                block.str("thinking"),
275            ),
276            "redacted_thinking" => (Block::Reasoning { redacted: true }, Kind::Redacted, None),
277            "tool_use" => {
278                self.open.insert(index, (Kind::Call, String::new()));
279                let id = block.str("id").unwrap_or_default().to_owned();
280                let input = block.get("input").cloned().unwrap_or_default();
281                match ToolName::new(block.str("name").unwrap_or_default()) {
282                    Ok(name) => {
283                        let id = CallId::from_wire(&id);
284                        out.open(index, Block::Call { id, name }, block)?;
285                    }
286                    // A nameless call: the writer drops it with a warning.
287                    Err(_) => out.fragment(
288                        Some(index),
289                        CallFragment {
290                            id: Some(&id),
291                            ..CallFragment::default()
292                        },
293                    )?,
294                }
295                // A whole reply states the input on the block; a stream
296                // streams it, and the fragments win.
297                return out.announce(index, input);
298            }
299            _ => (Block::Opaque { replay: true }, Kind::Opaque, None),
300        };
301        let text = text.unwrap_or_default().to_owned();
302        let citations: Vec<WireCitation> = match kind {
303            Kind::Text => block
304                .arr("citations")
305                .iter()
306                .filter_map(citation_of)
307                .collect(),
308            _ => Vec::new(),
309        };
310        self.open.insert(index, (kind, String::new()));
311        out.open(index, opened, block)?;
312        for citation in citations {
313            out.cite(index, citation);
314        }
315        out.push(index, &text)
316    }
317
318    /// Apply a delta to the open block at `index`: text and reasoning grow
319    /// both the block and its item, input JSON is assembled, a citation is
320    /// appended to the item and cited, and any other delta merges into the
321    /// item by key.
322    fn delta(
323        &mut self,
324        index: usize,
325        delta: &Map<String, Value>,
326        out: &mut Out<'_, Completion>,
327    ) -> Result<(), ProviderError> {
328        let kind = delta
329            .get("type")
330            .and_then(Value::as_str)
331            .unwrap_or_default();
332        // The fragment a block is built from must be text.
333        let fragment = |key: &str| {
334            delta.get(key).and_then(Value::as_str).ok_or_else(|| {
335                ProviderError::Response(format!("Anthropic `{kind}` carries no string `{key}`"))
336            })
337        };
338        // A gateway that skips `content_block_start` still streams the
339        // block's text, so the first delta opens it.
340        if !self.started.contains(&index) {
341            let opened = match kind {
342                "text_delta" => Some(json!({"type": "text", "text": ""})),
343                "thinking_delta" => Some(json!({"type": "thinking", "thinking": ""})),
344                _ => None,
345            };
346            if let Some(Value::Object(block)) = opened {
347                self.start(index, block, out)?;
348            }
349        }
350        match kind {
351            "text_delta" => out.push(index, fragment("text")?)?,
352            "thinking_delta" => out.push(index, fragment("thinking")?)?,
353            "input_json_delta" => {
354                let fragment = fragment("partial_json")?;
355                let Some((kind @ (Kind::Call | Kind::Opaque), json)) = self.open.get_mut(&index)
356                else {
357                    return Err(ProviderError::Response(format!(
358                        "Anthropic streamed input to content block {index}, which takes none"
359                    )));
360                };
361                json.push_str(fragment);
362                if *kind == Kind::Call {
363                    out.push(index, fragment)?;
364                }
365                return Ok(());
366            }
367            "citations_delta" => {
368                let citation = delta.get("citation").cloned().unwrap_or_default();
369                let cited = citation_of(&citation);
370                out.edit(index, |item| {
371                    if let Some(item) = item.as_object_mut() {
372                        match item.get_mut("citations") {
373                            Some(Value::Array(citations)) => citations.push(citation),
374                            _ => {
375                                item.insert("citations".to_owned(), Value::Array(vec![citation]));
376                            }
377                        }
378                    }
379                })?;
380                if let Some(cited) = cited {
381                    out.cite(index, cited);
382                }
383                return Ok(());
384            }
385            _ => {}
386        }
387        // Text and signatures concatenate; `compaction_delta` and kinds
388        // rig has never seen land in the item too.
389        out.edit(index, |item| {
390            crate::operation::completion::merge(item, delta)
391        })
392    }
393
394    /// End the block at `index` as stated complete. Its item becomes the
395    /// block's native only when the wire takes it back: text that is not
396    /// blank, thinking with its signature (unless the dialect takes it
397    /// unsigned), redacted thinking with its data, and a call with an
398    /// object `input`, set from what streamed. A hosted item whose input is
399    /// not an object never completed.
400    fn stop(&mut self, index: usize, out: &mut Out<'_, Completion>) -> Result<(), ProviderError> {
401        let Some((kind, json)) = self.open.remove(&index) else {
402            return out.finish(index);
403        };
404        let streamed = (!json.is_empty()).then(|| crate::json_utils::parse_tool_arguments(&json));
405        let unsigned = self.unsigned_thinking;
406        let mut complete = true;
407        out.edit(index, |item| {
408            let input = match streamed {
409                Some(Ok(parsed)) => Ok(Some(parsed)),
410                Some(Err(_)) => Err(()),
411                None => Ok(item.get("input").cloned()),
412            };
413            let kept = match (kind, input) {
414                (Kind::Text, _) => !item.str("text").unwrap_or_default().trim().is_empty(),
415                (Kind::Thinking, _) => {
416                    unsigned || item.str("signature").is_some_and(|s| !s.is_empty())
417                }
418                (Kind::Redacted, _) => item.str("data").is_some_and(|data| !data.is_empty()),
419                (Kind::Opaque, Ok(None)) => true,
420                (Kind::Call | Kind::Opaque, Ok(Some(input @ Value::Object(_)))) => {
421                    crate::operation::completion::merge(
422                        item,
423                        &set_fields([("input", Some(input))]),
424                    );
425                    true
426                }
427                (Kind::Call, Ok(None | Some(Value::Null))) => {
428                    crate::operation::completion::merge(
429                        item,
430                        &set_fields([("input", Some(json!({})))]),
431                    );
432                    true
433                }
434                (Kind::Call, _) => false,
435                (Kind::Opaque, _) => {
436                    complete = false;
437                    true
438                }
439            };
440            if !kept {
441                *item = Value::Null;
442            }
443        })?;
444        if complete {
445            out.finish(index)
446        } else {
447            out.close(index)
448        }
449    }
450
451    /// Note the metadata a whole message or `message_start` states.
452    fn metadata(&mut self, message: &Value) {
453        self.start = Counts::of(message.get("usage"));
454        self.message_id = message.str("id").map(str::to_owned);
455        self.response_model = message.str("model").map(str::to_owned);
456        self.note_container(message.get("container"));
457    }
458
459    fn note_container(&mut self, container: Option<&Value>) {
460        self.container = container
461            .filter(|c| !c.is_null())
462            .or(self.container.as_ref())
463            .cloned();
464    }
465
466    /// End the reply with Anthropic's terminal record. Every block still
467    /// open is complete, but a call whose input is not JSON yet: the end of
468    /// the reply closes it unfinished. The container the reply ran in is a
469    /// last opaque block.
470    fn end(
471        &mut self,
472        usage: &Counts,
473        stop_reason: Option<&str>,
474        details: Option<&Value>,
475        mut out: Out<'_, Completion>,
476    ) -> Result<Flow, ProviderError> {
477        let open: Vec<usize> = self
478            .open
479            .iter()
480            .filter(|(_, (kind, json))| {
481                *kind != Kind::Call
482                    || json.is_empty()
483                    || crate::json_utils::parse_tool_arguments(json).is_ok_and(|v| v.is_object())
484            })
485            .map(|(index, _)| *index)
486            .collect();
487        for index in open {
488            self.stop(index, &mut out)?;
489        }
490        if let Some(container) = &self.container {
491            let index = out.fresh_index();
492            let item = json!({ "type": "container", "container": container });
493            out.whole(index, Block::Opaque { replay: true }, item, "")?;
494        }
495        let (reason, error) = stop_reason.map_or((None, None), |reason| finish_of(reason, details));
496        Ok(out.end(Finish {
497            usage: usage.usage(),
498            reason,
499            response_id: self.message_id.clone(),
500            model: self.response_model.clone(),
501            error,
502        }))
503    }
504
505    /// A whole message, written block by block through the calls a stream
506    /// makes, then ended. Empty content is a turn like any other, as it is
507    /// streamed (pi's rule): the stop reason decides how it ends.
508    fn whole(
509        &mut self,
510        mut message: Value,
511        mut out: Out<'_, Completion>,
512    ) -> Result<Flow, ProviderError> {
513        self.metadata(&message);
514        let content = match message.get_mut("content").map(Value::take) {
515            Some(Value::Array(content)) => content,
516            _ => Vec::new(),
517        };
518        for (index, block) in content.into_iter().enumerate() {
519            let block = match block {
520                Value::Object(block) if block.get("type").is_some_and(Value::is_string) => block,
521                _ => {
522                    return Err(ProviderError::Response(format!(
523                        "Anthropic content block {index} has no string `type`"
524                    )));
525                }
526            };
527            self.start(index, block, &mut out)?;
528            self.stop(index, &mut out)?;
529        }
530        let usage = self.start.clone();
531        self.end(
532            &usage,
533            message.str("stop_reason"),
534            message.get("stop_details"),
535            out,
536        )
537    }
538
539    /// The stream's terminal `message_delta` counters, falling back to
540    /// `message_start`'s for those it omits.
541    fn terminal(&self, usage: Option<&Value>) -> Counts {
542        let (terminal, start) = (Counts::of(usage), self.start.clone());
543        Counts {
544            // Zero-as-missing is a gateway heuristic for the input count
545            // only, not a rule for cache counts.
546            input: terminal.input.filter(|tokens| *tokens > 0).or(start.input),
547            cache_read: terminal.cache_read.or(start.cache_read),
548            cache_creation: terminal.cache_creation.or(start.cache_creation),
549            cache_creation_split: terminal.cache_creation_split.or(start.cache_creation_split),
550            ..terminal
551        }
552    }
553}
554
555impl<'id> Decoder<'id, Completion> for MessagesDecoder {
556    type Event = MessagesEvent;
557
558    fn classify(&self, frame: WireFrame) -> WireEvent<MessagesEvent> {
559        let data = frame.as_str();
560        wire::classify_tagged_frame::<Value>(&data, "type", |tag| KNOWN_EVENT_TYPES.contains(&tag))
561            .map(|fields| {
562                // The one event whose payload leaves this crate as bytes rather
563                // than as decoded fields, so it is captured where the frame is
564                // still in hand.
565                let raw = (fields.str("type") == Some("error")).then(|| data.to_string());
566                MessagesEvent { fields, raw }
567            })
568    }
569
570    fn decode(
571        &mut self,
572        event: MessagesEvent,
573        mut out: Out<'id, Completion>,
574    ) -> Result<Flow, ProviderError> {
575        match event.kind() {
576            "message" => return self.whole(event.fields, out),
577            // A `message_start` without a message body (a Bedrock-compatible
578            // gateway sends one) is a no-op.
579            "message_start" => {
580                if let Some(message) = event.fields.get("message").filter(|m| m.is_object()) {
581                    self.metadata(message);
582                }
583            }
584            "content_block_start" => {
585                let block = event.item("content_block")?.clone();
586                self.start(event.index()?, block, &mut out)?;
587            }
588            "content_block_delta" => {
589                let delta = event.item("delta")?;
590                self.delta(event.index()?, delta, &mut out)?;
591            }
592            "content_block_stop" => self.stop(event.index()?, &mut out)?,
593            "message_delta" => {
594                let delta = event.fields.get("delta");
595                self.note_container(delta.and_then(|delta| delta.get("container")));
596                // Only a `message_delta` carrying a stop reason is the
597                // provider's end; without one it is a no-op.
598                let Some(reason) = delta.and_then(|delta| delta.str("stop_reason")) else {
599                    return Ok(Flow::More);
600                };
601                let usage = self.terminal(event.fields.get("usage"));
602                let details = delta.and_then(|delta| delta.get("stop_details"));
603                return self.end(&usage, Some(reason), details, out);
604            }
605            // Preserve the complete error envelope rather than re-encode
606            // modeled fields.
607            "error" => {
608                return Err(ProviderError::from_provider_body(
609                    event.raw.unwrap_or_default(),
610                ));
611            }
612            // `message_stop`, `ping`, and nothing else: the classifier
613            // passes only the listed tags.
614            _ => {}
615        }
616        Ok(Flow::More)
617    }
618}
619
620impl MessagesDecoder {
621    /// Messages metadata projected before normalization can discard it: the
622    /// stop reason, the model, the message id and any error envelope, on the
623    /// unary reply and on the stream's `message_start`, `message_delta` and
624    /// `error` events.
625    pub(crate) fn project(payload: &[u8], sink: &mut ObservationSink<'_>) {
626        let Ok(payload) = serde_json::from_slice::<Value>(payload) else {
627            return;
628        };
629        let fields = payload
630            .get("message")
631            .filter(|m| m.is_object())
632            .unwrap_or(&payload);
633        let stop_reason = fields
634            .str("stop_reason")
635            .or_else(|| payload.at("/delta/stop_reason").and_then(Value::as_str));
636        let verdict = AdapterVerdict {
637            finish_reason: stop_reason.map(|reason| sink.scrub(reason)),
638            block_reason: None,
639            detail: None,
640            model: fields.str("model").map(|model| sink.scrub(model)),
641        };
642        let response_id = fields.str("id").map(|id| sink.scrub(id));
643        sink.provider(verdict, response_id);
644        if let Some(error) = ObservedError::of(&payload) {
645            error.emit(sink);
646        }
647    }
648}
649
650pub(crate) mod document;
651
652/// The document a Messages reply reassembles into.
653pub use document::Message as MessagesDocument;
654
655#[cfg(test)]
656mod tests;