From 1c9c8aec2c4b96b1fba70c4e2159cab1bc5a5bb7 Mon Sep 17 00:00:00 2001 From: Dmitry Voropaev Date: Wed, 7 Oct 2026 19:01:35 +0300 Subject: [PATCH] fix(protocol): normalize Anthropic's refusal stop reason when streaming stop_reason_from_str, which the stream accumulator uses to fold a streamed response into a buffered one, knows content_filter but not refusal, the spelling Anthropic actually sends. The buffered Anthropic codec does map it (map_anthropic_stop_reason in codecs/anthropic/buffered.rs), so the same provider value means two different things depending on whether the response arrived buffered or was folded out of a stream: refusal -> Some(Unknown) <- streamed content_filter -> Some(ContentFilter) Unknown then encodes back as end_turn for Anthropic and stop for Chat, and the gen_ai.response.finish_reasons attribute reads unknown, so a refusal is served to the client as a normal finish. One arm, plus a test over the whole vocabulary both codecs share. Signed-off-by: Dmitry Voropaev --- crates/protocol/src/stream.rs | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/protocol/src/stream.rs b/crates/protocol/src/stream.rs index c59a66f772..76b90a7df3 100644 --- a/crates/protocol/src/stream.rs +++ b/crates/protocol/src/stream.rs @@ -506,7 +506,9 @@ fn stop_reason_from_str(reason: Option<&str>) -> StopReason { match reason { Some("length" | "max_tokens") => StopReason::MaxTokens, Some("tool_calls" | "function_call" | "tool_use") => StopReason::ToolUse, - Some("content_filter") => StopReason::ContentFilter, + // Anthropic spells a content-policy stop `refusal`; the buffered codec + // already maps it (anthropic/buffered.rs, map_anthropic_stop_reason). + Some("content_filter" | "refusal") => StopReason::ContentFilter, Some("stop" | "end_turn" | "stop_sequence") | None => StopReason::EndTurn, Some(_) => StopReason::Unknown, } @@ -563,6 +565,33 @@ mod tests { ); } + #[test] + fn stop_reason_spellings_normalize_the_same_streamed_as_buffered() { + // A stop reason has to mean the same thing whether the response arrived + // buffered or was folded out of a stream. The expectations here are the + // ones the codecs apply to a buffered body. + for (reason, expected) in [ + ("length", StopReason::MaxTokens), + ("max_tokens", StopReason::MaxTokens), + ("tool_calls", StopReason::ToolUse), + ("tool_use", StopReason::ToolUse), + ("content_filter", StopReason::ContentFilter), + ("refusal", StopReason::ContentFilter), + ("stop", StopReason::EndTurn), + ("end_turn", StopReason::EndTurn), + ] { + let agg = fold(vec![LlmResponseChunk::MessageStop { + reason: Some(reason.to_string()), + }]); + + assert_eq!( + agg.outputs.first().and_then(|output| output.stop_reason), + Some(expected), + "stop reason {reason:?}" + ); + } + } + #[test] fn aggregates_normalized_chunks_inside_stream_event() { let response = LlmResponse::Stream(Box::pin(stream::iter([Ok(