fix(translator): map Claude "refusal" stop_reason to content_filter and surface its explanation

Anthropic's API-level refusal (streaming classifier / ToS) ends the stream
with stop_reason "refusal", stop_details carrying the reason, zero output
tokens and no content blocks. Map refusal to content_filter in both
directions, surface stop_details.explanation as message text, and add
CLAUDE_STOP.REFUSAL to schema.
This commit is contained in:
Welington
2026-09-22 15:25:09 +07:00
parent 1a02713150
commit 0f488c7027
5 changed files with 97 additions and 0 deletions

View File

@@ -11,6 +11,10 @@ export function toOpenAIFinish(reason, format) {
case CLAUDE_STOP.MAX_TOKENS: return OPENAI_FINISH.LENGTH;
case CLAUDE_STOP.TOOL_USE: return OPENAI_FINISH.TOOL_CALLS;
case CLAUDE_STOP.STOP_SEQUENCE: return OPENAI_FINISH.STOP;
// A refusal is a blocked turn, not a clean stop: with the default mapping an
// OpenAI client saw finish_reason "stop" and an empty message (9Router logged
// "succeeded", OUT 0) and could not tell it from a real answer.
case CLAUDE_STOP.REFUSAL: return OPENAI_FINISH.CONTENT_FILTER;
default: return OPENAI_FINISH.STOP;
}
case "commandcode":
@@ -55,6 +59,7 @@ export function fromOpenAIFinish(reason, format) {
case OPENAI_FINISH.STOP: return CLAUDE_STOP.END_TURN;
case OPENAI_FINISH.LENGTH: return CLAUDE_STOP.MAX_TOKENS;
case OPENAI_FINISH.TOOL_CALLS: return CLAUDE_STOP.TOOL_USE;
case OPENAI_FINISH.CONTENT_FILTER: return CLAUDE_STOP.REFUSAL;
default: return CLAUDE_STOP.END_TURN;
}
default:

View File

@@ -149,6 +149,13 @@ export function claudeToOpenAIResponse(chunk, state) {
if (chunk.delta?.stop_reason) {
state.finishReason = convertStopReason(chunk.delta.stop_reason);
// A refusal produces no content blocks at all. Surface Anthropic's own
// explanation as the message text so the client shows *why* the turn is
// empty instead of a blank reply.
const refusalNote = chunk.delta.stop_reason === "refusal" && chunk.delta.stop_details?.explanation;
if (refusalNote) {
results.push(createChunk(state, { content: refusalNote }));
}
const finalChunk = createChunk(state, {}, state.finishReason);
if (state.usage) {

View File

@@ -14,6 +14,9 @@ export const CLAUDE_STOP = {
MAX_TOKENS: "max_tokens",
TOOL_USE: "tool_use",
STOP_SEQUENCE: "stop_sequence",
// Anthropic's API-level refusal (streaming classifier / ToS). Arrives in
// message_delta with zero output tokens; stop_details carries the reason.
REFUSAL: "refusal",
};
// Gemini finishReason values.