Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

fix(models): map Anthropic refusal stop_reason to content_filter (#4210)

Ehsand9e0217efd6f
diff --git a/camel/models/anthropic_model.py b/camel/models/anthropic_model.py
index 10ee47578..5f737c76a 100644
--- a/camel/models/anthropic_model.py
+++ b/camel/models/anthropic_model.py
@@ -705,6 +705,10 @@ class AnthropicModel(BaseModelBackend):
finish_reason = "stop"
elif stop_reason == "tool_use":
finish_reason = "tool_calls"
+ elif stop_reason == "refusal":
+ # Anthropic's safety refusal; the OpenAI vocabulary term for
+ # a generation the provider declined on safety grounds.
+ finish_reason = "content_filter"
else:
finish_reason = stop_reason
@@ -937,6 +941,11 @@ class AnthropicModel(BaseModelBackend):
finish_reason = "stop"
elif stop_reason == "tool_use":
finish_reason = "tool_calls"
+ elif stop_reason == "refusal":
+ # Anthropic's safety refusal; without this branch the
+ # chunk carries finish_reason=None and message_stop
+ # coerces it to "stop", hiding the refusal.
+ finish_reason = "content_filter"
# Extract usage info from message_delta
if hasattr(chunk, "usage") and chunk.usage:
usage = self._extract_usage(chunk.usage)
diff --git a/test/models/test_anthropic_model.py b/test/models/test_anthropic_model.py
index f2e37fd47..bf1d5222f 100644
--- a/test/models/test_anthropic_model.py
+++ b/test/models/test_anthropic_model.py
@@ -561,6 +561,8 @@ def test_convert_anthropic_response_stop_reasons():
"max_tokens": "length",
"stop_sequence": "stop",
"tool_use": "tool_calls",
+ # A safety refusal must map to the OpenAI vocabulary, not leak raw.
+ "refusal": "content_filter",
}
for anthropic_reason, openai_reason in stop_reason_mapping.items():
@@ -995,6 +997,31 @@ def test_convert_stream_chunk_message_delta_stop():
assert result.choices[0].finish_reason == "stop"
+def test_convert_stream_chunk_message_delta_refusal():
+ """A streaming safety refusal must surface as content_filter.
+
+ Without the mapping the message_delta chunk carries finish_reason=None
+ and message_stop coerces it to "stop", so the refusal reads as a normal
+ completion.
+ """
+ model = AnthropicModel(
+ ModelType.CLAUDE_HAIKU_4_5,
+ api_key="dummy_api_key",
+ )
+
+ mock_chunk = MagicMock()
+ mock_chunk.type = "message_delta"
+ mock_chunk.delta = MagicMock()
+ mock_chunk.delta.stop_reason = "refusal"
+
+ tool_call_index = {}
+ result = model._convert_anthropic_stream_to_openai_chunk(
+ mock_chunk, "claude-haiku-4-5", tool_call_index
+ )
+
+ assert result.choices[0].finish_reason == "content_filter"
+
+
def test_convert_stream_chunk_message_stop():
"""Test conversion of message_stop chunk."""
model = AnthropicModel(