Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion crates/protocol/src/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand Down Expand Up @@ -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(
Expand Down
Loading