feat(runtime): surface and recover from model refusals

Claude Fable 5 safety classifiers decline requests with HTTP 200 +
stop_reason=refusal and empty content. The Anthropic stream parser
never read stop_reason, so a refused turn looked like a successful
empty response — the UI showed nothing and the agent appeared hung.

- llm: ChatEvent carries StopReason/StopCategory on EventDone;
  StopReasonRefusal constant
- anthropic: parse stop_reason + stop_details.category from
  message_delta (streaming) and the message (non-streaming); WARN log
  on refusal
- runtime Run + RunTurn: on refusal, retry the turn once on
  FallbackModel (refusals are model-specific; Opus-tier has no
  bio/cyber classifiers), discarding any partial output; without a
  fallback (or if the fallback also refuses) synthesize a visible
  'model declined this request' message with the policy category
  instead of silent emptiness
This commit is contained in:
sausheong committed 2026-06-10 21:13:48 +08:00
1 parent 3064a0da14
commit d5e8abf492
6 files changed
+320 -18

No files matched your search

+12 -1
View File
@@ -245,7 +245,14 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
currentBlockType = ""
case "message_delta":
if event.Usage.OutputTokens > 0 || cacheCreationTokens > 0 || cacheReadTokens > 0 {
stopReason := string(event.Delta.StopReason)
stopCategory := string(event.Delta.StopDetails.Category)
if stopReason == llm.StopReasonRefusal {
slog.Warn("anthropic refusal stop reason",
"category", stopCategory,
"output_tokens", event.Usage.OutputTokens)
}
if event.Usage.OutputTokens > 0 || cacheCreationTokens > 0 || cacheReadTokens > 0 || stopReason != "" {
slog.Info("anthropic stream usage",
"input_tokens", inputTokens,
"output_tokens", event.Usage.OutputTokens,
@@ -260,6 +267,8 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
CacheCreationInputTokens: int(cacheCreationTokens),
CacheReadInputTokens: int(cacheReadTokens),
},
StopReason: stopReason,
StopCategory: stopCategory,
}
}
@@ -344,6 +353,8 @@ func (p *AnthropicProvider) ChatNonStreaming(ctx context.Context, req llm.ChatRe
CacheCreationInputTokens: int(msg.Usage.CacheCreationInputTokens),
CacheReadInputTokens: int(msg.Usage.CacheReadInputTokens),
},
StopReason: string(msg.StopReason),
StopCategory: string(msg.StopDetails.Category),
}
}()
return events, nil