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:
1 parent
3064a0da14
commit
d5e8abf492
6 files changed
+320
-18
No files matched your search
@@ -135,8 +135,23 @@ type ChatEvent struct {
|
||||
ToolCall *ToolCall
|
||||
Usage *Usage
|
||||
Error error
|
||||
// StopReason carries the provider's terminal stop reason on EventDone
|
||||
// ("end_turn", "tool_use", "max_tokens", "refusal", ...). Empty when
|
||||
// the provider doesn't report one. StopReasonRefusal is the value the
|
||||
// runtime branches on: Claude Fable 5 safety classifiers decline a
|
||||
// request with HTTP 200 + stop_reason=refusal and empty content —
|
||||
// without surfacing it the turn looks like a silent empty success.
|
||||
StopReason string
|
||||
// StopCategory is the refusal policy category from stop_details
|
||||
// ("cyber", "bio", "reasoning_extraction"); informational only and
|
||||
// may be empty even on a refusal.
|
||||
StopCategory string
|
||||
}
|
||||
|
||||
// StopReasonRefusal is the StopReason value for safety-classifier and
|
||||
// model-initiated refusals (Claude Fable 5+).
|
||||
const StopReasonRefusal = "refusal"
|
||||
|
||||
// ModelInfo describes an available model.
|
||||
type ModelInfo struct {
|
||||
ID string
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -627,3 +627,84 @@ func TestLegacyThinkingModels_KeepBudgetTokens(t *testing.T) {
|
||||
"pre-4.7 models keep the enabled+budget_tokens config")
|
||||
assert.NotContains(t, got, `"output_config"`)
|
||||
}
|
||||
|
||||
// TestAnthropicStream_RefusalStopReasonSurfaced reproduces the Claude
|
||||
// Fable 5 classifier refusal: HTTP 200, a message_delta carrying
|
||||
// stop_reason=refusal + stop_details.category, and NO content blocks.
|
||||
// The parser previously dropped stop_reason entirely, so the runtime
|
||||
// saw an empty-but-successful turn and the user saw a silent nothing.
|
||||
func TestAnthropicStream_RefusalStopReasonSurfaced(t *testing.T) {
|
||||
const sseBody = `event: message_start
|
||||
data: {"type":"message_start","message":{"id":"msg_r","type":"message","role":"assistant","content":[],"model":"claude-fable-5","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":29,"output_tokens":0}}}
|
||||
|
||||
event: message_delta
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"refusal","stop_sequence":null,"stop_details":{"type":"refusal","category":"bio","explanation":null}},"usage":{"output_tokens":4}}
|
||||
|
||||
event: message_stop
|
||||
data: {"type":"message_stop"}
|
||||
|
||||
`
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(sseBody))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
p := NewAnthropicProvider("test-key", srv.URL)
|
||||
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "claude-fable-5"})
|
||||
require.NoError(t, err)
|
||||
|
||||
var done *llm.ChatEvent
|
||||
for ev := range stream {
|
||||
if ev.Type == llm.EventDone {
|
||||
ev := ev
|
||||
done = &ev
|
||||
}
|
||||
}
|
||||
require.NotNil(t, done, "stream must emit EventDone")
|
||||
assert.Equal(t, "refusal", done.StopReason)
|
||||
assert.Equal(t, "bio", done.StopCategory)
|
||||
}
|
||||
|
||||
// Normal end_turn streams must carry the stop reason too (and no category).
|
||||
func TestAnthropicStream_EndTurnStopReason(t *testing.T) {
|
||||
const sseBody = `event: message_start
|
||||
data: {"type":"message_start","message":{"id":"msg_n","type":"message","role":"assistant","content":[],"model":"claude-fable-5","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":0}}}
|
||||
|
||||
event: content_block_start
|
||||
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
|
||||
|
||||
event: content_block_delta
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}
|
||||
|
||||
event: content_block_stop
|
||||
data: {"type":"content_block_stop","index":0}
|
||||
|
||||
event: message_delta
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":2}}
|
||||
|
||||
event: message_stop
|
||||
data: {"type":"message_stop"}
|
||||
|
||||
`
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(sseBody))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
p := NewAnthropicProvider("test-key", srv.URL)
|
||||
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "claude-fable-5"})
|
||||
require.NoError(t, err)
|
||||
|
||||
var done *llm.ChatEvent
|
||||
for ev := range stream {
|
||||
if ev.Type == llm.EventDone {
|
||||
ev := ev
|
||||
done = &ev
|
||||
}
|
||||
}
|
||||
require.NotNil(t, done)
|
||||
assert.Equal(t, "end_turn", done.StopReason)
|
||||
assert.Empty(t, done.StopCategory)
|
||||
}
|
||||
@@ -266,3 +266,110 @@ func TestBuildRuntimeRejectsCrossProviderFallback(t *testing.T) {
|
||||
func decodeMessage(e session.SessionEntry, dst *session.MessageData) error {
|
||||
return json.Unmarshal(e.Data, dst)
|
||||
}
|
||||
|
||||
// refusalThenSuccessProvider returns a classifier-refusal stream (HTTP
|
||||
// 200, EventDone with StopReason=refusal, no content) on the first call
|
||||
// and a normal text stream on the second. Mirrors Claude Fable 5 safety
|
||||
// classifier behavior: refusals are NOT transport errors, so the
|
||||
// existing IsRetryableModelError path never sees them.
|
||||
type refusalThenSuccessProvider struct {
|
||||
llmtest.Base
|
||||
calls int
|
||||
modelsSeen []string
|
||||
finalText string
|
||||
}
|
||||
|
||||
func (p *refusalThenSuccessProvider) ChatStream(_ context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.calls++
|
||||
p.modelsSeen = append(p.modelsSeen, req.Model)
|
||||
ch := make(chan llm.ChatEvent, 4)
|
||||
if p.calls == 1 {
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone, StopReason: llm.StopReasonRefusal, StopCategory: "bio"}
|
||||
} else {
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: p.finalText}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone, StopReason: "end_turn"}
|
||||
}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// TestRuntimeRefusalRetriesOnFallbackModel: a refusal turn with a
|
||||
// configured fallback must transparently re-run the turn on the
|
||||
// fallback model instead of surfacing an empty response.
|
||||
func TestRuntimeRefusalRetriesOnFallbackModel(t *testing.T) {
|
||||
prov := &refusalThenSuccessProvider{finalText: "fallback answered"}
|
||||
rt := &Runtime{
|
||||
LLM: prov,
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "claude-fable-5",
|
||||
FallbackModel: "claude-opus-4-8",
|
||||
Provider: "anthropic",
|
||||
MaxTurns: 3,
|
||||
Workspace: t.TempDir(),
|
||||
}
|
||||
out, err := rt.RunSync(context.Background(), "summarise the biology article", nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "fallback answered", out)
|
||||
require.Equal(t, 2, prov.calls, "refusal + fallback retry = 2 calls")
|
||||
assert.Equal(t, "claude-fable-5", prov.modelsSeen[0])
|
||||
assert.Equal(t, "claude-opus-4-8", prov.modelsSeen[1])
|
||||
}
|
||||
|
||||
// alwaysRefusalProvider refuses every call — covers the no-fallback and
|
||||
// fallback-also-refused paths.
|
||||
type alwaysRefusalProvider struct {
|
||||
llmtest.Base
|
||||
calls int
|
||||
}
|
||||
|
||||
func (p *alwaysRefusalProvider) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.calls++
|
||||
ch := make(chan llm.ChatEvent, 2)
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone, StopReason: llm.StopReasonRefusal, StopCategory: "cyber"}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// TestRuntimeRefusalWithoutFallbackSurfacesVisibleText: with no fallback
|
||||
// the user must see an explanation, not an empty response.
|
||||
func TestRuntimeRefusalWithoutFallbackSurfacesVisibleText(t *testing.T) {
|
||||
prov := &alwaysRefusalProvider{}
|
||||
rt := &Runtime{
|
||||
LLM: prov,
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "claude-fable-5",
|
||||
Provider: "anthropic",
|
||||
MaxTurns: 3,
|
||||
Workspace: t.TempDir(),
|
||||
}
|
||||
out, err := rt.RunSync(context.Background(), "do something", nil)
|
||||
require.NoError(t, err, "a refusal is a model decision, not a transport error")
|
||||
assert.Contains(t, out, "declined", "refusal must produce visible explanation text")
|
||||
assert.Contains(t, out, "cyber", "category should be included when present")
|
||||
assert.Equal(t, 1, prov.calls, "no fallback configured → no retry")
|
||||
}
|
||||
|
||||
// TestRuntimeRefusalFallbackAlsoRefusesSurfacesText: when the fallback
|
||||
// refuses too, stop (no infinite retry) and surface the explanation.
|
||||
func TestRuntimeRefusalFallbackAlsoRefusesSurfacesText(t *testing.T) {
|
||||
prov := &alwaysRefusalProvider{}
|
||||
rt := &Runtime{
|
||||
LLM: prov,
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "claude-fable-5",
|
||||
FallbackModel: "claude-opus-4-8",
|
||||
Provider: "anthropic",
|
||||
MaxTurns: 3,
|
||||
Workspace: t.TempDir(),
|
||||
}
|
||||
out, err := rt.RunSync(context.Background(), "do something", nil)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, out, "declined")
|
||||
assert.Equal(t, 2, prov.calls, "primary + one fallback attempt, then stop")
|
||||
}
|
||||
@@ -485,6 +485,9 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
|
||||
streamSource := stream
|
||||
retriedNonStreaming := false
|
||||
retriedRefusal := false
|
||||
var refused bool
|
||||
var refusalCategory string
|
||||
streamLoop:
|
||||
for {
|
||||
for event := range streamSource {
|
||||
@@ -527,6 +530,8 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
}()
|
||||
|
||||
case llm.EventDone:
|
||||
refused = event.StopReason == llm.StopReasonRefusal
|
||||
refusalCategory = event.StopCategory
|
||||
if event.Usage != nil {
|
||||
lastUsage = event.Usage
|
||||
}
|
||||
@@ -567,6 +572,53 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Classifier/model refusal (Claude Fable 5+): HTTP 200,
|
||||
// stop_reason=refusal, usually no content. Without handling,
|
||||
// the turn ends as a silent empty success. Retry once on the
|
||||
// fallback model (refusals are model-specific — Opus-tier
|
||||
// has no bio/cyber classifiers); otherwise synthesize a
|
||||
// visible explanation. Mid-stream refusals discard partial
|
||||
// output per the API contract.
|
||||
if refused {
|
||||
if !retriedRefusal && r.FallbackModel != "" && r.FallbackModel != req.Model {
|
||||
slog.Warn("model refused; retrying on fallback model",
|
||||
"agent", r.AgentID,
|
||||
"primary", req.Model,
|
||||
"fallback", r.FallbackModel,
|
||||
"category", refusalCategory)
|
||||
tr.Mark("llm.refusal_fallback", "turn", turn,
|
||||
"primary", req.Model, "fallback", r.FallbackModel,
|
||||
"category", refusalCategory)
|
||||
textContent.Reset()
|
||||
toolCalls = nil
|
||||
drainKickoffs(kickoffs)
|
||||
kickoffs = map[string]chan kickoffResult{}
|
||||
gotFirstToken = false
|
||||
kickoffStopped = false
|
||||
refused = false
|
||||
retriedRefusal = true
|
||||
req.Model = r.FallbackModel
|
||||
retryStream, retryErr := r.LLM.ChatStream(ctx, req)
|
||||
if retryErr != nil {
|
||||
stopReason = "error"
|
||||
r.emit(AgentEvent{Type: EventError, Error: retryErr})
|
||||
return
|
||||
}
|
||||
streamSource = retryStream
|
||||
continue streamLoop
|
||||
}
|
||||
textContent.Reset()
|
||||
toolCalls = nil
|
||||
drainKickoffs(kickoffs)
|
||||
note := "The model declined this request (safety classifier"
|
||||
if refusalCategory != "" {
|
||||
note += ", category: " + refusalCategory
|
||||
}
|
||||
note += "). Try rephrasing, or switch this agent to a model without these classifiers."
|
||||
textContent.WriteString(note)
|
||||
r.emit(AgentEvent{Type: EventTextDelta, Text: note})
|
||||
}
|
||||
break streamLoop
|
||||
}
|
||||
tr.Mark("llm.stream_end", "turn", turn,
|
||||
|
||||
+53
-17
@@ -113,25 +113,61 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag
|
||||
var textContent strings.Builder
|
||||
var toolCalls []llm.ToolCall
|
||||
var lastUsage *llm.Usage
|
||||
for event := range stream {
|
||||
switch event.Type {
|
||||
case llm.EventTextDelta:
|
||||
textContent.WriteString(event.Text)
|
||||
emit(AgentEvent{Type: EventTextDelta, Text: event.Text})
|
||||
case llm.EventToolCallStart:
|
||||
emit(AgentEvent{Type: EventToolCallStart, ToolCall: event.ToolCall})
|
||||
case llm.EventToolCallDone:
|
||||
if event.ToolCall != nil {
|
||||
toolCalls = append(toolCalls, *event.ToolCall)
|
||||
retriedRefusal := false
|
||||
streamLoop:
|
||||
for {
|
||||
var refused bool
|
||||
var refusalCategory string
|
||||
for event := range stream {
|
||||
switch event.Type {
|
||||
case llm.EventTextDelta:
|
||||
textContent.WriteString(event.Text)
|
||||
emit(AgentEvent{Type: EventTextDelta, Text: event.Text})
|
||||
case llm.EventToolCallStart:
|
||||
emit(AgentEvent{Type: EventToolCallStart, ToolCall: event.ToolCall})
|
||||
case llm.EventToolCallDone:
|
||||
if event.ToolCall != nil {
|
||||
toolCalls = append(toolCalls, *event.ToolCall)
|
||||
}
|
||||
case llm.EventDone:
|
||||
refused = event.StopReason == llm.StopReasonRefusal
|
||||
refusalCategory = event.StopCategory
|
||||
if event.Usage != nil {
|
||||
lastUsage = event.Usage
|
||||
}
|
||||
case llm.EventError:
|
||||
emit(AgentEvent{Type: EventError, Error: event.Error})
|
||||
return r.turnSlice(startLen, true, "error", lastUsage, event.Error), nil
|
||||
}
|
||||
case llm.EventDone:
|
||||
if event.Usage != nil {
|
||||
lastUsage = event.Usage
|
||||
}
|
||||
case llm.EventError:
|
||||
emit(AgentEvent{Type: EventError, Error: event.Error})
|
||||
return r.turnSlice(startLen, true, "error", lastUsage, event.Error), nil
|
||||
}
|
||||
|
||||
// Same refusal contract as Run: retry once on the fallback model,
|
||||
// else surface a visible explanation instead of empty silence.
|
||||
if refused {
|
||||
if !retriedRefusal && r.FallbackModel != "" && r.FallbackModel != req.Model {
|
||||
retriedRefusal = true
|
||||
textContent.Reset()
|
||||
toolCalls = nil
|
||||
req.Model = r.FallbackModel
|
||||
retryStream, retryErr := r.LLM.ChatStream(ctx, req)
|
||||
if retryErr != nil {
|
||||
emit(AgentEvent{Type: EventError, Error: retryErr})
|
||||
return r.turnSlice(startLen, true, "error", lastUsage, retryErr), nil
|
||||
}
|
||||
stream = retryStream
|
||||
continue streamLoop
|
||||
}
|
||||
textContent.Reset()
|
||||
toolCalls = nil
|
||||
note := "The model declined this request (safety classifier"
|
||||
if refusalCategory != "" {
|
||||
note += ", category: " + refusalCategory
|
||||
}
|
||||
note += "). Try rephrasing, or switch this agent to a model without these classifiers."
|
||||
textContent.WriteString(note)
|
||||
emit(AgentEvent{Type: EventTextDelta, Text: note})
|
||||
}
|
||||
break streamLoop
|
||||
}
|
||||
|
||||
if textContent.Len() > 0 {
|
||||
|
||||
Reference in new issue
Block a user