Skip to content
Open
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -1439,7 +1439,7 @@ pub(super) fn decode_anthropic_refusal(details: Option<&Value>) -> String {
// Maps Anthropic stop reasons to normalized stop reasons.
fn map_anthropic_stop_reason(reason: Option<&str>) -> StopReason {
match reason {
Some("max_tokens") => StopReason::MaxTokens,
Some("max_tokens" | "model_context_window_exceeded") => StopReason::MaxTokens,
Some("tool_use") => StopReason::ToolUse,
Some("refusal") => StopReason::ContentFilter,
Some("end_turn") | None => StopReason::EndTurn,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,12 @@ fn decode_anthropic_stream(
.and_then(|delta| delta.get("stop_reason"))
.and_then(Value::as_str)
{
// Remember the provider stop reason: Anthropic delivers it here, on
// A context-window cutoff truncates the answer just like `max_tokens`.
let stop_reason = match stop_reason {
"model_context_window_exceeded" => "max_tokens",
reason => reason,
};
// Remember the normalized stop reason: Anthropic delivers it here, on
// `message_delta`, while the terminal `message_stop` carries none of its own.
if stop_reason == "refusal" && state.stop_reason.as_deref() != Some("refusal") {
out.push(LlmResponseChunk::TextDelta {
Expand Down
40 changes: 40 additions & 0 deletions crates/switchyard-translation/tests/response_translation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1323,6 +1323,46 @@ fn incomplete_responses_source_survives_translation() -> TestResult {
Ok(())
}

// Verifies Anthropic's context-window stop is reported as a token limit.
#[test]
fn anthropic_context_window_stop_translates_to_token_limit() -> TestResult {
let engine = TranslationEngine::default();
let body = json!({
"id": "msg_test",
"type": "message",
"role": "assistant",
"model": "claude-sonnet",
"content": [{"type": "text", "text": "Half an ans"}],
"stop_reason": "model_context_window_exceeded",
"usage": {"input_tokens": 12, "output_tokens": 7}
});

let chat = engine
.translate_response(
WireFormat::AnthropicMessages,
WireFormat::OpenAiChat,
&body,
&TranslationPolicy::default(),
)?
.body;
assert_eq!(chat["choices"][0]["finish_reason"], "length");

let responses = engine
.translate_response(
WireFormat::AnthropicMessages,
WireFormat::OpenAiResponses,
&body,
&TranslationPolicy::default(),
)?
.body;
assert_eq!(responses["status"], "incomplete");
assert_eq!(
responses["incomplete_details"],
json!({"reason": "max_output_tokens"})
);
Ok(())
}

// Verifies an incomplete Responses source reports its reason to Chat and Anthropic
// clients, including when the response has no output items.
#[test]
Expand Down
59 changes: 59 additions & 0 deletions crates/switchyard-translation/tests/stream_translation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2680,6 +2680,65 @@ fn anthropic_max_tokens_stop_translates_to_responses_incomplete_event() -> TestR
Ok(())
}

// Verifies a streamed Anthropic context-window stop is reported as a token limit.
#[test]
fn anthropic_context_window_stop_streams_as_token_limit() -> TestResult {
let engine = TranslationEngine::default();
let delta = json!({
"type": "message_delta",
"delta": {"stop_reason": "model_context_window_exceeded"},
"usage": {"output_tokens": 1}
});

let mut state =
StreamTranslationState::new(WireFormat::AnthropicMessages, WireFormat::OpenAiChat);
let mut events = engine.translate_event(
&mut state,
WireFormat::AnthropicMessages,
WireFormat::OpenAiChat,
&delta,
)?;
events.extend(engine.finish_stream(&mut state, WireFormat::OpenAiChat)?);
let finish_reasons: Vec<&Value> = events
.iter()
.map(|event| &event["choices"][0]["finish_reason"])
.filter(|reason| !reason.is_null())
.collect();
assert_eq!(finish_reasons, vec!["length"]);

let mut state =
StreamTranslationState::new(WireFormat::AnthropicMessages, WireFormat::OpenAiResponses);
let mut events = engine.translate_event(
&mut state,
WireFormat::AnthropicMessages,
WireFormat::OpenAiResponses,
&delta,
)?;
events.extend(engine.finish_stream(&mut state, WireFormat::OpenAiResponses)?);
let Some(terminal) = events.last() else {
return Err("finish should emit a terminal Responses event".into());
};
assert_eq!(terminal["type"], "response.incomplete");
assert_eq!(
terminal["response"]["incomplete_details"],
json!({"reason": "max_output_tokens"})
);

// The server buffers a stream through the accumulator before encoding it.
let mut state =
StreamTranslationState::new(WireFormat::AnthropicMessages, WireFormat::AnthropicMessages);
let decoded = engine.decode_stream_event(&mut state, WireFormat::AnthropicMessages, delta)?;
let mut accumulator = ResponseAccumulator::new();
for chunk in decoded.normalized() {
accumulator.push(chunk.clone());
}
assert_eq!(
accumulator.finish().outputs[0].stop_reason,
Some(StopReason::MaxTokens)
);
Ok(())
}

// Verifies a streamed response.incomplete from a Responses upstream reaches a Chat client.
#[test]
fn responses_incomplete_event_translates_to_chat_length_finish() -> TestResult {
Expand Down
Loading