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
@@ -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