codex: GPT-6.2's instructions go first in the input, where its cache keeps them

From GPT-6.2 on, OpenAI reads a Responses request's top-level
instructions after its input, not before it (prompt caching guide:
"instructions ... appended to the end of the input" for gpt-6.2 and
later), so they sit past the cached prefix and are billed uncached on
every turn. Codex itself sends no top-level instructions: client.rs puts
its base instructions first in the input as a developer message
(BaseInstructionsFragment, codex-rs/core/src/client.rs).

magpie sent Codex's instructions on top for every ChatGPT-account
request that is not Responses Lite: Claude Code, OpenCode, Pi and other
translated agents through a codex account, and Codex CLIs older than
Lite. Measured on a real ChatGPT account, third turn of a growing
conversation: gpt-6.2-sol cached 1,920 of 8,271 input tokens with the
instructions on top, 6,016 with them first in the input; gpt-6-sol
cached 5,632 of 6,843 with them on top (the old order still works
there). Reported on X by Anotiaww (Codex hit rate looked low).

- codexBody: for a GPT-6.2+ model Codex's instructions, and a client's
  own, go first in the input as developer messages, and the request
  carries no instructions field. Older models are unchanged, and Lite
  turns (no instructions at all) are unchanged.
- siwcBody (Sign in with ChatGPT API path): the client's instructions
  go first in the input for GPT-6.2+.
- buildResponses (Chat/Anthropic translated to Responses, any host):
  the system prompt goes first in the input for GPT-6.2+.
- InstructionsAfterInput names the models: gpt-N.M with N.M >= 6.2,
  gpt-7 and later, after a provider prefix; gpt-6, gpt-6.1, gpt-5.x,
  o-series and other vendors' models keep top-level instructions.

The instruction text itself is unchanged; only where it sits moves.

Run (mote, at this tree on origin/main 48fffb60c):
- go test -count=1 -timeout 45m ./...: all 103 packages ok
  (internal/gateway 1602s, internal/provider 463s).
- go vet ./internal/provider ./internal/gateway on darwin, linux and
  windows: ok. gofmt -l: clean.

Broken by hand, then put back: InstructionsAfterInput returning false
turns TestInstructionsAfterInput, TestCodexBodyInstructionsFirstIn-
InputOnGPT62, TestSiwcBodyInstructionsFirstInInputOnGPT62 and
TestResponsesSystemFirstInInputOnGPT62 red.

Not tried: a real Claude Code or OpenCode session through magpie on
gpt-6.2 (the live app lists no gpt-6.2 model here); the cache numbers
above are from direct requests to the ChatGPT backend in both orders.
This commit is contained in:
yetone
2026-11-18 16:04:56 +08:00
parent 42c43c0020
commit f7e0f68ca2
5 changed files with 197 additions and 3 deletions
+5 -1
View File
@@ -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 {
@@ -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)
}
}
+9
View File
@@ -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")
+44 -2
View File
@@ -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
@@ -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)
}
}