Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
从 Claude 4 模型开始,Claude API 的流式响应在流式分类器介入处理潜在的政策违规时会返回 stop_reason: "refusal"。这项新的安全功能有助于在实时流式传输期间保持内容合规性。
要了解有关 Claude Sonnet 4.5 API 安全过滤器触发的拒绝的更多信息,请参阅了解 Sonnet 4.5 的 API 安全过滤器。
当流式分类器检测到违反 Anthropic 政策的内容时,API 会返回此响应:
{
"role": "assistant",
"content": [
{
"type": "text",
"text": "Hello.."
}
],
"stop_reason": "refusal"
}不包含额外的拒绝消息。您必须处理响应并提供适当的面向用户的消息。
当您收到 stop_reason: refusal 时,您必须通过删除或更新被拒绝的轮次来重置对话上下文,然后再继续。尝试在不重置的情况下继续将导致持续拒绝。
即使响应被拒绝,响应中仍会提供使用指标用于计费目的。
您将被计费直到拒绝为止的输出令牌。
如果在使用 Claude Sonnet 4.5 或 Opus 4.1 时频繁遇到 refusal 停止原因,您可以尝试更新 API 调用以使用 Haiku 4.5 (claude-haiku-4-5-20251001),它具有不同的使用限制。了解更多关于理解 Sonnet 4.5 的 API 安全过滤器。
以下是如何在您的应用程序中检测和处理流式拒绝的方法:
API 目前以三种不同的方式处理拒绝:
| 拒绝类型 | 响应格式 | 发生时机 |
|---|---|---|
| 流式分类器拒绝 | stop_reason: refusal | 在流式传输期间当内容违反政策时 |
| API 输入和版权验证 | 400 错误代码 | 当输入未通过验证检查时 |
| 模型生成的拒绝 | 标准文本响应 | 当模型本身决定拒绝时 |
未来的 API 版本将扩展 stop_reason: refusal 模式以统一所有类型的拒绝处理。
stop_reason: refusal 检查Was this page helpful?
client = anthropic.Anthropic()
messages = []
def reset_conversation():
"""拒绝后重置对话上下文"""
global messages
messages = []
print("Conversation reset due to refusal")
try:
with client.messages.stream(
max_tokens=1024,
messages=messages + [{"role": "user", "content": "Hello"}],
model="claude-sonnet-4-6",
) as stream:
for event in stream:
# 检查消息增量中的拒绝
if hasattr(event, "type") and event.type == "message_delta":
if event.delta.stop_reason == "refusal":
reset_conversation()
break
except Exception as e:
print(f"Error: {e}")