gateway: a translated model's messages say their phase, so Codex folds them (#2437)
Codex Desktop folds a finished turn's commentary and calls under "Worked
for …" by each assistant message's `phase`, which OpenAI's own models
write ("commentary" / "final_answer"). A message with none is read as an
answer, so every progress line of a model magpie translates (the
reporter's Qoder plugin, a chat upstream) stayed unfolded.
The Responses encoder now holds a message's output_item.done until the
next item that isn't reasoning opens (commentary) or the reply completes
(final_answer); the completed output carries the same phases.
renderResponses does the same for a whole reply. A Responses upstream
relayed as it is (passthrough) gets the same rule through a new phase
tidy, streamed or whole. A phase the upstream wrote is kept; a reply cut
short (incomplete, failed, error, a stream with no end) guesses no final
answer, since Codex reads a missing phase as the answer. Keepalives go
out at once; sequence numbers are given in write order. At most 512
events wait behind a message, then it goes without a phase. Codex's
base_instructions are not touched.
Run (worktree at origin/main cf21b71ff):
- new tests in internal/gateway/phase_test.go: encoder (call, reasoning
then call, last, reasoning after, length cut, two messages around a
call, keepalive while held), renderResponses, phase tidy (SSE fed a
byte at a time, CRLF, upstream phase kept, incomplete, no end, whole
reply with a 20-digit number kept) and a passthrough through the gateway
- broken by hand, each went red: encoder release ignoring the phase (3
tests), renderResponses without phaseOutput (1), passthrough without
the tidy (1), unphased ignoring an upstream phase (1 subtest)
- gofmt -l clean; go vet -tags nogui for darwin, linux, windows ok
- full suite: set -o pipefail; HOME=<scratch>/home-2437 GOMODCACHE=~/go/pkg/mod go test -tags nogui -count=1 -timeout 45m ./... at cf21b71ff plus this change: exit 0, 66 packages ok, none FAIL (gateway 844s, provider 355s)
- rebased onto origin/main a61a6f954 and run again: gofmt -l clean; go vet -tags nogui darwin, linux, windows ok; set -o pipefail; go test -timeout 45m ./... in a scratch HOME: exit 0, 66 packages ok
Full suite: green at a61a6f954 plus this change, 66 packages ok, exit 0.
This commit is contained in:
@@ -4376,6 +4376,19 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
if (proto == provider.Responses || proto == provider.Chat || proto == provider.Anthropic) && (grokModel(model) || grokModel(upstream)) {
|
||||
ints = &intTidy{proto: proto, sse: sse}
|
||||
}
|
||||
// a message the upstream gave no phase gets one, as OpenAI's own
|
||||
// models' do (phase.go, #2437); it goes last, as it holds events back
|
||||
var phases *phaseTidy
|
||||
if proto == provider.Responses {
|
||||
phases = &phaseTidy{sse: sse}
|
||||
}
|
||||
// out is what a filter let through, through phases
|
||||
out := func(b []byte) []byte {
|
||||
if phases != nil {
|
||||
return phases.write(b)
|
||||
}
|
||||
return b
|
||||
}
|
||||
buf := make([]byte, 32<<10)
|
||||
var rerr error
|
||||
for {
|
||||
@@ -4404,6 +4417,9 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
if sigs != nil {
|
||||
out = sigs.write(out)
|
||||
}
|
||||
if phases != nil {
|
||||
out = phases.write(out)
|
||||
}
|
||||
if _, werr := w.Write(out); werr != nil {
|
||||
return res.StatusCode, "", true
|
||||
}
|
||||
@@ -4418,14 +4434,14 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
}
|
||||
// what's held at the end goes through the filters after the one
|
||||
// that held it
|
||||
sign := func(out []byte) []byte {
|
||||
sign := func(b []byte) []byte {
|
||||
if ints != nil {
|
||||
out = ints.write(out)
|
||||
b = ints.write(b)
|
||||
}
|
||||
if sigs != nil {
|
||||
return sigs.write(out)
|
||||
b = sigs.write(b)
|
||||
}
|
||||
return out
|
||||
return out(b)
|
||||
}
|
||||
if tidy != nil {
|
||||
out := tidy.flush()
|
||||
@@ -4454,14 +4470,17 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
w.Write(sign(spaces.flush()))
|
||||
}
|
||||
if ints != nil {
|
||||
out := ints.flush()
|
||||
b := ints.flush()
|
||||
if sigs != nil {
|
||||
out = sigs.write(out)
|
||||
b = sigs.write(b)
|
||||
}
|
||||
w.Write(out)
|
||||
w.Write(out(b))
|
||||
}
|
||||
if sigs != nil {
|
||||
w.Write(sigs.flush())
|
||||
w.Write(out(sigs.flush()))
|
||||
}
|
||||
if phases != nil {
|
||||
w.Write(phases.flush())
|
||||
}
|
||||
if sse {
|
||||
sniff.drain()
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
// An assistant message in a Responses reply says its phase, as OpenAI's
|
||||
// own models' do: "commentary" for what the model said on the way (before
|
||||
// a call), "final_answer" for the answer that ends the turn. Codex folds a
|
||||
// finished turn's commentary and calls under "Worked for …" and leaves the
|
||||
// final answer out, and reads a message with no phase as an answer, so a
|
||||
// model magpie translates had every progress line left unfolded (#2437).
|
||||
//
|
||||
// A message's phase is known only from what comes after it: a call, a
|
||||
// search or another message makes it commentary; the reply ending with
|
||||
// nothing but reasoning after it makes it the final answer. A reply cut
|
||||
// short (incomplete, failed, cut mid-stream) guesses no final answer, and
|
||||
// a phase the upstream wrote is kept.
|
||||
|
||||
const (
|
||||
phaseCommentary = "commentary"
|
||||
phaseFinal = "final_answer"
|
||||
)
|
||||
|
||||
// heldMost is how many events may wait behind a message whose phase isn't
|
||||
// known yet; past it they go on, and the message without a phase.
|
||||
const heldMost = 512
|
||||
|
||||
// unphased reports whether an output item is an assistant message with no
|
||||
// phase of its own.
|
||||
func unphased(it map[string]any) bool {
|
||||
if it == nil || it["type"] != "message" {
|
||||
return false
|
||||
}
|
||||
if r, ok := it["role"]; ok && r != "assistant" {
|
||||
return false
|
||||
}
|
||||
p, _ := it["phase"].(string)
|
||||
return p == ""
|
||||
}
|
||||
|
||||
// phaseOutput gives each assistant message in a reply's output its phase,
|
||||
// and reports whether it gave any. done is whether the reply ended
|
||||
// completed: only then is the last message the final answer.
|
||||
func phaseOutput(output []any, done bool) bool {
|
||||
last := -1 // the last item that isn't reasoning
|
||||
for i, it := range output {
|
||||
if m, _ := it.(map[string]any); m != nil && m["type"] != "reasoning" {
|
||||
last = i
|
||||
}
|
||||
}
|
||||
changed := false
|
||||
for i, it := range output {
|
||||
m, _ := it.(map[string]any)
|
||||
if !unphased(m) {
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case i < last:
|
||||
m["phase"] = phaseCommentary
|
||||
case i == last && done:
|
||||
m["phase"] = phaseFinal
|
||||
default:
|
||||
continue
|
||||
}
|
||||
changed = true
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
// phaseTidy gives, in a relayed Responses reply, its assistant messages a
|
||||
// phase where the upstream wrote none. In a stream a message's
|
||||
// output_item.done waits, with what comes after it, until the next item
|
||||
// that isn't reasoning (commentary) or the reply's end (final answer); a
|
||||
// reply that isn't a stream is held whole and gone through at the end.
|
||||
type phaseTidy struct {
|
||||
sse bool
|
||||
buf []byte // a stream's part of an event, or a whole reply
|
||||
held [][]byte // events waiting on the first's message's phase
|
||||
}
|
||||
|
||||
func (t *phaseTidy) write(b []byte) []byte {
|
||||
t.buf = append(t.buf, b...)
|
||||
if !t.sse {
|
||||
return nil
|
||||
}
|
||||
var out []byte
|
||||
for {
|
||||
n := eventEnd(t.buf)
|
||||
if n < 0 {
|
||||
return out
|
||||
}
|
||||
out = append(out, t.event(t.buf[:n])...)
|
||||
t.buf = t.buf[n:]
|
||||
}
|
||||
}
|
||||
|
||||
func (t *phaseTidy) flush() []byte {
|
||||
b := t.buf
|
||||
t.buf = nil
|
||||
if !t.sse {
|
||||
if out, ok := phaseWhole(b); ok {
|
||||
return out
|
||||
}
|
||||
return b
|
||||
}
|
||||
// a stream that ended with a message still waiting: nothing says it
|
||||
// ended the turn, so it goes as it came
|
||||
out := t.release("")
|
||||
return append(out, b...)
|
||||
}
|
||||
|
||||
// eventData is an event's data, joined as SSE joins it.
|
||||
func eventData(ev []byte) []byte {
|
||||
var data []byte
|
||||
n := 0
|
||||
for _, line := range bytes.Split(ev, []byte("\n")) {
|
||||
line = bytes.TrimRight(line, "\r")
|
||||
if d, ok := bytes.CutPrefix(line, []byte("data:")); ok {
|
||||
if n > 0 {
|
||||
data = append(data, '\n')
|
||||
}
|
||||
data = append(data, bytes.TrimPrefix(d, []byte(" "))...)
|
||||
n++
|
||||
}
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// withData is ev with its data lines put back as data.
|
||||
func withData(ev, data []byte) []byte {
|
||||
var out []byte
|
||||
put := false
|
||||
for _, line := range bytes.SplitAfter(ev, []byte("\n")) {
|
||||
body := bytes.TrimRight(line, "\r\n")
|
||||
if bytes.HasPrefix(body, []byte("data:")) {
|
||||
if !put {
|
||||
out = append(append(append(out, "data: "...), data...), line[len(body):]...)
|
||||
put = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
out = append(out, line...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (t *phaseTidy) event(ev []byte) []byte {
|
||||
data := eventData(ev)
|
||||
typ := gjson.GetBytes(data, "type").String()
|
||||
if t.held != nil {
|
||||
switch typ {
|
||||
case "response.output_item.added":
|
||||
if gjson.GetBytes(data, "item.type").String() == "reasoning" {
|
||||
return t.hold(ev)
|
||||
}
|
||||
return append(t.release(phaseCommentary), t.event(ev)...)
|
||||
case "response.completed":
|
||||
return append(t.release(phaseFinal), t.ended(ev, data, true)...)
|
||||
case "response.incomplete", "response.failed", "error":
|
||||
return append(t.release(""), t.ended(ev, data, false)...)
|
||||
}
|
||||
return t.hold(ev)
|
||||
}
|
||||
switch typ {
|
||||
case "response.output_item.done":
|
||||
it := gjson.GetBytes(data, "item")
|
||||
if it.Get("type").String() == "message" && it.Get("role").String() != "user" && it.Get("phase").String() == "" {
|
||||
t.held = [][]byte{append([]byte(nil), ev...)}
|
||||
return nil
|
||||
}
|
||||
case "response.completed":
|
||||
return t.ended(ev, data, true)
|
||||
case "response.incomplete":
|
||||
return t.ended(ev, data, false)
|
||||
}
|
||||
return append([]byte(nil), ev...)
|
||||
}
|
||||
|
||||
func (t *phaseTidy) hold(ev []byte) []byte {
|
||||
t.held = append(t.held, append([]byte(nil), ev...))
|
||||
if len(t.held) > heldMost {
|
||||
return t.release("")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// release is the waiting events, the message among them given phase (or
|
||||
// left as it came, for "").
|
||||
func (t *phaseTidy) release(phase string) []byte {
|
||||
held := t.held
|
||||
t.held = nil
|
||||
if len(held) == 0 {
|
||||
return nil
|
||||
}
|
||||
if phase != "" {
|
||||
if nb, ok := phasedEvent(eventData(held[0]), phase); ok {
|
||||
held[0] = withData(held[0], nb)
|
||||
}
|
||||
}
|
||||
return bytes.Join(held, nil)
|
||||
}
|
||||
|
||||
// ended is the reply's last event, its output's messages given their phase
|
||||
// as the stream gave them.
|
||||
func (t *phaseTidy) ended(ev, data []byte, done bool) []byte {
|
||||
var e map[string]any
|
||||
if decodeNumbers(data, &e) != nil {
|
||||
return append([]byte(nil), ev...)
|
||||
}
|
||||
res, _ := e["response"].(map[string]any)
|
||||
out, _ := res["output"].([]any)
|
||||
if !phaseOutput(out, done) {
|
||||
return append([]byte(nil), ev...)
|
||||
}
|
||||
nb, err := marshalPlain(e)
|
||||
if err != nil {
|
||||
return append([]byte(nil), ev...)
|
||||
}
|
||||
return withData(ev, nb)
|
||||
}
|
||||
|
||||
// phasedEvent is an output_item.done event with its message given phase.
|
||||
func phasedEvent(data []byte, phase string) ([]byte, bool) {
|
||||
var e map[string]any
|
||||
if decodeNumbers(data, &e) != nil {
|
||||
return nil, false
|
||||
}
|
||||
it, _ := e["item"].(map[string]any)
|
||||
if !unphased(it) {
|
||||
return nil, false
|
||||
}
|
||||
it["phase"] = phase
|
||||
nb, err := marshalPlain(e)
|
||||
return nb, err == nil
|
||||
}
|
||||
|
||||
// phaseWhole is a whole Responses reply with its messages' phases.
|
||||
func phaseWhole(b []byte) ([]byte, bool) {
|
||||
var res map[string]any
|
||||
if decodeNumbers(b, &res) != nil || res == nil || res["object"] != "response" {
|
||||
return nil, false
|
||||
}
|
||||
out, _ := res["output"].([]any)
|
||||
if !phaseOutput(out, res["status"] == "completed") {
|
||||
return nil, false
|
||||
}
|
||||
nb, err := marshalPlain(res)
|
||||
return nb, err == nil
|
||||
}
|
||||
|
||||
func decodeNumbers(b []byte, v any) error {
|
||||
dec := json.NewDecoder(bytes.NewReader(b))
|
||||
dec.UseNumber()
|
||||
return dec.Decode(v)
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// phases is each assistant message's phase, in order, as the stream's
|
||||
// output_item.done events gave them, then as its last event's output did.
|
||||
func phases(body string) (streamed, ended []string) {
|
||||
for _, ev := range events(body) {
|
||||
switch ev["type"] {
|
||||
case "response.output_item.done":
|
||||
if it, _ := ev["item"].(map[string]any); it["type"] == "message" {
|
||||
p, _ := it["phase"].(string)
|
||||
streamed = append(streamed, p)
|
||||
}
|
||||
case "response.completed", "response.incomplete", "response.failed":
|
||||
res, _ := ev["response"].(map[string]any)
|
||||
out, _ := res["output"].([]any)
|
||||
for _, o := range out {
|
||||
if it, _ := o.(map[string]any); it["type"] == "message" {
|
||||
p, _ := it["phase"].(string)
|
||||
ended = append(ended, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func encoded(evs ...Event) string {
|
||||
rec := httptest.NewRecorder()
|
||||
enc := encoder(provider.Responses, newSSEWriter(rec), &Request{Model: "m"})
|
||||
for _, ev := range evs {
|
||||
enc.event(ev)
|
||||
}
|
||||
enc.finish()
|
||||
return rec.Body.String()
|
||||
}
|
||||
|
||||
// #2437: a translated model's messages say their phase, as OpenAI's do, so
|
||||
// Codex folds what was said on the way to a call under "Worked for …" and
|
||||
// shows the answer apart.
|
||||
func TestTranslatedMessagesSayPhase(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
evs []Event
|
||||
want string
|
||||
}{
|
||||
{"said before a call", []Event{{Kind: KText, Text: "Let me look."}, {Kind: KToolStart, ID: "c1", Name: "shell"}, {Kind: KToolArgs, Text: `{}`}, {Kind: KStop, Stop: "tool"}}, "commentary"},
|
||||
{"said before reasoning and a call", []Event{{Kind: KText, Text: "Let me look."}, {Kind: KThink, Text: "hm"}, {Kind: KToolStart, ID: "c1", Name: "shell"}, {Kind: KToolArgs, Text: `{}`}, {Kind: KStop, Stop: "tool"}}, "commentary"},
|
||||
{"said last", []Event{{Kind: KText, Text: "Done."}, {Kind: KStop, Stop: "stop"}}, "final_answer"},
|
||||
{"said last, reasoning after", []Event{{Kind: KText, Text: "Done."}, {Kind: KThink, Text: "hm"}, {Kind: KStop, Stop: "stop"}}, "final_answer"},
|
||||
{"cut at the length", []Event{{Kind: KText, Text: "Done"}, {Kind: KStop, Stop: "length"}}, ""},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
body := encoded(tc.evs...)
|
||||
streamed, ended := phases(body)
|
||||
if len(streamed) != 1 || streamed[0] != tc.want {
|
||||
t.Fatalf("streamed phases %q, want %q\n%s", streamed, tc.want, body)
|
||||
}
|
||||
if len(ended) != 1 || ended[0] != tc.want {
|
||||
t.Fatalf("ended phases %q, want %q\n%s", ended, tc.want, body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Two messages around a call: the first is commentary, the last the answer.
|
||||
func TestTranslatedMessagesAroundACall(t *testing.T) {
|
||||
body := encoded(
|
||||
Event{Kind: KText, Text: "Checking."},
|
||||
Event{Kind: KToolStart, ID: "c1", Name: "shell"},
|
||||
Event{Kind: KToolArgs, Text: `{}`},
|
||||
Event{Kind: KText, Text: "Found it."},
|
||||
Event{Kind: KStop, Stop: "stop"},
|
||||
)
|
||||
if streamed, ended := phases(body); strings.Join(streamed, ",") != "commentary,final_answer" || strings.Join(ended, ",") != "commentary,final_answer" {
|
||||
t.Fatalf("streamed %q, ended %q\n%s", streamed, ended, body)
|
||||
}
|
||||
}
|
||||
|
||||
// A keepalive while a message waits for its phase goes out at once, and
|
||||
// sequence numbers rise in the order events are written.
|
||||
func TestHeldMessageKeepsSequence(t *testing.T) {
|
||||
body := encoded(
|
||||
Event{Kind: KText, Text: "Checking."},
|
||||
Event{Kind: KAlive},
|
||||
Event{Kind: KToolStart, ID: "c1", Name: "shell"},
|
||||
Event{Kind: KToolArgs, Text: `{}`},
|
||||
)
|
||||
last := -1.0
|
||||
for _, ev := range events(body) {
|
||||
n, ok := ev["sequence_number"].(float64)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if n <= last {
|
||||
t.Fatalf("sequence %v after %v\n%s", n, last, body)
|
||||
}
|
||||
last = n
|
||||
}
|
||||
if streamed, _ := phases(body); strings.Join(streamed, ",") != "commentary" {
|
||||
t.Fatalf("streamed %q", streamed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderedMessagesSayPhase(t *testing.T) {
|
||||
res := Result{Stop: "tool", Parts: []Part{
|
||||
{Kind: Text, Text: "Checking."},
|
||||
{Kind: ToolCall, ID: "c1", Name: "shell", Args: json.RawMessage(`{}`)},
|
||||
}}
|
||||
var out struct {
|
||||
Output []map[string]any `json:"output"`
|
||||
}
|
||||
if err := json.Unmarshal(renderResponses(res, "m", nil), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out.Output[0]["phase"] != "commentary" {
|
||||
t.Fatalf("output %v", out.Output)
|
||||
}
|
||||
res = Result{Stop: "stop", Parts: []Part{{Kind: Text, Text: "Done."}}}
|
||||
out.Output = nil
|
||||
if err := json.Unmarshal(renderResponses(res, "m", nil), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out.Output[0]["phase"] != "final_answer" {
|
||||
t.Fatalf("output %v", out.Output)
|
||||
}
|
||||
}
|
||||
|
||||
func tidied(t *testing.T, sse bool, chunks ...string) string {
|
||||
t.Helper()
|
||||
p := &phaseTidy{sse: sse}
|
||||
var out []byte
|
||||
for _, c := range chunks {
|
||||
// a byte at a time, as an upstream may cut it
|
||||
for i := range len(c) {
|
||||
out = append(out, p.write([]byte{c[i]})...)
|
||||
}
|
||||
}
|
||||
return string(append(out, p.flush()...))
|
||||
}
|
||||
|
||||
const (
|
||||
evMsg = `data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"m1","role":"assistant","content":[{"type":"output_text","text":"Checking."}]}}`
|
||||
evRsAdd = `data: {"type":"response.output_item.added","output_index":1,"item":{"type":"reasoning","id":"rs1"}}`
|
||||
evRs = `data: {"type":"response.output_item.done","output_index":1,"item":{"type":"reasoning","id":"rs1","summary":[]}}`
|
||||
evFcAdd = `data: {"type":"response.output_item.added","output_index":2,"item":{"type":"function_call","id":"fc1","call_id":"c1","name":"shell","arguments":""}}`
|
||||
evDone = `data: {"type":"response.completed","response":{"id":"r","status":"completed","output":[{"type":"message","id":"m1","role":"assistant","content":[]}],"usage":{"input_tokens":5,"output_tokens":2}}}`
|
||||
evCut = `data: {"type":"response.incomplete","response":{"id":"r","status":"incomplete","output":[{"type":"message","id":"m1","role":"assistant","content":[]}]}}`
|
||||
)
|
||||
|
||||
// A Responses upstream relayed as it is: its messages with no phase get
|
||||
// one, by the same rule; one it gave a phase keeps it.
|
||||
func TestRelayedMessagesSayPhase(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
chunks []string
|
||||
streamed, end string
|
||||
}{
|
||||
{"before a call", []string{sse(evMsg, evRsAdd, evRs, evFcAdd, evDone)}, "commentary", "final_answer"},
|
||||
{"last, reasoning after", []string{sse(evMsg, evRsAdd, evRs, evDone)}, "final_answer", "final_answer"},
|
||||
{"cut short", []string{sse(evMsg, evCut)}, "", ""},
|
||||
{"stream ends without an end", []string{sse(evMsg, evRsAdd)}, "", ""},
|
||||
{"upstream's own phase", []string{sse(strings.Replace(evMsg, `"role":"assistant"`, `"role":"assistant","phase":"commentary"`, 1), strings.Replace(evDone, `"role":"assistant"`, `"role":"assistant","phase":"commentary"`, 1))}, "commentary", "commentary"},
|
||||
{"CRLF", []string{strings.ReplaceAll(sse(evMsg, evFcAdd, evDone), "\n", "\r\n")}, "commentary", "final_answer"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
body := tidied(t, true, tc.chunks...)
|
||||
streamed, ended := phases(strings.ReplaceAll(body, "\r\n", "\n"))
|
||||
if strings.Join(streamed, ",") != tc.streamed {
|
||||
t.Fatalf("streamed %q, want %q\n%s", streamed, tc.streamed, body)
|
||||
}
|
||||
if tc.end != "" || len(ended) > 0 {
|
||||
if strings.Join(ended, ",") != tc.end {
|
||||
t.Fatalf("ended %q, want %q\n%s", ended, tc.end, body)
|
||||
}
|
||||
}
|
||||
// nothing is lost or reordered but the phase
|
||||
want := strings.Join(tc.chunks, "")
|
||||
if got := strings.NewReplacer(`,"phase":"commentary"`, "", `,"phase":"final_answer"`, "").Replace(body); tc.name != "upstream's own phase" && len(got) != len(want) {
|
||||
t.Fatalf("relayed %d bytes, want %d\n%s", len(got), len(want), body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelayedWholeReplySaysPhase(t *testing.T) {
|
||||
whole := `{"id":"r","object":"response","status":"completed","output":[{"type":"message","role":"assistant","content":[]},{"type":"function_call","call_id":"c1","name":"shell","arguments":"{}"},{"type":"message","role":"assistant","content":[]}],"usage":{"input_tokens":12345678901234567890}}`
|
||||
got := tidied(t, false, whole)
|
||||
var res struct {
|
||||
Output []map[string]any `json:"output"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(got), &res); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.Output[0]["phase"] != "commentary" || res.Output[2]["phase"] != "final_answer" || !strings.Contains(got, "12345678901234567890") {
|
||||
t.Fatalf("%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Through the gateway: a Responses provider whose model writes no phase.
|
||||
func TestRelayedStreamSaysPhase(t *testing.T) {
|
||||
fresh(t)
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
io.Copy(io.Discard, r.Body)
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, sse(evMsg, evFcAdd,
|
||||
`data: {"type":"response.output_item.done","output_index":2,"item":{"type":"function_call","id":"fc1","call_id":"c1","name":"shell","arguments":"{}"}}`,
|
||||
`data: {"type":"response.completed","response":{"id":"r","status":"completed","output":[{"type":"message","id":"m1","role":"assistant","content":[]},{"type":"function_call","id":"fc1","call_id":"c1","name":"shell","arguments":"{}"}]}}`))
|
||||
}))
|
||||
t.Cleanup(up.Close)
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Models: []string{"gpt-5.4"}, Responses: up.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := codexPostTo(New(), `{"model":"relay/gpt-5.4","stream":true,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}]}`)
|
||||
if streamed, ended := phases(rec.Body.String()); rec.Code != 200 || strings.Join(streamed, ",") != "commentary" || strings.Join(ended, ",") != "commentary" {
|
||||
t.Fatalf("%d streamed %q ended %q\n%s", rec.Code, streamed, ended, rec.Body)
|
||||
}
|
||||
}
|
||||
@@ -1502,6 +1502,15 @@ type responsesEncoder struct {
|
||||
// collector's last part isn't it once a hidden thinking block (signed
|
||||
// with no text, or redacted) has come after the call (#1786)
|
||||
call Part
|
||||
// a message's output_item.done, and the events after it, wait here
|
||||
// until its phase is known (phase.go, #2437)
|
||||
heldMsg map[string]any
|
||||
held []heldEvent
|
||||
}
|
||||
|
||||
type heldEvent struct {
|
||||
typ string
|
||||
fields map[string]any
|
||||
}
|
||||
|
||||
// callTo names the tool a function_call item is to as the client knows it:
|
||||
@@ -1549,12 +1558,39 @@ func itemPrefix(item map[string]any) string {
|
||||
}
|
||||
|
||||
func (e *responsesEncoder) send(typ string, fields map[string]any) {
|
||||
if e.heldMsg != nil {
|
||||
e.held = append(e.held, heldEvent{typ, fields})
|
||||
if len(e.held) > heldMost {
|
||||
e.release("")
|
||||
}
|
||||
return
|
||||
}
|
||||
e.write(typ, fields)
|
||||
}
|
||||
|
||||
func (e *responsesEncoder) write(typ string, fields map[string]any) {
|
||||
fields["type"] = typ
|
||||
fields["sequence_number"] = e.seq
|
||||
e.seq++
|
||||
e.w.event(typ, fields)
|
||||
}
|
||||
|
||||
// release sends the waiting message's events, the message given phase
|
||||
// (or none, for "").
|
||||
func (e *responsesEncoder) release(phase string) {
|
||||
if e.heldMsg == nil {
|
||||
return
|
||||
}
|
||||
if phase != "" {
|
||||
e.heldMsg["phase"] = phase
|
||||
}
|
||||
held := e.held
|
||||
e.heldMsg, e.held = nil, nil
|
||||
for _, h := range held {
|
||||
e.write(h.typ, h.fields)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *responsesEncoder) response(status string, extra map[string]any) map[string]any {
|
||||
// a list, never null, before any item: Muse Code refuses a stream whose
|
||||
// response.created has output null (its nil slice in an any isn't nil)
|
||||
@@ -1606,7 +1642,10 @@ func (e *responsesEncoder) closeAs(sealed json.RawMessage) {
|
||||
e.send("response.output_text.done", map[string]any{"item_id": e.itemID, "output_index": e.item, "content_index": 0, "text": t, "logprobs": []any{}})
|
||||
part := map[string]any{"type": "output_text", "text": t, "annotations": []any{}, "logprobs": []any{}}
|
||||
e.send("response.content_part.done", map[string]any{"item_id": e.itemID, "output_index": e.item, "content_index": 0, "part": part})
|
||||
item = map[string]any{"id": e.itemID, "type": "message", "role": "assistant", "status": "completed", "content": []map[string]any{part}}
|
||||
m := map[string]any{"id": e.itemID, "type": "message", "role": "assistant", "status": "completed", "content": []map[string]any{part}}
|
||||
// its done waits for what comes next to say its phase
|
||||
e.release(phaseCommentary)
|
||||
item, e.heldMsg = m, m
|
||||
case Thinking:
|
||||
t := e.text.String()
|
||||
e.send("response.reasoning_summary_text.done", map[string]any{"item_id": e.itemID, "output_index": e.item, "summary_index": 0, "text": t})
|
||||
@@ -1634,6 +1673,9 @@ func (e *responsesEncoder) closeAs(sealed json.RawMessage) {
|
||||
|
||||
func (e *responsesEncoder) openItem(k Kind, prefix string, item map[string]any) {
|
||||
e.closeItem()
|
||||
if k != Thinking {
|
||||
e.release(phaseCommentary)
|
||||
}
|
||||
e.item++
|
||||
e.open, e.itemID = k, prefix+newID()
|
||||
if k == Thinking && e.thinkID != "" {
|
||||
@@ -1701,6 +1743,7 @@ func (e *responsesEncoder) event(ev Event) {
|
||||
// and sources, as Anthropic's encoder does, without inventing
|
||||
// earlier in-progress events or citation offsets in the answer.
|
||||
e.closeItem()
|
||||
e.release(phaseCommentary)
|
||||
e.item++
|
||||
item := responsesSearchItem(ev.Text, ev.Hits)
|
||||
e.send("response.output_item.added", map[string]any{"output_index": e.item, "item": item})
|
||||
@@ -1729,6 +1772,7 @@ func (e *responsesEncoder) event(ev Event) {
|
||||
}
|
||||
case KError:
|
||||
e.closeItem()
|
||||
e.release("")
|
||||
code := "server_error"
|
||||
if ev.Code != "" {
|
||||
code = ev.Code
|
||||
@@ -1747,7 +1791,8 @@ func (e *responsesEncoder) keepalive() {
|
||||
e.start(Event{}) // response.created and response.in_progress
|
||||
return
|
||||
}
|
||||
e.send("response.in_progress", map[string]any{"response": e.response("in_progress", nil)})
|
||||
// past what's waiting: a keepalive held back keeps nothing alive
|
||||
e.write("response.in_progress", map[string]any{"response": e.response("in_progress", nil)})
|
||||
}
|
||||
|
||||
func (e *responsesEncoder) finish() {
|
||||
@@ -1766,6 +1811,10 @@ func (e *responsesEncoder) finish() {
|
||||
}
|
||||
extra["incomplete_details"] = map[string]any{"reason": reason}
|
||||
}
|
||||
if status == "completed" {
|
||||
e.release(phaseFinal)
|
||||
}
|
||||
e.release("")
|
||||
e.send(typ, map[string]any{"response": e.response(status, extra)})
|
||||
}
|
||||
|
||||
@@ -1838,6 +1887,7 @@ func renderResponses(res Result, model string, named map[string]nsTool) []byte {
|
||||
// as the stream says it (#248)
|
||||
status, incomplete = "incomplete", map[string]any{"reason": "content_filter"}
|
||||
}
|
||||
phaseOutput(output, status == "completed")
|
||||
b, _ := json.Marshal(map[string]any{"id": id, "object": "response", "created_at": time.Now().Unix(), "status": status,
|
||||
"model": model, "output": output, "usage": res.Usage.responses(), "incomplete_details": incomplete,
|
||||
"parallel_tool_calls": true, "tool_choice": "auto", "tools": []any{}, "error": nil})
|
||||
|
||||
Reference in New Issue
Block a user