diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index b55b9160f..da10e2ca2 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -2667,6 +2667,20 @@ included). `previousResponse` in new input with the provider's own id (`prevDelta`), so images aren't uploaded again. A provider that says it doesn't know that id (`prevRefused`) is sent the whole conversation at once. +- A kept turn remembers which provider and key its reply came from + (`made`, any relayed reply, kept upstream or not). A conversation going + on with another one is sent the items magpie brings back without the + ids that name them where they were made (`prevElsewhere`): an item that + may go without its id (`idOptional`) loses it, reasoning stays only + with its `encrypted_content`, and the client's new input is as sent. +- An upstream that says the response or an item belongs to another of + its resources (`prevForeign`: Azure OpenAI behind a relay that spreads + one key over several resources, hykql's report; the text was not + reproduced against Azure) is asked once more with the conversation + whole and those ids taken out. Only a request whose conversation magpie + holds is asked again, and only with a body that differs: an id magpie + doesn't hold, or a refusal with nothing of magpie's to take out, is + passed on as before. - A ChatGPT account's streamed turn goes on its conversation's kept socket as a delta after the backend's own `previous_response_id` (`codexKept`, see [Providers and accounts](providers-accounts.md)). diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 9e4ba8b1e..1702fac91 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -5339,7 +5339,7 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P // a response the request named that magpie doesn't hold goes only to // a provider it is relayed to as written (prev_response.go): Claude's // and the ChatGPT backend's accounts drop it, as a translation does - noteAnswered(r, "") + noteAnswered(r, "", "") if id := prevLost(r); id != "" && p.Account != nil && (p.Account.Agent == "claude" || p.Account.Agent == "codex") { return writePrevNotFound(w, id) } @@ -6485,10 +6485,15 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. } // the new input alone, after the id the provider keeps the previous // response under, when it answered that one (prev_response.go) - sentWhole, delta := body, false + // and when not, the items it brought back without the ids that name + // them where they were made, when that was another provider or key + asSent, sentWhole, delta := body, body, false var remote *remoteTurn if proto == provider.Responses { - body, delta = prevDelta(r, p, body) + sentWhole = prevElsewhere(r, p, body, false) + if body, delta = prevDelta(r, p, body); !delta { + body = sentWhole + } // and to another magpie, which Codex's store false would leave // sent whole each turn: asked to keep it, and sent the input after // the turn it kept last (remote_delta.go) @@ -6520,14 +6525,24 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. } } } - if delta && badRequest(res.StatusCode) || delta && res.StatusCode == http.StatusNotFound { - // one it no longer holds: the conversation whole + if (delta || proto == provider.Responses && prevHeld(r)) && (badRequest(res.StatusCode) || res.StatusCode == http.StatusNotFound) { + // one it no longer holds: the conversation whole; and one another + // of its resources made (prevForeign): the whole, with the items + // magpie brought back naming nothing. Asked again once, and only + // with a body that differs. b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) res.Body.Close() res.Body = io.NopCloser(bytes.NewReader(b)) - if prevRefused(res.StatusCode, b) { - body = sentWhole - if remote != nil { + next := body + switch { + case proto == provider.Responses && prevForeign(res.StatusCode, b): + next = prevElsewhere(r, p, asSent, true) + case delta && prevRefused(res.StatusCode, b): + next = sentWhole + } + if !bytes.Equal(next, body) { + body = next + if delta && remote != nil { remote.refused() } if res, err = s.forward(r.Context(), p, proto, path, p.Prepare(body), r.Header); err != nil { @@ -6535,8 +6550,12 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. } } } - if proto == provider.Responses && prevKeptBy(p) && !storeOff(body) { - noteAnswered(r, prevRoute(p)) + if proto == provider.Responses { + route := "" + if prevKeptBy(p) && !storeOff(body) { + route = prevRoute(p) + } + noteAnswered(r, route, prevRoute(p)) } if res.StatusCode >= 400 && p.PassesErrors() { // the user leaves its errors to the client (errors=pass): the diff --git a/internal/gateway/prev_response.go b/internal/gateway/prev_response.go index 2f7e678fd..d559bfb82 100644 --- a/internal/gateway/prev_response.go +++ b/internal/gateway/prev_response.go @@ -57,6 +57,9 @@ type prevTurn struct { // the provider that keeps it too, if one does: the id it gave it // and which provider and key (prevRoute) upstreamID, route string + // the provider and key whose reply the output is, as relayed + // (prevRoute), kept or not; empty for a translated reply + made string } type prevStore struct { @@ -173,10 +176,12 @@ type prevAsk struct { total, fresh int upstreamID string // the id the provider that answered it keeps it under route string + made string // the route whose reply the named response was // which try answered: its route if it was relayed to a provider - // that keeps what it is sent, empty otherwise - mu sync.Mutex - answered string + // that keeps what it is sent, empty otherwise; and by, its route + // for any relayed try + mu sync.Mutex + answered, by string } type prevAskKey struct{} @@ -186,6 +191,13 @@ func prevAskOf(ctx context.Context) *prevAsk { return a } +// prevHeld is whether the request named a response magpie holds and was +// given its conversation whole. +func prevHeld(r *http.Request) bool { + a := prevAskOf(r.Context()) + return a != nil && a.known +} + // prevLost is the id a request named that magpie doesn't hold, which a // try that doesn't relay it to a provider as written can't honour. func prevLost(r *http.Request) string { @@ -202,10 +214,12 @@ func writePrevNotFound(w http.ResponseWriter, id string) (int, string) { } // noteAnswered is called by each try: the last is the one that answered. -func noteAnswered(r *http.Request, route string) { +// route is the provider and key if it keeps what it is sent, by the +// provider and key a relayed try went to (both empty for a translation). +func noteAnswered(r *http.Request, route, by string) { if a := prevAskOf(r.Context()); a != nil { a.mu.Lock() - a.answered = route + a.answered, a.by = route, by a.mu.Unlock() } } @@ -231,7 +245,7 @@ func previousResponse(w http.ResponseWriter, r *http.Request, from provider.Prot ask.id = id if t, ok := prevResponses.get(prevKey{scope, id}); ok { prior = t.items - ask.known, ask.upstreamID, ask.route = true, t.upstreamID, t.route + ask.known, ask.upstreamID, ask.route, ask.made = true, t.upstreamID, t.route, t.made } } } @@ -303,6 +317,7 @@ func previousResponse(w http.ResponseWriter, r *http.Request, from provider.Prot if ask.answered != "" { t.upstreamID, t.route = id, ask.answered } + t.made = ask.by ask.mu.Unlock() prevResponses.put(t) } @@ -433,6 +448,96 @@ func prevRefused(status int, b []byte) bool { return strings.Contains(s, "previous_response") || strings.Contains(s, "previousresponse") } +// prevForeign is an upstream's refusal of an item, or the response named, +// that another of its resources made: Azure OpenAI's, behind a relay that +// spreads one key over several resources (hykql on Discord: "The +// requested item was created under a different Azure OpenAI resource. Use +// the same resource that created the item to access it."). The text is +// the report's; it was not reproduced against Azure itself. +func prevForeign(status int, b []byte) bool { + if !badRequest(status) && status != http.StatusNotFound { + return false + } + s := strings.ToLower(string(b)) + return strings.Contains(s, "created under a different") && strings.Contains(s, "resource") +} + +// prevElsewhere is body, a Responses request magpie gave its conversation +// whole, with the items it brought back no longer naming what the +// upstream that made them keeps them under, when they go to another +// provider or key than the one whose reply they were (or always, when +// force: one upstream said they are another resource's). An item that +// can go without its id (idOptional) goes without it, its text and +// call_id kept; reasoning keeps its place only with its encrypted_content, +// as Codex sends it, since what it held lives only where it was made. Any +// other kind, and the client's own new input, stay as they were. A body +// whose items the tries changed in number is left as it is, as prevDelta +// leaves it. +func prevElsewhere(r *http.Request, p provider.Provider, body []byte, force bool) []byte { + a := prevAskOf(r.Context()) + if a == nil || !a.known || !force && a.made == prevRoute(p) { + return body + } + n := a.total - a.fresh + if n <= 0 || !bytes.Contains(body, []byte(`"id"`)) { + return body + } + var q map[string]json.RawMessage + if decodeJSONView(body, &q) != nil { + return body + } + items, ok := inputList(q["input"]) + if !ok || len(items) != a.total { + return body + } + out := make([]json.RawMessage, 0, len(items)) + changed := false + for i, raw := range items { + var it map[string]json.RawMessage + if i >= n || json.Unmarshal(raw, &it) != nil { + out = append(out, raw) + continue + } + if _, has := it["id"]; !has { + out = append(out, raw) + continue + } + var typ string + json.Unmarshal(it["type"], &typ) + switch { + case typ == "reasoning" && gjson.GetBytes(raw, "encrypted_content").String() == "": + changed = true + continue + case typ == "reasoning" || idOptional[typ]: + delete(it, "id") + b, err := marshalPlain(it) + if err != nil { + return body + } + out, changed = append(out, b), true + default: + out = append(out, raw) + } + } + if !changed { + return body + } + in, err := marshalPlain(out) + if err != nil { + return body + } + m := make(map[string]json.RawMessage, len(q)) + for k, v := range q { + m[k] = v + } + m["input"] = in + nb, err := marshalPlain(m) + if err != nil { + return body + } + return nb +} + // storeOff is whether a Responses body says store false. func storeOff(body []byte) bool { v := gjson.GetBytes(body, "store") diff --git a/internal/gateway/prev_response_test.go b/internal/gateway/prev_response_test.go index b0ec79238..426b4689b 100644 --- a/internal/gateway/prev_response_test.go +++ b/internal/gateway/prev_response_test.go @@ -292,3 +292,110 @@ func TestKeptTurnOwnsItsInput(t *testing.T) { t.Fatalf("own %d, want the %d bytes kept", kept.own, n) } } + +// foreignUp is an upstream that, once foreign is set, turns away a +// previous_response_id or an input item id another of its resources made, +// as Azure OpenAI behind a relay spreading one key over several resources +// does (hykql on Discord), and answers each turn with reasoning and a +// message that carry ids. +func foreignUp(t *testing.T, foreign *atomic.Bool) *prevUp { + return newPrevUp(t, func(n int, body []byte) (int, string, string) { + s := string(body) + if foreign.Load() && (strings.Contains(s, "previous_response_id") || strings.Contains(s, `"id":"msg_`) || strings.Contains(s, `"id":"rs_`)) { + return 400, "application/json", `{"error":{"message":"The requested item was created under a different Azure OpenAI resource. Use the same resource that created the item to access it.","type":"invalid_request_error"}}` + } + return 200, "application/json", fmt.Sprintf(`{"id":"resp_up%d","object":"response","status":"completed","output":[{"type":"reasoning","id":"rs_%d","summary":[]},{"type":"reasoning","id":"rs_e%d","summary":[],"encrypted_content":"sealed%d"},{"type":"message","id":"msg_%d","role":"assistant","content":[{"type":"output_text","text":"answer %d"}]}],"usage":{"input_tokens":3,"output_tokens":1}}`, n, n, n, n, n, n) + }) +} + +// wholeWithoutIDs fails unless q, a request's body, is the conversation +// whole with none of the earlier reply's ids, its sealed reasoning kept. +func wholeWithoutIDs(t *testing.T, q map[string]any) { + t.Helper() + in, _ := json.Marshal(q["input"]) + s := string(in) + if _, has := q["previous_response_id"]; has { + t.Fatalf("previous_response_id still sent: %.400s", s) + } + if strings.Contains(s, `"id":"msg_`) || strings.Contains(s, `"id":"rs_`) { + t.Fatalf("the earlier reply's ids still sent: %.400s", s) + } + for _, want := range []string{"first turn", "answer 1", "sealed1", "second turn"} { + if !strings.Contains(s, want) { + t.Fatalf("%q missing from the whole: %.400s", want, s) + } + } +} + +// An upstream that keeps responses, behind which another resource +// answers: the delta naming the earlier response is turned away as +// another resource's, and the conversation goes whole, its items naming +// nothing, rather than the 400 reaching the client. +func TestPreviousResponseOtherResourceDeltaSentWhole(t *testing.T) { + defer func(old func(provider.Provider) bool) { prevKeptBy = old }(prevKeptBy) + prevKeptBy = func(p provider.Provider) bool { return p.ID == "fake" } + var foreign atomic.Bool + up := foreignUp(t, &foreign) + s := prevSandbox(t, provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Responses: up.srv.URL + "/v1"}) + id := responseID(t, askResponses(t, s, "", `{"model":"fake/m1","input":"first turn"}`)) + foreign.Store(true) + rec := askResponses(t, s, "", `{"model":"fake/m1","previous_response_id":"`+id+`","input":"second turn"}`) + if rec.Code != 200 { + t.Fatalf("client given %d: %s", rec.Code, rec.Body.String()) + } + if n := up.calls(); n != 3 { + t.Fatalf("%d upstream calls, want the delta and the whole once", n) + } + wholeWithoutIDs(t, up.last()) +} + +// The same behind a provider that doesn't keep responses, sent the whole +// each turn: the items magpie brought back are what is turned away, and +// they go once more without their ids. A refusal with nothing left to +// take out is passed on, not asked again as it was. +func TestPreviousResponseOtherResourceWholeSentWithoutIDs(t *testing.T) { + defer func(old func(provider.Provider) bool) { prevKeptBy = old }(prevKeptBy) + prevKeptBy = func(provider.Provider) bool { return false } + var foreign atomic.Bool + up := foreignUp(t, &foreign) + s := prevSandbox(t, provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Responses: up.srv.URL + "/v1"}) + id := responseID(t, askResponses(t, s, "", `{"model":"fake/m1","input":"first turn"}`)) + foreign.Store(true) + rec := askResponses(t, s, "", `{"model":"fake/m1","previous_response_id":"`+id+`","input":"second turn"}`) + if rec.Code != 200 { + t.Fatalf("client given %d: %s", rec.Code, rec.Body.String()) + } + if n := up.calls(); n != 3 { + t.Fatalf("%d upstream calls, want the whole and the whole without ids", n) + } + wholeWithoutIDs(t, up.last()) + + // the client's own item with an id: nothing of magpie's to take out + rec = askResponses(t, s, "", `{"model":"fake/m1","input":[{"type":"message","id":"msg_mine","role":"user","content":"hi"}]}`) + if rec.Code != 400 || up.calls() != 4 { + t.Fatalf("client given %d after %d calls, want the 400 after one", rec.Code, up.calls()-3) + } +} + +// A conversation going on with another provider than the one whose reply +// it holds goes without that reply's ids at once: the other never made +// them. The same provider and key is sent them as before. +func TestPreviousResponseToAnotherProviderSentWithoutIDs(t *testing.T) { + var foreign atomic.Bool + up := foreignUp(t, &foreign) + other := foreignUp(t, &foreign) + s := prevSandbox(t, provider.Provider{ID: "fake", Name: "Fake", Key: "k", Models: []string{"m1"}, Responses: up.srv.URL + "/v1"}) + if err := provider.Save(provider.Provider{ID: "other", Name: "Other", Key: "k2", Models: []string{"m1"}, Responses: other.srv.URL + "/v1"}); err != nil { + t.Fatal(err) + } + id := responseID(t, askResponses(t, s, "", `{"model":"fake/m1","input":"first turn"}`)) + id = responseID(t, askResponses(t, s, "", `{"model":"fake/m1","previous_response_id":"`+id+`","input":"again"}`)) + if in, _ := json.Marshal(up.last()["input"]); !strings.Contains(string(in), `"id":"msg_1"`) { + t.Fatalf("the provider that made them not sent its own ids: %.400s", in) + } + responseID(t, askResponses(t, s, "", `{"model":"other/m1","previous_response_id":"`+id+`","input":"second turn"}`)) + if n := other.calls(); n != 1 { + t.Fatalf("%d calls to the other provider, want one", n) + } + wholeWithoutIDs(t, other.last()) +}