Files
magpie/internal/gateway/effort_update.go
T
yetone abec0cae1c gateway: a reasoning effort changed mid-thread keeps the upstream's cached prompt on GPT-6 (#617) — an agent switching effort changed the request's reasoning.effort, and with it the prefix OpenAI caches. OpenAI's Responses API takes the change as an input item instead (developers.openai.com/api/docs/guides/reasoning, "Change reasoning mid-conversation": {"type":"configuration_update","reasoning":{"effort":…}} before the next user message, the request-level effort unchanged, GPT-6 family). For a GPT-6 model through a ChatGPT account or OpenAI's own API, asked in Responses, magpie keeps per thread (conversation, prompt_cache_key, account, model) the effort it started at and where each change went: the top stays at the first effort, and the updates are put back at the same places on every later request (before the turn's first user message, else at the input's end; a turn asked again at another effort replaces its own update). A history that isn't the last one with more after it (compaction, edits), previous_response_id, truncation auto, context_management, a request without an effort or an agent sending its own updates goes as the agent sent it and starts the thread again — what every request cost before. An upstream that answers 400 to a request with updates is asked again as the agent sent it (trace: update); if that one goes, the account and model get no updates for a day. Other vendors (forVendor strips the items anyway) and older models are untouched. A preview, off unless MAGPIE_EFFORT_UPDATES=on, until it is seen on the real backends: one that took the item and ignored it would leave an effort change doing nothing, unseen. Tests: TestEffortChangeKeepsTheCache, TestEffortUpdateRefused (both fail with it off), TestTakesEffortUpdates, TestEffortChangeOtherVendor against a fake ChatGPT backend. Not tried against the real ChatGPT backend or OpenAI API: whether the backend honours the item (rather than ignoring it) and cached_tokens across a switch are unverified. go vet ./internal/..., go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui -count=1 ./... under a temp HOME pass.
2026-10-03 09:58:00 +08:00

222 lines
6.9 KiB
Go

package gateway
// An agent that changes its reasoning effort mid-thread changes the
// request's reasoning.effort, and the upstream's cached prompt with it
// (#617). OpenAI's Responses API takes the change as an input item instead
// ("Change reasoning mid-conversation", developers.openai.com/api/docs/
// guides/reasoning): the thread's first effort stays at the top, and
//
// {"type": "configuration_update", "reasoning": {"effort": "high"}}
//
// goes before the next user message, in the history from then on, so the
// prefix the cache keeps stays as it was. The GPT-6 family takes it.
//
// The agent's own history has no such items, so magpie keeps, for each
// thread on each account and model, the effort it started at and where it
// put each update, and puts them back on every later request. A history
// that isn't the last one with more after it (compacted, edited, another
// thread under the same key) starts the thread again, at the effort it
// asks — what a request costs without any of this. Lost on a restart, a
// thread's state costs one cache miss, as before.
import (
"bytes"
"crypto/sha256"
"encoding/json"
"os"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/provider"
)
// effortThread is a thread's reasoning as magpie sends it.
type effortThread struct {
base string // the effort at the top, the thread's first
updates []effortUpdate // in order of where they go
n int // how many items the last request's input had
sum [sha256.Size]byte
at time.Time
}
// effortUpdate is a configuration_update put before the agent's input
// item at (an index into the agent's own input).
type effortUpdate struct {
at int
effort string
}
// effort is the thread's effort after its updates.
func (t *effortThread) effort() string {
if len(t.updates) > 0 {
return t.updates[len(t.updates)-1].effort
}
return t.base
}
var effortThreads = struct {
sync.Mutex
m map[string]*effortThread
// no is an account and model whose upstream turned the items away:
// its requests go as the agent sent them
no map[string]time.Time
}{m: map[string]*effortThread{}, no: map[string]time.Time{}}
const effortThreadKeep = 24 * time.Hour
// takesEffortUpdates: a GPT-6 model, through a ChatGPT account or
// OpenAI's own API, asked in Responses, with MAGPIE_EFFORT_UPDATES=on — a
// preview until it is seen on the real backends: one that took the item
// and ignored it would leave an effort change doing nothing, unseen.
func takesEffortUpdates(p provider.Provider, model string) bool {
if os.Getenv("MAGPIE_EFFORT_UPDATES") != "on" || p.Base(provider.Responses) == "" {
return false
}
if !(p.Account != nil && p.Account.Agent == "codex" || p.Account == nil && strings.HasSuffix(p.Host(), "openai.com")) {
return false
}
if i := strings.LastIndexByte(model, '/'); i >= 0 {
model = model[i+1:]
}
return strings.HasPrefix(strings.ToLower(model), "gpt-6")
}
// withEffortUpdates is a Responses request to who's model, asking for
// effort (as fitted to the model), with the thread's effort changes as
// configuration_update items, conv naming the conversation; ok is false
// when it goes as it is.
func withEffortUpdates(conv, who, model, effort string, body []byte) ([]byte, bool) {
var q map[string]json.RawMessage
if json.Unmarshal(body, &q) != nil {
return nil, false
}
var reasoning map[string]json.RawMessage
if json.Unmarshal(q["reasoning"], &reasoning) != nil || reasoning == nil {
effort = ""
}
var items []json.RawMessage
if json.Unmarshal(q["input"], &items) != nil || len(items) == 0 {
return nil, false
}
var key string
json.Unmarshal(q["prompt_cache_key"], &key)
k := conv + "|" + key + "|" + who + "|" + model
acct := who + "|" + model
effortThreads.Lock()
defer effortThreads.Unlock()
now := time.Now()
if t, ok := effortThreads.no[acct]; ok && now.Sub(t) < effortThreadKeep {
return nil, false
}
// what the update can't go with: a history the server keeps, the
// API's automatic truncation or compaction, an agent that sends its
// own updates, or a request without an effort
_, prev := q["previous_response_id"]
_, managed := q["context_management"]
if prev || managed || string(q["truncation"]) == `"auto"` || effort == "" || effort == "none" ||
bytes.Contains(q["input"], []byte(`"configuration_update"`)) {
delete(effortThreads.m, k)
return nil, false
}
t := effortThreads.m[k]
if t != nil && (len(items) < t.n || itemsSum(items[:t.n]) != t.sum || now.Sub(t.at) > effortThreadKeep) {
t = nil
}
if t == nil {
effortThreads.m[k] = &effortThread{base: effort, n: len(items), sum: itemsSum(items), at: now}
pruneEffortThreads(now)
return nil, false
}
if effort != t.effort() {
// before the first user message this turn added; with none, at
// its end — between the replies either way
at := len(items)
for i := t.n; i < len(items); i++ {
if isUserItem(items[i]) {
at = i
break
}
}
if n := len(t.updates); n > 0 && t.updates[n-1].at == at {
// the same turn asked again at another effort: one update
// there, none when it's back to what it was before
t.updates = t.updates[:n-1]
if effort != t.effort() {
t.updates = append(t.updates, effortUpdate{at, effort})
}
} else {
t.updates = append(t.updates, effortUpdate{at, effort})
}
}
t.n, t.sum, t.at = len(items), itemsSum(items), now
if len(t.updates) == 0 {
return nil, false // still at the effort it started at
}
out := make([]json.RawMessage, 0, len(items)+len(t.updates))
u := 0
for i := 0; i <= len(items); i++ {
for u < len(t.updates) && t.updates[u].at == i {
e := t.updates[u].effort
if e == "ultra" {
e = "max" // Codex CLI's name for it
}
raw, _ := marshalPlain(map[string]any{"type": "configuration_update", "reasoning": map[string]any{"effort": e}})
out = append(out, raw)
u++
}
if i < len(items) {
out = append(out, items[i])
}
}
reasoning["effort"], _ = json.Marshal(t.base)
q["reasoning"], _ = marshalPlain(reasoning)
q["input"], _ = marshalPlain(out)
b, err := marshalPlain(q)
if err != nil {
return nil, false
}
return b, true
}
// effortUpdatesRefused notes that who's model turned the items away: its
// requests go as the agent sent them from now on.
func effortUpdatesRefused(who, model string) {
effortThreads.Lock()
defer effortThreads.Unlock()
effortThreads.no[who+"|"+model] = time.Now()
}
func pruneEffortThreads(now time.Time) {
if len(effortThreads.m) <= 4096 {
return
}
for k, t := range effortThreads.m {
if now.Sub(t.at) > time.Hour {
delete(effortThreads.m, k)
}
}
}
func itemsSum(items []json.RawMessage) [sha256.Size]byte {
h := sha256.New()
for _, it := range items {
h.Write(it)
h.Write([]byte{0})
}
var s [sha256.Size]byte
h.Sum(s[:0])
return s
}
func isUserItem(raw json.RawMessage) bool {
var it struct {
Type string `json:"type"`
Role string `json:"role"`
}
return json.Unmarshal(raw, &it) == nil && it.Role == "user" && (it.Type == "" || it.Type == "message")
}