Skip to content

Commit 43a6312

Browse files
Python: fix(anthropic): map every Anthropic stop reason instead of raising KeyError (#14616)
### Motivation and Context `AnthropicChatCompletion` fails whenever Claude ends a reply with a stop reason other than `end_turn`, `max_tokens` or `tool_use`. `ANTHROPIC_TO_SEMANTIC_KERNEL_FINISH_REASON_MAP` only has those three and is indexed with `[...]`, while the Anthropic API also returns `stop_sequence` (whenever one of the request's `stop_sequences` ends the reply), `refusal`, `pause_turn` and `model_context_window_exceeded`. For example, any call with `stop_sequences` that stops on one of them: - non-streaming: `get_chat_message_content` raises `KeyError: 'stop_sequence'`; - streaming: `get_streaming_chat_message_content` raises `ServiceResponseException`, caused by the same `KeyError`. ### Description - `stop_sequence` → `FinishReason.STOP`, `model_context_window_exceeded` → `FinishReason.LENGTH`, `refusal` → `FinishReason.CONTENT_FILTER`. - Both lookups (`_create_chat_message_content` and `_create_streaming_chat_message_content`) use `.get(...)`, so a stop reason without a Semantic Kernel equivalent (`pause_turn`, or one added later) leaves `finish_reason` unset instead of failing the call. Reproduced end to end with `AnthropicChatCompletion` and a real `AsyncAnthropic` client against a local endpoint that returns `stop_reason: "stop_sequence"`: before, both calls raise; after, the non-streaming call returns the message with `FinishReason.STOP` and the stream completes. ### Contribution Checklist - [x] The code builds clean without any errors or warnings - [x] The PR follows the [SK Contribution Guidelines](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md) and the [pre-submission formatting script](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md#development-scripts) raises no violations - [x] All unit tests pass, and I have added new tests where possible - [x] I didn't break anyone 😄 Tests: `test_stop_reason_maps_to_finish_reason` in `tests/unit/connectors/ai/anthropic/services/test_anthropic_chat_completion.py`, parametrized over all seven Anthropic stop reasons, checks both the streaming and non-streaming conversion. The four unmapped ones fail on `main` with `KeyError`. `tests/unit/connectors/ai/anthropic`: 42 passed. `ruff format`, `ruff check` and `mypy` on the changed module are clean. This change was written with Claude Code; the tests and the reproduction above were run before opening the PR. Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 8d46973 commit 43a6312

2 files changed

Lines changed: 43 additions & 2 deletions

File tree

‎python/semantic_kernel/connectors/ai/anthropic/services/anthropic_chat_completion.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,11 @@
6565
# map finish reasons from Anthropic to Semantic Kernel
6666
ANTHROPIC_TO_SEMANTIC_KERNEL_FINISH_REASON_MAP = {
6767
"end_turn": SemanticKernelFinishReason.STOP,
68+
"stop_sequence": SemanticKernelFinishReason.STOP,
6869
"max_tokens": SemanticKernelFinishReason.LENGTH,
70+
"model_context_window_exceeded": SemanticKernelFinishReason.LENGTH,
6971
"tool_use": SemanticKernelFinishReason.TOOL_CALLS,
72+
"refusal": SemanticKernelFinishReason.CONTENT_FILTER,
7073
}
7174

7275
logger: logging.Logger = logging.getLogger(__name__)
@@ -274,7 +277,7 @@ def _create_chat_message_content(
274277

275278
finish_reason = None
276279
if response.stop_reason:
277-
finish_reason = ANTHROPIC_TO_SEMANTIC_KERNEL_FINISH_REASON_MAP[response.stop_reason]
280+
finish_reason = ANTHROPIC_TO_SEMANTIC_KERNEL_FINISH_REASON_MAP.get(response.stop_reason)
278281

279282
return ChatMessageContent(
280283
inner_content=response,
@@ -312,7 +315,7 @@ def _create_streaming_chat_message_content(
312315
)
313316
)
314317
elif isinstance(stream_event, RawMessageDeltaEvent):
315-
finish_reason = ANTHROPIC_TO_SEMANTIC_KERNEL_FINISH_REASON_MAP[str(stream_event.delta.stop_reason)]
318+
finish_reason = ANTHROPIC_TO_SEMANTIC_KERNEL_FINISH_REASON_MAP.get(str(stream_event.delta.stop_reason))
316319
usage = _get_completion_usage(stream_event.usage)
317320
start_usage = metadata.get("usage") if metadata else None
318321
if getattr(stream_event.usage, "input_tokens", None) is None and isinstance(start_usage, CompletionUsage):

‎python/tests/unit/connectors/ai/anthropic/services/test_anthropic_chat_completion.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from semantic_kernel.contents.chat_message_content import ChatMessageContent, FunctionCallContent, TextContent
2323
from semantic_kernel.contents.streaming_chat_message_content import StreamingChatMessageContent
2424
from semantic_kernel.contents.utils.author_role import AuthorRole
25+
from semantic_kernel.contents.utils.finish_reason import FinishReason
2526
from semantic_kernel.exceptions import (
2627
ServiceInitializationError,
2728
ServiceInvalidExecutionSettingsError,
@@ -666,3 +667,40 @@ async def async_generator():
666667
gen_ai_attributes.INPUT_TOKENS: 130,
667668
gen_ai_attributes.OUTPUT_TOKENS: 7,
668669
}
670+
671+
672+
@pytest.mark.parametrize(
673+
("stop_reason", "finish_reason"),
674+
[
675+
("end_turn", FinishReason.STOP),
676+
("stop_sequence", FinishReason.STOP),
677+
("max_tokens", FinishReason.LENGTH),
678+
("model_context_window_exceeded", FinishReason.LENGTH),
679+
("tool_use", FinishReason.TOOL_CALLS),
680+
("refusal", FinishReason.CONTENT_FILTER),
681+
("pause_turn", None),
682+
],
683+
)
684+
def test_stop_reason_maps_to_finish_reason(anthropic_unit_test_env, stop_reason, finish_reason) -> None:
685+
chat_completion = AnthropicChatCompletion()
686+
message = Message(
687+
id="msg_1",
688+
type="message",
689+
role="assistant",
690+
model="claude-sonnet-4-5",
691+
content=[TextBlock(type="text", text="Hello")],
692+
stop_reason=stop_reason,
693+
stop_sequence=None,
694+
usage=Usage(input_tokens=1, output_tokens=1),
695+
)
696+
delta_event = RawMessageDeltaEvent(
697+
type="message_delta",
698+
delta=Delta(stop_reason=stop_reason, stop_sequence=None),
699+
usage=MessageDeltaUsage(output_tokens=1),
700+
)
701+
702+
content = chat_completion._create_chat_message_content(message, {})
703+
streaming_content = chat_completion._create_streaming_chat_message_content(delta_event)
704+
705+
assert content.finish_reason == finish_reason
706+
assert streaming_content.finish_reason == finish_reason

0 commit comments

Comments
 (0)