diff --git a/internal/gateway/responses.go b/internal/gateway/responses.go index d64239b6d..11d6c9edb 100644 --- a/internal/gateway/responses.go +++ b/internal/gateway/responses.go @@ -1547,7 +1547,11 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte { if r.CacheKey != "" { out["prompt_cache_key"] = r.CacheKey } - if r.System != "" { + if r.System != "" && provider.InstructionsAfterInput(model) { + // GPT-6.2 reads top-level instructions after the input, uncached + // every turn: the system prompt goes first in it instead + out["input"] = append([]any{provider.DeveloperMessage(r.System)}, input...) + } else if r.System != "" { out["instructions"] = r.System } if r.MaxTokens > 0 { diff --git a/internal/gateway/responses_instructions_after_input_test.go b/internal/gateway/responses_instructions_after_input_test.go new file mode 100644 index 000000000..680da69d9 --- /dev/null +++ b/internal/gateway/responses_instructions_after_input_test.go @@ -0,0 +1,35 @@ +package gateway + +import ( + "encoding/json" + "testing" +) + +// A request built in Responses for GPT-6.2 carries its system prompt first +// in the input: the model reads top-level instructions after the input, +// uncached every turn. Another model's goes on top as before. +func TestResponsesSystemFirstInInputOnGPT62(t *testing.T) { + r := &Request{System: "You are Claude Code.", Messages: []Message{{Role: "user", Parts: []Part{{Kind: Text, Text: "hi"}}}}} + var m struct { + Instructions *string `json:"instructions"` + Input []map[string]any `json:"input"` + } + if err := json.Unmarshal(buildResponses(r, "gpt-6.2-sol", "api.openai.com", false), &m); err != nil { + t.Fatal(err) + } + if m.Instructions != nil || len(m.Input) != 2 || m.Input[0]["role"] != "developer" || m.Input[1]["role"] != "user" { + t.Fatalf("gpt-6.2-sol: %+v", m) + } + c, _ := m.Input[0]["content"].([]any) + if p, _ := c[0].(map[string]any); len(c) != 1 || p["text"] != "You are Claude Code." { + t.Fatalf("gpt-6.2-sol developer item: %+v", m.Input[0]) + } + + m.Instructions, m.Input = nil, nil + if err := json.Unmarshal(buildResponses(r, "gpt-6-sol", "api.openai.com", false), &m); err != nil { + t.Fatal(err) + } + if m.Instructions == nil || *m.Instructions != "You are Claude Code." || len(m.Input) != 1 { + t.Fatalf("gpt-6-sol: %+v", m) + } +} diff --git a/internal/provider/chatgpt_api.go b/internal/provider/chatgpt_api.go index 4546e3536..3321411a1 100644 --- a/internal/provider/chatgpt_api.go +++ b/internal/provider/chatgpt_api.go @@ -646,6 +646,15 @@ func siwcBody(body []byte) []byte { m["prompt_cache_key"] = k } } + // GPT-6.2 reads top-level instructions after the input, uncached + // every turn: they go first in it (InstructionsAfterInput) + if own, _ := m["instructions"].(string); own != "" { + if model, _ := m["model"].(string); InstructionsAfterInput(model) { + input, _ := m["input"].([]any) + m["input"] = append([]any{DeveloperMessage(own)}, input...) + delete(m, "instructions") + } + } if tools, ok := m["tools"].([]any); ok { if tools = siwcOwnTools(tools); len(tools) == 0 { delete(m, "tools") diff --git a/internal/provider/codex_request.go b/internal/provider/codex_request.go index 226ebc2b3..2110e4890 100644 --- a/internal/provider/codex_request.go +++ b/internal/provider/codex_request.go @@ -10,6 +10,7 @@ import ( "os" "path/filepath" "runtime" + "strconv" "strings" "sync" "time" @@ -358,10 +359,17 @@ func codexBody(body []byte) []byte { if firstLine(own) == firstLine(codex) { codex = own } else { - input = append([]any{map[string]any{"type": "message", "role": "developer", - "content": []any{map[string]any{"type": "input_text", "text": own}}}}, input...) + input = append([]any{DeveloperMessage(own)}, input...) } } + if codex != "" && InstructionsAfterInput(model) { + // GPT-6.2 reads top-level instructions after the input, so they + // went uncached every turn; they go first in the input, where + // Codex puts its own (BaseInstructionsFragment) + input = append([]any{DeveloperMessage(codex)}, input...) + codex = "" + delete(m, "instructions") + } if input == nil { input = []any{} } @@ -411,6 +419,40 @@ func codexBody(body []byte) []byte { return out } +// InstructionsAfterInput says model is one OpenAI reads a request's +// top-level instructions for after its input, not before it: GPT-6.2 and +// later ("Starting with GPT-6.2, models append top-level instructions +// after input and bill those tokens at the uncached input rate", +// developers.openai.com/api/docs/guides/prompt-caching). Sent so, they +// end the prompt the cache keeps, and from the second turn on what is +// cached ends where the last turn's input did: on a ChatGPT account +// gpt-6.2-sol had 1,920 of 8,271 input tokens cached on a third turn with +// Codex's instructions on top, 6,016 with them first in the input +// (gpt-6-sol cached 5,632 of 6,843 with them on top). Such a model is +// sent its instructions as a developer message first in the input, which +// is where Codex puts its own on every model. +func InstructionsAfterInput(model string) bool { + if i := strings.LastIndexByte(model, '/'); i >= 0 { + model = model[i+1:] + } + g := gptVersionRE.FindStringSubmatch(strings.ToLower(model)) + if g == nil { + return false + } + major, _ := strconv.Atoi(g[1]) + minor, _ := strconv.Atoi(g[2]) // "" (gpt-7) is 0 + return major > 6 || major == 6 && minor >= 2 +} + +var gptVersionRE = lazyre.New(`^gpt-(\d+)(?:\.(\d+))?(?:$|-)`) + +// DeveloperMessage is text as a Responses developer message, as Codex +// sends its base instructions in the input. +func DeveloperMessage(text string) map[string]any { + return map[string]any{"type": "message", "role": "developer", + "content": []any{map[string]any{"type": "input_text", "text": text}}} +} + // conversationKey names the conversation a request belongs to, for a client // that doesn't (Codex sends its thread's id as prompt_cache_key): the // backend keeps a conversation's cached prompt, and Codex CLI's session diff --git a/internal/provider/instructions_after_input_test.go b/internal/provider/instructions_after_input_test.go new file mode 100644 index 000000000..dd7580343 --- /dev/null +++ b/internal/provider/instructions_after_input_test.go @@ -0,0 +1,104 @@ +package provider + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" +) + +func TestInstructionsAfterInput(t *testing.T) { + for model, want := range map[string]bool{ + "gpt-6.2-sol": true, "gpt-6.2-astra": true, "codex/gpt-6.2-sol": true, "GPT-6.3": true, "gpt-7": true, "gpt-7.1-luna": true, "relay/gpt-6.10": true, + "gpt-6-sol": false, "gpt-6.1-sol": false, "gpt-6": false, "gpt-5.6-sol": false, "gpt-5.5": false, "gpt-4.1": false, "o3": false, + "claude-opus-5-5": false, "chatgpt-6.2": false, "": false, + } { + if got := InstructionsAfterInput(model); got != want { + t.Errorf("InstructionsAfterInput(%q) = %v, want %v", model, got, want) + } + } +} + +// A ChatGPT account's GPT-6.2 turn carries Codex's instructions first in +// its input, not on top, where the model reads them after the input and +// the cache never keeps them; an older model's stay on top. +func TestCodexBodyInstructionsFirstInInputOnGPT62(t *testing.T) { + dir := t.TempDir() + t.Setenv("CODEX_HOME", dir) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + os.WriteFile(filepath.Join(dir, "models_cache.json"), []byte(`{"models":[ + {"slug":"gpt-6.2-sol","model_messages":{"instructions_template":"You are Codex, based on GPT-6.2.\nMore."}}, + {"slug":"gpt-6-sol","model_messages":{"instructions_template":"You are Codex, based on GPT-6.\nMore."}}]}`), 0o644) + type body struct { + Instructions *string `json:"instructions"` + Input []map[string]any `json:"input"` + } + text := func(it map[string]any) string { + c, _ := it["content"].([]any) + if len(c) != 1 { + return "" + } + p, _ := c[0].(map[string]any) + s, _ := p["text"].(string) + return s + } + for name, tc := range map[string]struct { + in string + want []string // the developer texts first in the input + }{ + "translated": {`{"model":"gpt-6.2-sol","instructions":"You are Pi.","input":[{"type":"message","role":"user","content":"hi"}]}`, + []string{"You are Codex, based on GPT-6.2.\nMore.", "You are Pi."}}, + "codex's own": {`{"model":"gpt-6.2-sol","instructions":"You are Codex, based on GPT-6.2.\nMore.","input":[{"type":"message","role":"user","content":"hi"}]}`, + []string{"You are Codex, based on GPT-6.2.\nMore."}}, + "none": {`{"model":"gpt-6.2-sol","input":[{"type":"message","role":"user","content":"hi"}]}`, + []string{"You are Codex, based on GPT-6.2.\nMore."}}, + } { + var m body + out := codexBody([]byte(tc.in)) + if err := json.Unmarshal(out, &m); err != nil { + t.Fatal(err) + } + if m.Instructions != nil { + t.Errorf("%s: instructions on top: %s", name, out) + } + if len(m.Input) != len(tc.want)+1 { + t.Fatalf("%s: %s", name, out) + } + for i, w := range tc.want { + if m.Input[i]["role"] != "developer" || text(m.Input[i]) != w { + t.Errorf("%s: input[%d] = %v, want developer %q", name, i, m.Input[i], w) + } + } + if m.Input[len(tc.want)]["role"] != "user" { + t.Errorf("%s: %s", name, out) + } + } + + var m body + if err := json.Unmarshal(codexBody([]byte(`{"model":"gpt-6-sol","instructions":"You are Pi.","input":[{"type":"message","role":"user","content":"hi"}]}`)), &m); err != nil { + t.Fatal(err) + } + if m.Instructions == nil || *m.Instructions != "You are Codex, based on GPT-6.\nMore." || len(m.Input) != 2 || text(m.Input[0]) != "You are Pi." { + t.Fatalf("gpt-6-sol: %+v", m) + } +} + +func TestSiwcBodyInstructionsFirstInInputOnGPT62(t *testing.T) { + var m map[string]any + if err := json.Unmarshal(siwcBody([]byte(`{"model":"gpt-6.2-astra","instructions":"Be brief.","input":"hello"}`)), &m); err != nil { + t.Fatal(err) + } + in, _ := m["input"].([]any) + first, _ := in[0].(map[string]any) + if _, ok := m["instructions"]; ok || len(in) != 2 || first["role"] != "developer" { + t.Fatalf("%v", m) + } + if k, _ := m["prompt_cache_key"].(string); k == "" { + t.Fatalf("no prompt_cache_key: %v", m) + } + m = nil + json.Unmarshal(siwcBody([]byte(`{"model":"gpt-6-astra","instructions":"Be brief.","input":"hello"}`)), &m) + if m["instructions"] != "Be brief." { + t.Fatalf("gpt-6-astra: %v", m) + } +}