gateway: a relayed citation without the offsets OpenAI's schema wants is dropped, the thread healed (#4921)
A thread a routing group served once on Volcengine Ark (or another vendor whose Responses endpoint writes its url_citations with no start_index/end_index) never worked on a codex member again: magpie relayed the reply's annotations as they came, Codex stored them, and the ChatGPT backend refused every later replay of the history whole — "Missing required parameter: 'input[221].content[0].annotations[0]. start_index'" — five retries a turn, on any codex member, through any upgrade (#4921, the reporter's routing log and rollout). This is #2855's defect with a different field: what magpie hands a client must be something magpie could send again. Such an annotation goes, at both seams, as the reasoning-item fix did: - a whole reply streamed as the vendor's own events (responsesWholeEvents) drops it in every place a client reads a citation: its annotation events, the content part, the item and the reply the client keeps (dropOffsetlessCitations); - the history Codex replays loses it on its way to the ChatGPT backend (withoutOffsetlessCitations, the same leaving-out as a reasoning item's text, #1411): to the backend by its own sign-in and compaction relay (codexUpstreamOn), to it as a group member or an openai.com or Azure upstream (the provider loop, beside withoutReasoningText), and asked again without it where a relay in front of it names the parameter (refusesCitationOffsets), marked so it is never sent one again — a thread already poisoned heals on its next turn, no new thread needed. The text, and a citation that carries its offsets, go as the vendor wrote them; a turn with no "annotations" in it is not decoded (anyInputItem scan, itemCitesWithoutOffsets; the undecoded-turn test holds, allocations and all). Run: the three new tests fail on the base with the reporter's exact 400 and pass here (ablation: the tidy call and the rewrite's body neutralized, tests kept); TestCodexRewritesAsBefore, TestCodexRewritesLeaveTurnUndecoded and the fuzz hold the rewrite to its scan; the citation/whole/reasoning neighborhood ok (23s); gofmt, go vet (linux, windows) and go build -tags nogui clean. Review: this is skygunner's version of the fix (fcea11649), not ggbdpq's 57dc7b420. ggbdpq's stripped citations only for a request that wasn't for a magpie model, so the reporter's own path (a routing group's codex member, the history passed through) kept the bad annotation. ggbdpq's parity table and verification of the report were used to check this one. Changed in review: annotationLacksOffsets looks only at url_citation and container_file_citation, the two types OpenAI's schema gives start_index and end_index. file_citation and file_path carry a single index, so the patch dropped every one of them as "offsetless". TestCitationsWithOneIndexKept (added in review) holds both kinds and checks that a history with only file_citations is sent byte for byte. Broken by hand at the reviewed head: annotationLacksOffsets made to return false, all four citation tests red; the type check removed, TestCitationsWithOneIndexKept red. Restored, green. Run at the pushed tree (this stack of nine on origin/main3c2dceb34), on mote (macOS arm64, Go 1.26.8): - go test -count=1 -timeout 45m ./internal/catalog/... ./internal/plugin/... ./internal/davsync/... ./internal/gateway/...: catalog, plugin and davsync ok; gateway red on one test only, TestCodexPoolSaysTheClientsVersion, the open #4807 (another test's Codex identity reaches it in a full package run). It passes run alone at this tree, 3 of 3. - go vet ./... (darwin); GOOS=linux and GOOS=windows go vet -tags nogui ./...: ok. gofmt -l on every tracked .go file: clean. - The hand breaks above ran on this stack before its rebase onto3c2dceb34. That commit changed member.go only, nothing these tests reach. Not tried: the GUI suite, since no GUI file changed. Windows and Linux test runs (the Claude bridge tests use a shell fake and skip on Windows). No real vendor, Claude Code or network was used; every case runs against fakes.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -0,0 +1,242 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// citationsStrict stands in for the ChatGPT backend, and a relay in front
|
||||
// of it, as they check a replayed citation (#4921): an output_text
|
||||
// annotation without both of the offsets OpenAI's schema wants is turned
|
||||
// away naming the parameter, as Volcengine Ark's answer — its url_citations
|
||||
// carry no start_index/end_index — came back when Codex replayed it:
|
||||
// "Invalid response.create payload: Missing required parameter:
|
||||
// 'input[n].content[m].annotations[k].start_index'."
|
||||
type citationsStrict struct {
|
||||
mu sync.Mutex
|
||||
inputs [][]map[string]any
|
||||
}
|
||||
|
||||
func (u *citationsStrict) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
if strings.HasSuffix(r.URL.Path, "/models") {
|
||||
io.WriteString(w, `{"models":[{"slug":"gpt-6.1-sol","visibility":"list"}]}`)
|
||||
return
|
||||
}
|
||||
var q struct {
|
||||
Input []map[string]any `json:"input"`
|
||||
}
|
||||
json.Unmarshal(b, &q)
|
||||
u.mu.Lock()
|
||||
u.inputs = append(u.inputs, q.Input)
|
||||
u.mu.Unlock()
|
||||
for i, it := range q.Input {
|
||||
content, _ := it["content"].([]any)
|
||||
for ci, raw := range content {
|
||||
part, _ := raw.(map[string]any)
|
||||
notes, _ := part["annotations"].([]any)
|
||||
for ai, raw := range notes {
|
||||
note, _ := raw.(map[string]any)
|
||||
if note["start_index"] != nil && note["end_index"] != nil {
|
||||
continue
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
fmt.Fprintf(w, `{"error":{"message":"Invalid response.create payload: Missing required parameter: 'input[%d].content[%d].annotations[%d].start_index'.","type":"invalid_request_error","param":"input[%d].content[%d].annotations[%d].start_index","code":"missing_required_parameter"}}`, i, ci, ai, i, ci, ai)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, sse(
|
||||
`data: {"type":"response.created","response":{"id":"resp_1","status":"in_progress"}}`,
|
||||
`data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"m1","role":"assistant","content":[{"type":"output_text","text":"DONE"}]}}`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":2}}}`))
|
||||
}
|
||||
|
||||
func (u *citationsStrict) asked() [][]map[string]any {
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
return append([][]map[string]any(nil), u.inputs...)
|
||||
}
|
||||
|
||||
// citationCounts is how many annotations an input's message items carry
|
||||
// with and without their offsets.
|
||||
func citationCounts(input []map[string]any) (with, without int) {
|
||||
for _, it := range input {
|
||||
content, _ := it["content"].([]any)
|
||||
for _, raw := range content {
|
||||
part, _ := raw.(map[string]any)
|
||||
notes, _ := part["annotations"].([]any)
|
||||
for _, raw := range notes {
|
||||
note, _ := raw.(map[string]any)
|
||||
if note["start_index"] == nil || note["end_index"] == nil {
|
||||
without++
|
||||
} else {
|
||||
with++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return with, without
|
||||
}
|
||||
|
||||
// arkCitedTurn is a Codex conversation a routing group served once on
|
||||
// Volcengine Ark (#4921): its answer's first citation carries the shape
|
||||
// Ark writes — url_citation with no offsets — as Codex stored it, beside a
|
||||
// citation with its offsets and plain turns.
|
||||
func arkCitedTurn(model string) string {
|
||||
return `{"model":"` + model + `","stream":true,"store":false,"include":["reasoning.encrypted_content"],"input":[` +
|
||||
`{"type":"message","role":"user","content":[{"type":"input_text","text":"what changed in go 1.27?"}]},` +
|
||||
`{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Go 1.27.2 shipped, on go.dev.","annotations":[` +
|
||||
`{"type":"url_citation","url":"https://go.dev/doc/devel/release","title":"Release History","site_name":"go.dev","publish_time":"2026-10-08","summary":"Go 1.27.2 released October 8."},` +
|
||||
`{"type":"url_citation","start_index":25,"end_index":31,"url":"https://go.dev","title":"go.dev"}]}]},` +
|
||||
`{"type":"message","role":"user","content":[{"type":"input_text","text":"and 1.26?"}]}]}`
|
||||
}
|
||||
|
||||
// #4921: a citation another vendor's Responses reply wrote without the
|
||||
// offsets OpenAI's schema wants turned every later turn of the thread away
|
||||
// where that schema holds. Asked again without it — everything else, the
|
||||
// citation that carries its offsets included, kept — and never sent one
|
||||
// again.
|
||||
func TestCitationsWithoutOffsetsAskedAgainWithout(t *testing.T) {
|
||||
fresh(t)
|
||||
u := &citationsStrict{}
|
||||
srv := httptest.NewServer(u)
|
||||
t.Cleanup(srv.Close)
|
||||
if err := provider.Save(provider.Provider{ID: "ar", Name: "AgentRouter", Key: "k", Models: []string{"gpt-6-luna"}, Responses: srv.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := provider.SaveGroup(provider.Group{ID: "medium", Name: "Medium", Members: []string{"ar/gpt-6-luna"}, Routing: provider.Ordered}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New()
|
||||
rec := codexPostTo(s, arkCitedTurn("group/medium"))
|
||||
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "DONE") && !strings.Contains(rec.Body.String(), "RE9ORQ") {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body)
|
||||
}
|
||||
got := u.asked()
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("asked the relay %d times, want again once after its 400: %v", len(got), got)
|
||||
}
|
||||
if with, without := citationCounts(got[0]); without != 1 || with != 1 {
|
||||
t.Fatalf("first ask: %d citations with offsets, %d without", with, without)
|
||||
}
|
||||
if with, without := citationCounts(got[1]); without != 0 || with != 1 {
|
||||
t.Fatalf("asked again: %d citations with offsets, %d without", with, without)
|
||||
}
|
||||
for _, k := range []string{"message"} {
|
||||
before, after := kinds(got[0])[k], kinds(got[1])[k]
|
||||
if after == 0 || after != before {
|
||||
t.Errorf("%s: %d asked again, %d first", k, after, before)
|
||||
}
|
||||
}
|
||||
|
||||
// the next turn goes without it at once
|
||||
rec = codexPostTo(s, arkCitedTurn("group/medium"))
|
||||
if gotNow := u.asked(); rec.Code != 200 || len(gotNow) != 3 {
|
||||
t.Fatalf("again: %d, %d asks", rec.Code, len(gotNow))
|
||||
} else if with, without := citationCounts(gotNow[2]); without != 0 || with != 1 {
|
||||
t.Fatalf("asked at once: %d citations with offsets, %d without", with, without)
|
||||
}
|
||||
}
|
||||
|
||||
// The ChatGPT backend a group's codex member answers on is never sent the
|
||||
// citation: asked once, the citation with its offsets kept, the text kept.
|
||||
func TestCitationsWithoutOffsetsNotSentToCodexBackend(t *testing.T) {
|
||||
fresh(t)
|
||||
home := os.Getenv("HOME")
|
||||
claims := func(m map[string]any) string {
|
||||
b, _ := json.Marshal(m)
|
||||
return "h." + base64.RawURLEncoding.EncodeToString(b) + ".s"
|
||||
}
|
||||
os.MkdirAll(filepath.Join(home, ".codex"), 0o755)
|
||||
os.WriteFile(filepath.Join(home, ".codex", "auth.json"), mustJSON(map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{
|
||||
"id_token": claims(map[string]any{"email": "me@example.com"}),
|
||||
"access_token": claims(map[string]any{"exp": time.Now().Add(time.Hour).Unix()}),
|
||||
"refresh_token": "r", "account_id": "acct-1"}}), 0o600)
|
||||
provider.ForgetAccounts()
|
||||
t.Cleanup(provider.ForgetAccounts)
|
||||
u := &citationsStrict{}
|
||||
srv := httptest.NewServer(u)
|
||||
t.Cleanup(srv.Close)
|
||||
was := provider.CodexBase
|
||||
provider.CodexBase = srv.URL + "/backend-api/codex"
|
||||
t.Cleanup(func() { provider.CodexBase = was })
|
||||
if err := provider.SaveGroup(provider.Group{ID: "medium", Name: "Medium", Members: []string{"codex/gpt-6.1-sol"}, Routing: provider.Ordered}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New()
|
||||
rec := codexPostTo(s, arkCitedTurn("group/medium"))
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body)
|
||||
}
|
||||
got := u.asked()
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("the ChatGPT backend was asked %d times: %v", len(got), got)
|
||||
}
|
||||
if with, without := citationCounts(got[0]); without != 0 || with != 1 || kinds(got[0])["message"] != 3 {
|
||||
t.Fatalf("asked with %d citations with offsets, %d without: %v", with, without, got[0])
|
||||
}
|
||||
|
||||
// and on Codex's own sign-in alike
|
||||
u2 := &citationsStrict{}
|
||||
srv2 := httptest.NewServer(u2)
|
||||
t.Cleanup(srv2.Close)
|
||||
provider.CodexBase = srv2.URL + "/backend-api/codex"
|
||||
rec = codexPostTo(s, arkCitedTurn("gpt-6.1-sol"))
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("own sign-in: %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if got := u2.asked(); len(got) != 1 {
|
||||
t.Fatalf("the backend was asked %d times on Codex's own sign-in: %v", len(got), got)
|
||||
} else if with, without := citationCounts(got[0]); without != 0 || with != 1 {
|
||||
t.Fatalf("own sign-in asked with %d citations with offsets, %d without", with, without)
|
||||
}
|
||||
}
|
||||
|
||||
// Only the kinds of annotation OpenAI's schema wants a start and end
|
||||
// index of are dropped without them: a file_citation or file_path names
|
||||
// its place by a single index, as OpenAI's own file search writes it, and
|
||||
// goes back to the ChatGPT backend as it came.
|
||||
func TestCitationsWithOneIndexKept(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
note string
|
||||
drop bool
|
||||
}{
|
||||
{`{"type":"url_citation","url":"https://go.dev","title":"go.dev"}`, true},
|
||||
{`{"type":"url_citation","start_index":null,"end_index":3,"url":"https://go.dev","title":"go.dev"}`, true},
|
||||
{`{"type":"container_file_citation","container_id":"cntr_1","file_id":"cfile_1","filename":"a.csv"}`, true},
|
||||
{`{"type":"url_citation","start_index":0,"end_index":3,"url":"https://go.dev","title":"go.dev"}`, false},
|
||||
{`{"type":"file_citation","file_id":"file-1","filename":"notes.md","index":12}`, false},
|
||||
{`{"type":"file_path","file_id":"file-2","index":4}`, false},
|
||||
} {
|
||||
if got := annotationLacksOffsets(json.RawMessage(c.note)); got != c.drop {
|
||||
t.Errorf("%s: dropped %v, want %v", c.note, got, c.drop)
|
||||
}
|
||||
}
|
||||
body := `{"model":"gpt-6.1","input":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"See notes.md.","annotations":[` +
|
||||
`{"type":"file_citation","file_id":"file-1","filename":"notes.md","index":12},` +
|
||||
`{"type":"url_citation","url":"https://go.dev","title":"go.dev"}]}]}]}`
|
||||
got := string(withoutOffsetlessCitations([]byte(body)))
|
||||
if !strings.Contains(got, `"file_citation"`) || strings.Contains(got, `"url_citation"`) {
|
||||
t.Fatalf("the file citation went, or the offsetless url citation stayed:\n%s", got)
|
||||
}
|
||||
only := `{"model":"gpt-6.1","input":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"See notes.md.","annotations":[` +
|
||||
`{"type":"file_citation","file_id":"file-1","filename":"notes.md","index":12}]}]}]}`
|
||||
if got := string(withoutOffsetlessCitations([]byte(only))); got != only {
|
||||
t.Fatalf("a history whose citations all name their place was rewritten:\n%s", got)
|
||||
}
|
||||
}
|
||||
@@ -980,6 +980,11 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
// provider's model wrote it) turned every turn and compaction
|
||||
// away, as on an account's (provider.CodexToolNames, wing3556)
|
||||
body = provider.CodexToolNames(body)
|
||||
// and a citation without the offsets the backend's schema wants,
|
||||
// another vendor's Responses reply's (Volcengine Ark's
|
||||
// url_citation) as Codex stored it, turned them away alike
|
||||
// (#4921)
|
||||
body = withoutOffsetlessCitations(body)
|
||||
}
|
||||
u := base + rest
|
||||
if r.URL.RawQuery != "" {
|
||||
@@ -2804,6 +2809,119 @@ func withoutReasoningText(body []byte) []byte {
|
||||
return b
|
||||
}
|
||||
|
||||
// citationOffsetRefused is how unfit remembers a provider turning away,
|
||||
// for model, a citation without the offsets OpenAI's schema wants
|
||||
// (withoutOffsetlessCitations).
|
||||
func citationOffsetRefused(model string) string { return "citation offsets\x00" + model }
|
||||
|
||||
// citationOffsetRefusal is the ChatGPT backend's refusal of an annotation
|
||||
// the offsets its schema wants are missing from, as a relay in front of
|
||||
// it passes it on: "Invalid response.create payload: Missing required
|
||||
// parameter: 'input[221].content[0].annotations[0].start_index'."
|
||||
// (#4921)
|
||||
var citationOffsetRefusal = regexp.MustCompile(`input\[\d+\]\.content\[\d+\]\.annotations\[\d+\]\.(?:start|end)_index`)
|
||||
|
||||
// refusesCitationOffsets is a 400 refusing a Responses request over a
|
||||
// citation that lacks the offsets OpenAI's schema wants.
|
||||
func refusesCitationOffsets(status int, b []byte) bool {
|
||||
return badRequest(status) && citationOffsetRefusal.Match(b)
|
||||
}
|
||||
|
||||
// withoutOffsetlessCitations is a Responses request without the
|
||||
// output_text annotations that lack the offsets OpenAI's schema wants on
|
||||
// every one, as another vendor's Responses reply wrote them (Volcengine
|
||||
// Ark's url_citation, #4921): Codex stored the reply magpie relayed, and
|
||||
// where that schema holds — the ChatGPT backend, OpenAI's API, a relay in
|
||||
// front of them — the replay was refused whole, every turn of the thread
|
||||
// with it. Such an annotation goes; the text, and a citation with its
|
||||
// offsets, stay as they came.
|
||||
func withoutOffsetlessCitations(body []byte) []byte {
|
||||
if !bytes.Contains(body, []byte(`"annotations"`)) || !anyInputItem(body, itemCitesWithoutOffsets) {
|
||||
return body
|
||||
}
|
||||
q, err := rawObject(body)
|
||||
if err != nil {
|
||||
return body
|
||||
}
|
||||
items, err := rawArray(q["input"])
|
||||
if err != nil {
|
||||
return body
|
||||
}
|
||||
changed := false
|
||||
for i, raw := range items {
|
||||
if !itemCitesWithoutOffsets(raw) {
|
||||
continue
|
||||
}
|
||||
it, err := rawObject(raw)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
parts, err := rawArray(it["content"])
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
itemChanged := false
|
||||
for j, p := range parts {
|
||||
part, err := rawObject(p)
|
||||
if err != nil || string(part["type"]) != `"output_text"` {
|
||||
continue
|
||||
}
|
||||
notes := elementsOf(part["annotations"])
|
||||
if notes == nil {
|
||||
continue
|
||||
}
|
||||
kept := notes[:0]
|
||||
dropped := false
|
||||
for _, a := range notes {
|
||||
if annotationLacksOffsets(a) {
|
||||
dropped = true
|
||||
continue
|
||||
}
|
||||
kept = append(kept, a)
|
||||
}
|
||||
if dropped {
|
||||
part["annotations"], _ = marshalPlain(kept)
|
||||
parts[j], _ = marshalPlain(part)
|
||||
itemChanged = true
|
||||
}
|
||||
}
|
||||
if itemChanged {
|
||||
it["content"], _ = marshalPlain(parts)
|
||||
items[i], _ = marshalPlain(it)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return body
|
||||
}
|
||||
q["input"], _ = marshalPlain(items)
|
||||
nb, err := marshalPlain(q)
|
||||
if err != nil {
|
||||
return body
|
||||
}
|
||||
return nb
|
||||
}
|
||||
|
||||
// itemCitesWithoutOffsets is whether it, an input item, carries an
|
||||
// output_text annotation without the offsets OpenAI's schema wants, read
|
||||
// as the scan reads it, without decoding the conversation.
|
||||
func itemCitesWithoutOffsets(it []byte) bool {
|
||||
if !bytes.Contains(it, []byte(`"annotations"`)) {
|
||||
return false
|
||||
}
|
||||
for _, part := range elementsOf(memberOrNil(it, "content")) {
|
||||
if typ, _ := stringBytes(memberOrNil(part, "type")); string(typ) != "output_text" {
|
||||
continue
|
||||
}
|
||||
for _, a := range elementsOf(memberOrNil(part, "annotations")) {
|
||||
if annotationLacksOffsets(a) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// openaiItemPrefix is the id prefix OpenAI takes for each kind of call item
|
||||
// a vendor's reply may have handed Codex with another: magpie, or the
|
||||
// vendor, gave a tool search's and a custom tool's call a function_call's
|
||||
|
||||
@@ -55,6 +55,7 @@ var codexRewrites = func() []codexRewrite {
|
||||
{"plainItemIDs", plainItemIDs, wasPlainItemIDs},
|
||||
{"withoutBareReasoning", withoutBareReasoning, wasWithoutBareReasoning},
|
||||
{"withoutReasoningText", withoutReasoningText, wasWithoutReasoningText},
|
||||
{"withoutOffsetlessCitations", withoutOffsetlessCitations, wasWithoutOffsetlessCitations},
|
||||
{"withModel", func(b []byte) []byte { return withModel(b, "gpt-5.5<&>") }, func(b []byte) []byte {
|
||||
if string(trimJSON(b)) == "null" {
|
||||
return b // was a panic
|
||||
@@ -144,6 +145,38 @@ var codexMarks = []func(it map[string]any){
|
||||
it["type"] = "reasoning"
|
||||
it["content"] = []any{map[string]any{"type": "reasoning_text", "text": "t"}}
|
||||
},
|
||||
// a reply another vendor's Responses endpoint wrote, its citation
|
||||
// without the offsets OpenAI's schema wants (#4921), beside one with
|
||||
// them
|
||||
func(it map[string]any) {
|
||||
it["type"] = "message"
|
||||
it["role"] = "assistant"
|
||||
it["content"] = []any{map[string]any{"type": "output_text", "text": "t", "annotations": []any{
|
||||
map[string]any{"type": "url_citation", "url": "https://a", "title": "A"},
|
||||
map[string]any{"type": "url_citation", "start_index": 0, "end_index": 1, "url": "https://b"},
|
||||
}}}
|
||||
},
|
||||
func(it map[string]any) {
|
||||
it["type"] = "message"
|
||||
it["content"] = "text"
|
||||
},
|
||||
func(it map[string]any) {
|
||||
it["type"] = "message"
|
||||
it["content"] = []any{map[string]any{"type": "output_text", "text": "t", "annotations": []any{
|
||||
map[string]any{"type": "url_citation", "start_index": nil, "end_index": 2},
|
||||
}}}
|
||||
},
|
||||
func(it map[string]any) {
|
||||
it["type"] = "message"
|
||||
it["content"] = []any{map[string]any{"type": "input_text", "text": "t", "annotations": []any{
|
||||
map[string]any{"type": "url_citation", "url": "https://a"},
|
||||
}}}
|
||||
},
|
||||
func(it map[string]any) {
|
||||
it["content"] = []any{map[string]any{"type": "output_text", "text": "t", "annotations": []any{
|
||||
map[string]any{"type": "url_citation", "url": "https://a"},
|
||||
}}}
|
||||
},
|
||||
func(it map[string]any) { it["type"] = "reasoning"; it["content"] = nil },
|
||||
func(it map[string]any) { it["type"] = "reasoning"; it["content"] = "text" },
|
||||
func(it map[string]any) { it["type"] = "reasoning"; it["content"] = map[string]any{} },
|
||||
@@ -441,6 +474,70 @@ func wasWithoutReasoningText(body []byte) []byte {
|
||||
return b
|
||||
}
|
||||
|
||||
func wasWithoutOffsetlessCitations(body []byte) []byte {
|
||||
if !bytes.Contains(body, []byte(`"annotations"`)) {
|
||||
return body
|
||||
}
|
||||
var q map[string]json.RawMessage
|
||||
if json.Unmarshal(body, &q) != nil {
|
||||
return body
|
||||
}
|
||||
var items []json.RawMessage
|
||||
if json.Unmarshal(q["input"], &items) != nil {
|
||||
return body
|
||||
}
|
||||
changed := false
|
||||
for i, raw := range items {
|
||||
var it map[string]json.RawMessage
|
||||
if json.Unmarshal(raw, &it) != nil {
|
||||
continue
|
||||
}
|
||||
var parts []json.RawMessage
|
||||
if json.Unmarshal(it["content"], &parts) != nil {
|
||||
continue
|
||||
}
|
||||
itemChanged := false
|
||||
for j, p := range parts {
|
||||
var part map[string]json.RawMessage
|
||||
if json.Unmarshal(p, &part) != nil || string(part["type"]) != `"output_text"` {
|
||||
continue
|
||||
}
|
||||
var notes []json.RawMessage
|
||||
if json.Unmarshal(part["annotations"], ¬es) != nil {
|
||||
continue
|
||||
}
|
||||
kept := notes[:0:0]
|
||||
dropped := false
|
||||
for _, a := range notes {
|
||||
if annotationLacksOffsets(a) {
|
||||
dropped = true
|
||||
continue
|
||||
}
|
||||
kept = append(kept, a)
|
||||
}
|
||||
if dropped {
|
||||
part["annotations"], _ = wasMarshalPlain(kept)
|
||||
parts[j], _ = wasMarshalPlain(part)
|
||||
itemChanged = true
|
||||
}
|
||||
}
|
||||
if itemChanged {
|
||||
it["content"], _ = wasMarshalPlain(parts)
|
||||
items[i], _ = wasMarshalPlain(it)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return body
|
||||
}
|
||||
q["input"], _ = wasMarshalPlain(items)
|
||||
nb, err := wasMarshalPlain(q)
|
||||
if err != nil {
|
||||
return body
|
||||
}
|
||||
return nb
|
||||
}
|
||||
|
||||
func wasCallItemIDs(body []byte) []byte {
|
||||
if !bytes.Contains(body, []byte(`"tool_search_call"`)) && !bytes.Contains(body, []byte(`"custom_tool_call"`)) {
|
||||
return body
|
||||
|
||||
@@ -5517,6 +5517,14 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
// that has turned it away before (#1411)
|
||||
body = withoutReasoningText(body)
|
||||
}
|
||||
if strings.HasSuffix(p.Host(), "openai.com") || p.IsAzure() || p.Account != nil && p.Account.Agent == "codex" || !s.fits(p.ID, citationOffsetRefused(model), proto) {
|
||||
// a citation another vendor's reply wrote without the
|
||||
// offsets OpenAI's schema wants (Volcengine Ark's
|
||||
// url_citation, #4921), which the ChatGPT backend
|
||||
// refuses the whole replay over, nor does an upstream
|
||||
// that has turned one away before
|
||||
body = withoutOffsetlessCitations(body)
|
||||
}
|
||||
}
|
||||
// Relays enforce OpenAI's item ID prefixes too, including during
|
||||
// compaction. call_id stays unchanged so tool outputs remain paired.
|
||||
@@ -5923,6 +5931,21 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
continue
|
||||
}
|
||||
}
|
||||
if len(fs) == 0 && len(ms) == 0 && proto == provider.Responses && refusesCitationOffsets(res.StatusCode, b) {
|
||||
// and a citation without the offsets OpenAI's schema wants,
|
||||
// which the ChatGPT backend and the relays in front of it
|
||||
// turn the whole replay away over ("Missing required
|
||||
// parameter: 'input[n].content[m].annotations[k].start_index'",
|
||||
// #4921): asked once more without it, and not sent one again
|
||||
if nb := withoutOffsetlessCitations(body); !bytes.Equal(nb, body) {
|
||||
refused = append(refused, citationOffsetRefused(model))
|
||||
body = nb
|
||||
if res, err = s.forward(r.Context(), p, proto, path, p.Prepare(body), r.Header); err != nil {
|
||||
return writeError(w, proto, 502, p.Name+": "+err.Error()), err.Error(), true
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
if len(fs) == 0 && len(ms) == 0 && proto == provider.Responses && itemIDRefusal.Match(b) {
|
||||
// and an input item's id with a character OpenAI's don't
|
||||
// have, which a relay in front of OpenAI turns away as it
|
||||
|
||||
@@ -257,6 +257,34 @@ func TestWholeAsStreamResponsesCitations(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A citation another vendor's whole reply carries without the offsets
|
||||
// OpenAI's schema wants on every annotation (Volcengine Ark's
|
||||
// url_citation, #4921) goes to no place a client reads one: not in the
|
||||
// annotation events, nor in the parts, items and reply the client keeps,
|
||||
// for the client stores them and replays them, and where that schema
|
||||
// holds the replay is refused whole. The text and a citation that carries
|
||||
// its offsets go as the vendor wrote them.
|
||||
func TestWholeAsStreamDropsCitationsWithoutOffsets(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
if !wholeAsStream(rec, provider.Responses, []byte(`{"id":"resp_1","object":"response","created_at":1,"status":"completed","model":"m","output":[{"type":"message","id":"msg_1","status":"completed","role":"assistant","content":[{"type":"output_text","text":"Sun.","annotations":[`+
|
||||
`{"type":"url_citation","url":"https://example.com/ark","title":"Ark","site_name":"example.com"},`+
|
||||
`{"type":"url_citation","start_index":0,"end_index":3,"url":"https://example.com/w","title":"W"}]}]}]}`)) {
|
||||
t.Fatal("not streamed")
|
||||
}
|
||||
got := rec.Body.String()
|
||||
if strings.Contains(got, "example.com/ark") {
|
||||
t.Fatalf("the offsetless citation reached the client:\n%s", got)
|
||||
}
|
||||
// the citation with its offsets is in every place a client reads one:
|
||||
// its annotation event, the part, the item and the reply it keeps
|
||||
if cited := strings.Count(got, "example.com/w"); cited != 4 {
|
||||
t.Fatalf("the citation with its offsets is in %d places, want 4:\n%s", cited, got)
|
||||
}
|
||||
if said := saidIn(provider.Responses, got); said != "text:Sun.|stop:stop" {
|
||||
t.Fatalf("the stream says %q:\n%s", said, got)
|
||||
}
|
||||
}
|
||||
|
||||
// A held try's reply under a type that says neither JSON nor a stream,
|
||||
// once the agent has a stream's headers: its first bytes decide, however
|
||||
// they are split. A stream is held as a stream from there, read event by
|
||||
|
||||
@@ -169,6 +169,9 @@ func responsesWholeEvents(b []byte) []wholeEvent {
|
||||
if json.Unmarshal(v["output"], &output) != nil {
|
||||
return nil
|
||||
}
|
||||
if dropOffsetlessCitations(output) {
|
||||
v["output"] = raw(output)
|
||||
}
|
||||
var events []wholeEvent
|
||||
seq := 0
|
||||
send := func(typ string, fields obj) {
|
||||
@@ -360,3 +363,78 @@ func orNull(r json.RawMessage) json.RawMessage {
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// dropOffsetlessCitations takes, from a whole reply's message items, the
|
||||
// output_text annotations that lack the offsets OpenAI's schema wants on
|
||||
// every annotation — another vendor's Responses endpoint writes its
|
||||
// citations so (Volcengine Ark's url_citation, #4921) — and reports
|
||||
// whether it took any. What magpie hands a client must be something it
|
||||
// could send again (#2855): the client stores the reply and replays it,
|
||||
// and where that schema holds the replay is refused whole, every turn of
|
||||
// the thread after ("Missing required parameter:
|
||||
// 'input[n].content[m].annotations[k].start_index'"). The text goes as it
|
||||
// came; so does a citation that carries its offsets.
|
||||
func dropOffsetlessCitations(output []obj) bool {
|
||||
dropped := false
|
||||
for _, item := range output {
|
||||
if str(item, "type") != "message" {
|
||||
continue
|
||||
}
|
||||
var parts []obj
|
||||
if json.Unmarshal(item["content"], &parts) != nil {
|
||||
continue
|
||||
}
|
||||
itemChanged := false
|
||||
for _, part := range parts {
|
||||
if str(part, "type") != "output_text" {
|
||||
continue
|
||||
}
|
||||
var notes []json.RawMessage
|
||||
if json.Unmarshal(part["annotations"], ¬es) != nil || len(notes) == 0 {
|
||||
continue
|
||||
}
|
||||
kept := notes[:0]
|
||||
partDropped := false
|
||||
for _, a := range notes {
|
||||
if annotationLacksOffsets(a) {
|
||||
partDropped = true
|
||||
continue
|
||||
}
|
||||
kept = append(kept, a)
|
||||
}
|
||||
if partDropped {
|
||||
part["annotations"] = raw(kept)
|
||||
itemChanged = true
|
||||
}
|
||||
}
|
||||
if itemChanged {
|
||||
item["content"] = raw(parts)
|
||||
}
|
||||
dropped = dropped || itemChanged
|
||||
}
|
||||
return dropped
|
||||
}
|
||||
|
||||
// annotationLacksOffsets is whether a, an output_text annotation of a
|
||||
// kind OpenAI's schema wants a start and end index of (url_citation,
|
||||
// container_file_citation), lacks either, as absent or null. A
|
||||
// file_citation or file_path places itself by its one index and is kept
|
||||
// as it came; one that isn't an object lacks nothing magpie can read.
|
||||
func annotationLacksOffsets(a json.RawMessage) bool {
|
||||
var note map[string]json.RawMessage
|
||||
if json.Unmarshal(a, ¬e) != nil || note == nil {
|
||||
return false
|
||||
}
|
||||
switch t, _ := stringBytes(note["type"]); string(t) {
|
||||
case "url_citation", "container_file_citation":
|
||||
default:
|
||||
return false
|
||||
}
|
||||
for _, k := range []string{"start_index", "end_index"} {
|
||||
v, ok := note[k]
|
||||
if !ok || string(bytes.TrimSpace(v)) == "null" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user