gateway: a group member's reply that ends with nothing in it goes to the next member (#6712)
shawn8888's ai-studio (magpie-gemini-web 0.14.0, aistudio2api 0.3.8) answered a streamed request with 200, a role chunk with "" content, then finish_reason "stop" and 0 output tokens when Google's every regeneration came back malformed_response. streamEvent read that Chat finish chunk as content, so the hold let the stream through as an answer and group/auto-gemini-4-hydrogen (routing order) never asked agy-cli or google; the agent got no reply. A reply's end in an event that says nothing itself is now eventEmptyEnd: a Chat finish_reason other than length, error or a filter; Messages' end_turn, stop_sequence or tool_use; a completed Responses reply; Gemini's STOP. The hold fails the try with a 502 "empty reply: it ended with nothing in it" only when nothing was said before it, reasoning included, and only for a group member with another member after it and errors not passed through (holdWriter.emptyFails). The group's existing empty-reply branch then asks the next member and rests nobody. A reply held whole is judged in the one parse settle already made (refusedReply is now readWhole, which also says empty), so a passing reply is read no more than before. The last member's empty reply, or a model asked alone, goes to the agent as it came, so an empty answer can't loop. Changed on purpose: a Claude member's empty end_turn inside a group with members left now asks the next member; TestStreamEventRefusals' three rows for an empty end now say eventEmptyEnd. Not handled: a stream the hold already let through on its timer (a Gemini client after 15s) before the empty end came. The plugin side is BUKOWSKIREAL/magpie-gemini-web#61 (a 502 or error event, not 200 + stop). Run, on mica: - new tests red on 369ec0418's fallback.go/gateway.go (checked out over the new ones, the unit tables left out): TestEmptyStopFailsOverToTheNextMember (chat, messages, responses, gemini), TestEmptyWholeReplyFailsOverToTheNextMember, TestEmptyStopEndsAtTheLastMember, TestEmptyEndFromEachUpstreamFailsOver (Messages and Responses upstreams) all FAIL; TestReasonedThenStoppedStaysTheAnswer passes on both (a guard against reaching too far). All green on the new code. - go test ./internal/gateway -count=1 (whole package): one red, TestStreamEventRefusals' three empty-end rows, updated here; then -run 'StreamEvent|Refusal|Empty|FinishReason|Overload|Overflow|ReadWhole|Reasoned|Responses' ok. - go vet ./internal/gateway, GOOS=linux (nogui) and GOOS=windows vet ok; gofmt -l clean. - The full go test ./... -timeout 45m runs after the push (ship-at-once); its result goes on #6712.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -0,0 +1,235 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// emptyStop is #6712's stream, as aistudio2api (magpie-gemini-web) sent
|
||||
// it when Google's every regeneration came back malformed: keepalive
|
||||
// comments while it waited, its role chunk with an empty content, then
|
||||
// finish_reason "stop" and usage that counted the prompt and no output.
|
||||
var emptyStop = sse(`: keepalive`,
|
||||
`data: {"id":"chatcmpl_1794688838638417321_17","object":"chat.completion.chunk","model":"gemini-4-hydrogen","choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}`,
|
||||
`: keepalive`,
|
||||
`data: {"id":"chatcmpl_1794688838638417321_17","object":"chat.completion.chunk","model":"gemini-4-hydrogen","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`,
|
||||
`data: {"id":"chatcmpl_1794688838638417321_17","object":"chat.completion.chunk","model":"gemini-4-hydrogen","choices":[],"usage":{"prompt_tokens":2048,"completion_tokens":0,"total_tokens":2048,"prompt_tokens_details":{"cached_tokens":61004}}}`,
|
||||
`data: [DONE]`)
|
||||
|
||||
var chatFromB = sse(`data: {"id":"c2","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant"}}]}`,
|
||||
`data: {"id":"c2","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"from b"}}]}`,
|
||||
`data: {"id":"c2","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":2,"total_tokens":7}}`,
|
||||
`data: [DONE]`)
|
||||
|
||||
// threeGroup saves group/g of a, b and c, each a scripted Chat provider
|
||||
// answering with its own replies.
|
||||
func threeGroup(t *testing.T, a, b, c *scripted) {
|
||||
t.Helper()
|
||||
scriptedOn(t, "a", provider.Chat, a)
|
||||
scriptedOn(t, "b", provider.Chat, b)
|
||||
scriptedOn(t, "c", provider.Chat, c)
|
||||
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m", "c/m"}, Routing: provider.Ordered}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// A group member's 200 stream that ends with finish_reason "stop" having
|
||||
// said nothing at all — no text, no reasoning, no call — is no answer
|
||||
// (#6712): the held stream fails before anything of it reaches the agent,
|
||||
// the group's next member answers, and nobody rests. So in each protocol
|
||||
// an agent speaks, the reply relayed as it came (Chat) or translated.
|
||||
func TestEmptyStopFailsOverToTheNextMember(t *testing.T) {
|
||||
for _, x := range []struct {
|
||||
name, path, body string
|
||||
}{
|
||||
{"chat", "/v1/chat/completions", `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}`},
|
||||
{"messages", "/v1/messages", `{"model":"group/g","max_tokens":100,"stream":true,"messages":[{"role":"user","content":"hi"}]}`},
|
||||
{"responses", "/v1/responses", `{"model":"group/g","stream":true,"input":"hi"}`},
|
||||
{"gemini", "/v1beta/models/group/g:streamGenerateContent?alt=sse", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`},
|
||||
} {
|
||||
t.Run(x.name, func(t *testing.T) {
|
||||
fresh(t)
|
||||
a := &scripted{replies: []reply{{200, "text/event-stream", emptyStop}}}
|
||||
b := &scripted{replies: []reply{{200, "text/event-stream", chatFromB}}}
|
||||
c := &scripted{replies: []reply{{200, "text/event-stream", chatFromB}}}
|
||||
threeGroup(t, a, b, c)
|
||||
s := New()
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", x.path, strings.NewReader(x.body)))
|
||||
code, body := rec.Code, rec.Body.String()
|
||||
if code != 200 || !strings.Contains(body, "from b") || strings.Contains(body, "chatcmpl_1794688838638417321_17") {
|
||||
t.Fatalf("%d %s %+v", code, body, s.trace.routes[len(s.trace.routes)-1])
|
||||
}
|
||||
if b.n != 1 || c.n != 0 {
|
||||
t.Fatalf("a asked %d, b asked %d, c asked %d", a.n, b.n, c.n)
|
||||
}
|
||||
r := s.trace.routes[len(s.trace.routes)-1]
|
||||
if len(r.Tries) != 2 || r.Tries[0].Status != 502 || r.Tries[0].Fail != failOther || r.Tries[0].Rest != nil ||
|
||||
!strings.Contains(r.Tries[0].Error, emptyReply) {
|
||||
t.Fatalf("tries: %+v", r.Tries)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The same reply given whole, to an agent that didn't ask for a stream,
|
||||
// goes to the next member too.
|
||||
func TestEmptyWholeReplyFailsOverToTheNextMember(t *testing.T) {
|
||||
fresh(t)
|
||||
empty := `{"id":"x","object":"chat.completion","choices":[{"index":0,"message":{"role":"assistant","content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":2048,"completion_tokens":0,"total_tokens":2048}}`
|
||||
a := &scripted{replies: []reply{{200, "", empty}}}
|
||||
b := &scripted{replies: []reply{{200, "", chatOK}}}
|
||||
c := &scripted{replies: []reply{{200, "", chatOK}}}
|
||||
threeGroup(t, a, b, c)
|
||||
s := New()
|
||||
code, body := postAs(t, s, "", `{"model":"group/g","messages":[{"role":"user","content":"hi"}]}`)
|
||||
if code != 200 || !strings.Contains(body, "hello") || b.n != 1 || c.n != 0 {
|
||||
t.Fatalf("%d %s (a %d, b %d, c %d)", code, body, a.n, b.n, c.n)
|
||||
}
|
||||
r := s.trace.routes[len(s.trace.routes)-1]
|
||||
if len(r.Tries) != 2 || r.Tries[0].Fail != failOther || r.Tries[0].Rest != nil || !strings.Contains(r.Tries[0].Error, emptyReply) {
|
||||
t.Fatalf("tries: %+v", r.Tries)
|
||||
}
|
||||
}
|
||||
|
||||
// A reply meant to be empty doesn't go round for ever: every member is
|
||||
// asked once, and the last one's empty reply is the agent's, a 200 as it
|
||||
// came. A model asked alone, outside a group, answers empty as before.
|
||||
func TestEmptyStopEndsAtTheLastMember(t *testing.T) {
|
||||
fresh(t)
|
||||
a := &scripted{replies: []reply{{200, "text/event-stream", emptyStop}}}
|
||||
b := &scripted{replies: []reply{{200, "text/event-stream", emptyStop}}}
|
||||
c := &scripted{replies: []reply{{200, "text/event-stream", emptyStop}}}
|
||||
threeGroup(t, a, b, c)
|
||||
s := New()
|
||||
code, body := postAs(t, s, "", `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
if code != 200 || !strings.Contains(body, `"finish_reason":"stop"`) || strings.Contains(body, emptyReply) {
|
||||
t.Fatalf("%d %s", code, body)
|
||||
}
|
||||
if a.n != 1 || b.n != 1 || c.n != 1 {
|
||||
t.Fatalf("a asked %d, b asked %d, c asked %d", a.n, b.n, c.n)
|
||||
}
|
||||
|
||||
fresh(t)
|
||||
a = &scripted{replies: []reply{{200, "text/event-stream", emptyStop}}}
|
||||
scriptedOn(t, "a", provider.Chat, a)
|
||||
code, body = postAs(t, New(), "", `{"model":"a/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
if code != 200 || !strings.Contains(body, `"finish_reason":"stop"`) || a.n != 1 {
|
||||
t.Fatalf("alone: %d %s (asked %d)", code, body, a.n)
|
||||
}
|
||||
}
|
||||
|
||||
// A reply that only reasoned and then stopped said something: the agent
|
||||
// has its reasoning, and the next member isn't asked.
|
||||
func TestReasonedThenStoppedStaysTheAnswer(t *testing.T) {
|
||||
fresh(t)
|
||||
reasoned := sse(`data: {"id":"r","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}`,
|
||||
`data: {"id":"r","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"reasoning_content":"thinking it over"}}]}`,
|
||||
`data: {"id":"r","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`,
|
||||
`data: [DONE]`)
|
||||
a := &scripted{replies: []reply{{200, "text/event-stream", reasoned}}}
|
||||
b := &scripted{replies: []reply{{200, "text/event-stream", chatFromB}}}
|
||||
c := &scripted{replies: []reply{{200, "text/event-stream", chatFromB}}}
|
||||
threeGroup(t, a, b, c)
|
||||
code, body := postAs(t, New(), "", `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
if code != 200 || !strings.Contains(body, "thinking it over") || b.n != 0 {
|
||||
t.Fatalf("%d %s (b asked %d)", code, body, b.n)
|
||||
}
|
||||
}
|
||||
|
||||
// streamEvent tells a reply's end with nothing in its event apart, in
|
||||
// each protocol, from one that ends a reply with something in it or for
|
||||
// a reason of its own.
|
||||
func TestStreamEventEmptyEnd(t *testing.T) {
|
||||
for _, x := range []struct {
|
||||
ev string
|
||||
kind int
|
||||
}{
|
||||
{`data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, eventEmptyEnd},
|
||||
{`data: {"choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":"stop"}]}`, eventEmptyEnd},
|
||||
{`data: {"choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":"stop"}]}`, eventContent},
|
||||
{`data: {"choices":[{"index":0,"delta":{"reasoning_content":"hm"},"finish_reason":"stop"}]}`, eventContent},
|
||||
{`data: {"choices":[{"index":0,"delta":{},"finish_reason":"length"}]}`, eventContent},
|
||||
{`event: message_delta` + "\n" + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":0}}`, eventEmptyEnd},
|
||||
{`event: message_delta` + "\n" + `data: {"type":"message_delta","delta":{"stop_reason":"max_tokens"}}`, eventContent},
|
||||
{`event: response.completed` + "\n" + `data: {"type":"response.completed","response":{"status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":0}}}`, eventEmptyEnd},
|
||||
{`event: response.completed` + "\n" + `data: {"type":"response.completed","response":{"status":"incomplete","output":[]}}`, eventContent},
|
||||
{`data: {"candidates":[{"content":{"role":"model","parts":[{"text":""}]},"finishReason":"STOP"}]}`, eventEmptyEnd},
|
||||
{`data: {"candidates":[{"content":{"role":"model","parts":[{"text":"hi"}]},"finishReason":"STOP"}]}`, eventContent},
|
||||
{`data: {"candidates":[{"content":{"role":"model","parts":[]},"finishReason":"MAX_TOKENS"}]}`, eventContent},
|
||||
} {
|
||||
if k, _, _ := streamEvent([]byte(x.ev)); k != x.kind {
|
||||
t.Errorf("streamEvent(%s) = %d, want %d", x.ev, k, x.kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// readWhole tells a whole reply with nothing in it apart from one with
|
||||
// something, or one cut at its length, in each protocol.
|
||||
func TestReadWholeEmpty(t *testing.T) {
|
||||
for _, x := range []struct {
|
||||
body string
|
||||
empty bool
|
||||
}{
|
||||
{`{"choices":[{"message":{"role":"assistant","content":""},"finish_reason":"stop"}]}`, true},
|
||||
{`{"choices":[{"message":{"role":"assistant","content":null},"finish_reason":"stop"}]}`, true},
|
||||
{`{"choices":[{"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]}`, false},
|
||||
{`{"choices":[{"message":{"role":"assistant","content":null,"tool_calls":[{"id":"t"}]},"finish_reason":"tool_calls"}]}`, false},
|
||||
{`{"choices":[{"message":{"role":"assistant","content":"","reasoning_content":"hm"},"finish_reason":"stop"}]}`, false},
|
||||
{`{"choices":[{"message":{"role":"assistant","content":""},"finish_reason":"length"}]}`, false},
|
||||
{`{"type":"message","content":[],"stop_reason":"end_turn","usage":{"input_tokens":3,"output_tokens":0}}`, true},
|
||||
{`{"type":"message","content":[{"type":"text","text":"hi"}],"stop_reason":"end_turn"}`, false},
|
||||
{`{"type":"message","content":[],"stop_reason":"max_tokens"}`, false},
|
||||
{`{"status":"completed","output":[]}`, true},
|
||||
{`{"status":"completed","output":[{"type":"message","content":[{"type":"output_text","text":"hi"}]}]}`, false},
|
||||
{`{"candidates":[{"content":{"parts":[{"text":""}]},"finishReason":"STOP"}]}`, true},
|
||||
{`{"candidates":[{"content":{"parts":[{"functionCall":{"name":"f"}}]},"finishReason":"STOP"}]}`, false},
|
||||
{`{"error":{"message":"boom"}}`, false},
|
||||
} {
|
||||
if _, _, empty := readWhole([]byte(x.body)); empty != x.empty {
|
||||
t.Errorf("readWhole(%s) empty = %v, want %v", x.body, empty, x.empty)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A Messages or Responses upstream that ends its turn with nothing in it,
|
||||
// though it counted the prompt's tokens, is no answer either: the
|
||||
// group's next member gives the agent its reply.
|
||||
func TestEmptyEndFromEachUpstreamFailsOver(t *testing.T) {
|
||||
for _, x := range []struct {
|
||||
name string
|
||||
proto provider.Protocol
|
||||
body string
|
||||
}{
|
||||
{"messages", provider.Anthropic, sse(
|
||||
"event: message_start\ndata: "+`{"type":"message_start","message":{"id":"m","type":"message","role":"assistant","content":[],"usage":{"input_tokens":2048,"output_tokens":0}}}`,
|
||||
"event: ping\ndata: "+`{"type":"ping"}`,
|
||||
"event: message_delta\ndata: "+`{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":0}}`,
|
||||
"event: message_stop\ndata: "+`{"type":"message_stop"}`)},
|
||||
{"responses", provider.Responses, sse(
|
||||
"event: response.created\ndata: "+`{"type":"response.created","response":{"id":"r","status":"in_progress","output":[]}}`,
|
||||
"event: response.completed\ndata: "+`{"type":"response.completed","response":{"id":"r","status":"completed","output":[],"usage":{"input_tokens":2048,"output_tokens":0,"total_tokens":2048}}}`)},
|
||||
} {
|
||||
t.Run(x.name, func(t *testing.T) {
|
||||
fresh(t)
|
||||
a := &scripted{replies: []reply{{200, "text/event-stream", x.body}}}
|
||||
b := &scripted{replies: []reply{{200, "text/event-stream", chatFromB}}}
|
||||
scriptedOn(t, "a", x.proto, a)
|
||||
scriptedOn(t, "b", provider.Chat, b)
|
||||
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New()
|
||||
code, body := postAs(t, s, "", `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
if code != 200 || !strings.Contains(body, "from b") || a.n != 1 || b.n != 1 {
|
||||
t.Fatalf("%d %s (a %d, b %d) %+v", code, body, a.n, b.n, s.trace.routes[len(s.trace.routes)-1].Tries)
|
||||
}
|
||||
if r := s.trace.routes[len(s.trace.routes)-1]; r.Tries[0].Rest != nil || !strings.Contains(r.Tries[0].Error, emptyReply) {
|
||||
t.Fatalf("tries: %+v", r.Tries)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+126
-10
@@ -2753,6 +2753,13 @@ type holdWriter struct {
|
||||
// the tier the request went out at (stampTier), once it has a status
|
||||
tierStamp func(http.Header)
|
||||
|
||||
// emptyFails: a routing group's member stands behind the try, and a
|
||||
// reply of it that ends having said nothing at all fails it, for that
|
||||
// member to answer instead (emptyEnded, #6712); spoke says the held
|
||||
// reply has said something, read whole (wantWhole) past its first
|
||||
// content
|
||||
emptyFails, spoke bool
|
||||
|
||||
// over, when another candidate stands behind the try, reads what
|
||||
// passes before its answer begins for a refusal to hand to the next
|
||||
// one in the same stream (refusalHandover); handedOver says it was
|
||||
@@ -3215,7 +3222,18 @@ func (h *holdWriter) scan() {
|
||||
// protocol's terminator after it; an error above cannot.
|
||||
h.failure, h.failMsg, h.refused = status, msg, true
|
||||
return
|
||||
case eventEmptyEnd:
|
||||
if h.emptyFails && !h.spoke && !h.thinking {
|
||||
// nothing said, not even reasoning, and the reply over:
|
||||
// its usage and terminator may follow, which nobody gets
|
||||
h.failure, h.failMsg = http.StatusBadGateway, emptyEnded
|
||||
if h.stop != nil {
|
||||
h.stop()
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
h.spoke = true
|
||||
if h.wantWhole {
|
||||
if why, ok := endedIncomplete(rest[:end]); ok {
|
||||
h.failure, h.failMsg = http.StatusBadGateway, why
|
||||
@@ -3597,10 +3615,17 @@ func (h *holdWriter) settle() {
|
||||
if !h.whole {
|
||||
return
|
||||
}
|
||||
if msg, ok := refusedReply(h.held.Bytes()); ok {
|
||||
msg, refused, empty := readWhole(h.held.Bytes())
|
||||
if refused {
|
||||
h.failure, h.failMsg, h.refused = refusedStatus, msg, true
|
||||
return
|
||||
}
|
||||
if empty && h.emptyFails && h.status < 400 {
|
||||
// a reply given whole that said nothing at all (emptyEnded), read
|
||||
// in the same parse as for a refusal
|
||||
h.failure, h.failMsg = http.StatusBadGateway, emptyEnded
|
||||
return
|
||||
}
|
||||
if h.status < 400 {
|
||||
// a 200 that is only an error fails as that error's own status
|
||||
// would (errorReply): asked again, or of the next, not handed on
|
||||
@@ -3933,8 +3958,46 @@ const (
|
||||
eventRefusalError // the filter's error event: canceled like eventError
|
||||
eventBuffering // a lead saying the reply is held back for safety checks
|
||||
eventThinking // reasoning, before anything is said: a refusal may yet end it
|
||||
// eventEmptyEnd is a reply's end as it ends a whole turn — a stop,
|
||||
// not a cut at its length nor a filter's — in an event that says
|
||||
// nothing itself. The hold reads one only before anything was said
|
||||
// (scan): such a reply answered nothing at all (#6712, emptyEnded)
|
||||
eventEmptyEnd
|
||||
)
|
||||
|
||||
// emptyEnded is what a try whose reply ended with nothing in it at all —
|
||||
// no text, no reasoning, no call — fails with while a routing group's
|
||||
// next member stands behind it (holdWriter.emptyFails, #6712): the
|
||||
// empty reply's error, which the group answers with its next member and
|
||||
// rests nobody for (#1221). aistudio2api, behind the magpie-gemini-web
|
||||
// plugin, ended a 200 stream with only its role chunk and finish_reason
|
||||
// "stop" when Google's every regeneration came back malformed, and the
|
||||
// try stood as answered, the agent's turn ending with no reply and the
|
||||
// group's agy-cli and google never asked. The last member's goes as it
|
||||
// came: a reply meant to be empty ends there, asked of each member once.
|
||||
const emptyEnded = emptyReply + ": it ended with nothing in it"
|
||||
|
||||
// endsEmptyChat, endsEmptyAnthropic and endsEmptyGemini tell whether a
|
||||
// stop reason ends a turn a reply had nothing in (eventEmptyEnd): not one
|
||||
// cut at its length (answersNothing) nor one a filter or an error ended,
|
||||
// which say why themselves.
|
||||
func endsEmptyChat(fin string) bool {
|
||||
_, filtered := filterReasons[fin]
|
||||
return fin != "" && fin != "length" && fin != "error" && !filtered
|
||||
}
|
||||
|
||||
func endsEmptyAnthropic(stop string) bool {
|
||||
switch stop {
|
||||
case "end_turn", "stop_sequence", "tool_use":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func endsEmptyGemini(fin string) bool {
|
||||
return fin == "STOP"
|
||||
}
|
||||
|
||||
// refusedStatus is what a refusal with nothing said is answered as: a
|
||||
// request the agent is told not to send again as it is, rather than a
|
||||
// reply that looks whole but empty, which Codex asks for again and again,
|
||||
@@ -4222,6 +4285,9 @@ func streamEvent(ev []byte) (kind, status int, msg string) {
|
||||
if json.Unmarshal(v.Delta, &d) == nil && d.StopReason == "refusal" {
|
||||
return eventRefusal, refusedStatus, refusedDetail(d.StopReason, d.StopDetails)
|
||||
}
|
||||
if endsEmptyAnthropic(d.StopReason) {
|
||||
return eventEmptyEnd, 0, ""
|
||||
}
|
||||
case typ == "response.incomplete" || typ == "response.completed" && v.Response.Status == "incomplete":
|
||||
if d := v.Response.IncompleteDetails; d != nil {
|
||||
if r, ok := filterReasons[d.Reason]; ok {
|
||||
@@ -4238,6 +4304,9 @@ func streamEvent(ev []byte) (kind, status int, msg string) {
|
||||
// beside it — so nothing of the try has reached the agent, and
|
||||
// the failure is still held for the group's next candidate
|
||||
return eventError, streamStatus(emptyCompleted), emptyCompleted
|
||||
case typ == "response.completed" && v.Response.Status == "completed":
|
||||
// a reply's end; read before anything was said, it said nothing
|
||||
return eventEmptyEnd, 0, ""
|
||||
case typ == "" && v.Candidates != nil:
|
||||
// a Gemini chunk
|
||||
if r, ok := filterReasons[v.PromptFeedback.BlockReason]; ok {
|
||||
@@ -4261,6 +4330,9 @@ func streamEvent(ev []byte) (kind, status int, msg string) {
|
||||
if r, ok := filterReasons[c.FinishReason]; ok {
|
||||
return refusal(r)
|
||||
}
|
||||
if !thinks && endsEmptyGemini(c.FinishReason) {
|
||||
return eventEmptyEnd, 0, ""
|
||||
}
|
||||
if c.FinishReason != "" {
|
||||
return eventContent, 0, ""
|
||||
}
|
||||
@@ -4318,6 +4390,9 @@ func streamEvent(ev []byte) (kind, status int, msg string) {
|
||||
// stood as a success
|
||||
return eventError, streamStatus(finishFailed), finishFailed
|
||||
}
|
||||
if !thinks && endsEmptyChat(*c.FinishReason) {
|
||||
return eventEmptyEnd, 0, ""
|
||||
}
|
||||
return eventContent, 0, ""
|
||||
}
|
||||
}
|
||||
@@ -4545,6 +4620,15 @@ func refusedCode(data string) string {
|
||||
// "refusal", Chat's finish_reason "content_filter", Responses' incomplete
|
||||
// for content_filter, Gemini's SAFETY — with no text or call in it.
|
||||
func refusedReply(b []byte) (string, bool) {
|
||||
msg, refused, _ := readWhole(b)
|
||||
return msg, refused
|
||||
}
|
||||
|
||||
// readWhole reads a whole reply, not streamed, once: whether it is a
|
||||
// refusal with nothing said (refusedReply), and whether it is a turn
|
||||
// ended with nothing in it at all — no text, no reasoning, no call — as
|
||||
// a stream's eventEmptyEnd is (#6712).
|
||||
func readWhole(b []byte) (msg string, refused, empty bool) {
|
||||
var v struct {
|
||||
// Anthropic's
|
||||
StopReason string `json:"stop_reason"`
|
||||
@@ -4554,8 +4638,10 @@ func refusedReply(b []byte) (string, bool) {
|
||||
Choices []struct {
|
||||
FinishReason string `json:"finish_reason"`
|
||||
Message struct {
|
||||
Content any `json:"content"`
|
||||
ToolCalls []any `json:"tool_calls"`
|
||||
Content any `json:"content"`
|
||||
ToolCalls []any `json:"tool_calls"`
|
||||
ReasoningContent string `json:"reasoning_content"`
|
||||
Reasoning string `json:"reasoning"`
|
||||
} `json:"message"`
|
||||
} `json:"choices"`
|
||||
// Responses'
|
||||
@@ -4576,33 +4662,63 @@ func refusedReply(b []byte) (string, bool) {
|
||||
} `json:"promptFeedback"`
|
||||
}
|
||||
if json.Unmarshal(b, &v) != nil {
|
||||
return "", false
|
||||
return "", false, false
|
||||
}
|
||||
none := func(ps []streamPart) bool {
|
||||
return !slices.ContainsFunc(ps, streamPart.said)
|
||||
}
|
||||
if r, ok := filterReasons[v.StopReason]; ok && r == "refusal" && none(v.Content) {
|
||||
return refusedDetail(r, v.StopDetails), true
|
||||
return refusedDetail(r, v.StopDetails), true, false
|
||||
}
|
||||
for _, c := range v.Choices {
|
||||
if r, ok := filterReasons[c.FinishReason]; ok && (c.Message.Content == nil || c.Message.Content == "") && len(c.Message.ToolCalls) == 0 {
|
||||
return refusedNote(r), true
|
||||
return refusedNote(r), true, false
|
||||
}
|
||||
}
|
||||
if d := v.IncompleteDetails; v.Status == "incomplete" && d != nil && none(v.Output) {
|
||||
if r, ok := filterReasons[d.Reason]; ok {
|
||||
return refusedNote(r), true
|
||||
return refusedNote(r), true, false
|
||||
}
|
||||
}
|
||||
if r, ok := filterReasons[v.PromptFeedback.BlockReason]; ok {
|
||||
return refusedNote(r), true
|
||||
return refusedNote(r), true, false
|
||||
}
|
||||
for _, c := range v.Candidates {
|
||||
if r, ok := filterReasons[c.FinishReason]; ok && len(c.Content.Parts) == 0 {
|
||||
return refusedNote(r), true
|
||||
return refusedNote(r), true, false
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
switch {
|
||||
case endsEmptyAnthropic(v.StopReason):
|
||||
empty = none(v.Content)
|
||||
case len(v.Choices) > 0:
|
||||
empty = true
|
||||
for _, c := range v.Choices {
|
||||
m := c.Message
|
||||
if !endsEmptyChat(c.FinishReason) || m.Content != nil && m.Content != "" || len(m.ToolCalls) > 0 || m.ReasoningContent != "" || m.Reasoning != "" {
|
||||
empty = false
|
||||
}
|
||||
}
|
||||
case v.Status == "completed" && v.Output != nil:
|
||||
empty = none(v.Output)
|
||||
case len(v.Candidates) > 0:
|
||||
empty = true
|
||||
for _, c := range v.Candidates {
|
||||
if !endsEmptyGemini(c.FinishReason) || slices.ContainsFunc(c.Content.Parts, geminiPartSays) {
|
||||
empty = false
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", false, empty
|
||||
}
|
||||
|
||||
// geminiPartSays tells whether a Gemini part has anything in it: text,
|
||||
// reasoning, or anything that isn't text (a call, an image).
|
||||
func geminiPartSays(p json.RawMessage) bool {
|
||||
var part struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
return json.Unmarshal(p, &part) != nil || part.Text != "" || !bodyHas(p, `"text"`)
|
||||
}
|
||||
|
||||
// errorReply says whether a reply that came whole under a success status
|
||||
|
||||
@@ -3837,6 +3837,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
// a compaction's summary is held to its end, for a cut or an
|
||||
// error halfway to go to the next candidate (#2274)
|
||||
hw.wantWhole = wantWhole && !pass
|
||||
// a group member's reply that said nothing at all goes to the
|
||||
// next member while one is left (emptyEnded, #6712); the last
|
||||
// one's goes as it came
|
||||
hw.emptyFails = isGroup && !last && !pass
|
||||
// Claude's and GPT's reasoning is held for a refusal after it only
|
||||
// while another candidate could answer instead: the last one's
|
||||
// refusal isn't asked again, so holding it only kept a lone relay's
|
||||
|
||||
@@ -396,10 +396,10 @@ func TestStreamEventRefusals(t *testing.T) {
|
||||
{`event: content_block_delta` + "\n" + `data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"hm"}}`, eventThinking},
|
||||
{`event: content_block_delta` + "\n" + `data: {"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":""}}`, eventContent},
|
||||
{`event: message_delta` + "\n" + `data: {"type":"message_delta","delta":{"stop_reason":"refusal"}}`, eventRefusal},
|
||||
{`event: message_delta` + "\n" + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}`, eventContent},
|
||||
{`event: message_delta` + "\n" + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}`, eventEmptyEnd},
|
||||
{`data: {"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"content_filter"}]}`, eventRefusal},
|
||||
{`data: {"id":"c","choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":"content_filter"}]}`, eventContent},
|
||||
{`data: {"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, eventContent},
|
||||
{`data: {"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, eventEmptyEnd},
|
||||
{`data: {"type":"response.output_item.added","item":{"type":"reasoning","summary":[]}}`, eventThinking},
|
||||
{`data: {"type":"response.reasoning_summary_text.delta","delta":"**Plan**"}`, eventThinking},
|
||||
{`data: {"id":"c","choices":[{"index":0,"delta":{"reasoning_content":"hm"}}]}`, eventThinking},
|
||||
@@ -411,7 +411,7 @@ func TestStreamEventRefusals(t *testing.T) {
|
||||
{`data: {"type":"response.reasoning_summary_part.added","part":{"type":"summary_text","text":""}}`, eventThinking},
|
||||
{`data: {"type":"response.incomplete","response":{"status":"incomplete","incomplete_details":{"reason":"content_filter"}}}`, eventRefusal},
|
||||
{`data: {"type":"response.incomplete","response":{"status":"incomplete","incomplete_details":{"reason":"max_output_tokens"}}}`, eventContent},
|
||||
{`data: {"type":"response.completed","response":{"status":"completed"}}`, eventContent},
|
||||
{`data: {"type":"response.completed","response":{"status":"completed"}}`, eventEmptyEnd},
|
||||
{`data: {"type":"error","error":{"code":"content_filter","message":"filtered"}}`, eventRefusalError},
|
||||
{`data: {"candidates":[{"content":{"parts":[]},"finishReason":"SAFETY"}]}`, eventRefusal},
|
||||
{`data: {"candidates":[{"content":{"parts":[{"text":"hi"}]},"finishReason":"SAFETY"}]}`, eventContent},
|
||||
|
||||
@@ -168,7 +168,7 @@ func TestStreamErrorBeforeContentFailsOver(t *testing.T) {
|
||||
{`: keep-alive`, eventLead},
|
||||
{`data: {"id":"c","choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}`, eventLead},
|
||||
{`data: {"id":"c","choices":[{"index":0,"delta":{"content":"hi"}}]}`, eventContent},
|
||||
{`data: {"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, eventContent},
|
||||
{`data: {"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, eventEmptyEnd},
|
||||
{`data: {"id":"c","choices":[{"index":0,"delta":{},"finish_reason":"error"}]}`, eventError},
|
||||
{`data: {"error":{"message":"upstream failed"}}`, eventError},
|
||||
{`event: response.created` + "\n" + `data: {"type":"response.created","response":{"id":"r"}}`, eventLead},
|
||||
|
||||
Reference in New Issue
Block a user