gui, tune: Tuned for you weighs a model magpie routes at its provider's price, not by its name (#3435)
Tune weighed a call's tokens by its model's name alone (tune.WeightsFor):
an id starting "claude" at Anthropic's ratios (read 0.1, write 1.25, an
hour's write 2), any other at generic ones (an hour's write at a
5-minute one's price). Claude Code is given magpie's models as
provider/model ids (copilot/claude-opus-5-5, anthropic/claude-opus-5-5),
which the name rule took for no Claude model. So a Claude model on an
Anthropic-billed provider was weighed with its hour costing no more than
5 minutes, and none was weighed at the price the usage pages count.
The replay now takes its weights from a tune.Weigh (CompactOpts.Weigh,
and CacheTTL's third argument), per stream; nil weighs as before. Tuned
for you passes pricedWeights: an id with a provider resolves as the
gateway resolves it (provider.Resolve after ClaudeRead) and is weighed
at that provider's EffectivePriceIn, so a Claude model on Copilot has
its hour at the 5-minute write Copilot bills (the previous commit) and
one on Anthropic at 2x. A model Claude Code named itself keeps its
maker's weights, as does a price with no cache read or write. The
compaction advice is weighed the same way. docs/subsystems/agent-wiring.md
says so.
Run on mote (go1.26.8, macOS) at 400b66ec3 plus the previous commit and
this one:
- go test ./internal/tune, and ./internal/gui -run Tune: ok.
- With pricedWeights weighing by the name alone (by hand),
TestTuneWeighsRoutedCallsAtTheirProvidersPrice is red:
"relay/claude-opus-5-5 weighs {Read:0.1 Write:1 Write1h:1 Out:8};
want its price's" and "cache advice ... {Current:1h Best:1h ...};
want 1h -> 5m".
Not tried: the Context tab in the app; the advice's numbers change, not
its layout or text. Claude Desktop's Code tab is still left out of Tuned
for you, though #3435 names it.
Reported-by: mdwsk88 (dawei on Discord)
Co-authored-by: mdwsk88 <11055210+mdwsk88@users.noreply.github.com>
This commit is contained in:
@@ -30,7 +30,7 @@ something else shows up as drift.
|
||||
| Named omp profiles | omp keeps a profile's settings under `~/.omp/profiles/<name>` (or under `PI_CONFIG_DIR`), each with its own `config.yml` and `models.yml`. Every such profile is an agent of its own — `omp#<name>` on Windows, `omp#<name>@wsl:<distro>` in a distro — so each can be connected, drifted and disconnected on its own. They share omp's model lists (`ListsFor`), and the default `omp` row is the folder `ompDir`/`ompIn` already pick, so an `OMP_PROFILE` that row is already pointed at is not listed twice. A name omp refuses is not a row: `default`, a trailing dot, or a Windows reserved device name (`aux`, `nul`, `com1`, `lpt9.x`, `con.work`), on every platform (`ompProfileOK`). A distro's profile names come from its probe and are kept in `wsl.json`; a stopped distro is never started to list them, its profile rows showing what was last seen (`asleep`). | [`omp.go`](../../internal/agent/omp.go), [`wsl.go`](../../internal/agent/wsl.go) |
|
||||
| WSL twins | On Windows each running distro is probed once, without starting a stopped one. The `wslKinds` agents found there become agents of their own, `<id>@wsl:<distro>`, edited through `\\wsl.localhost\<distro>`. A kind is found by its folder under the distro's home or by its command there (not one on a Windows drive). The probe runs `sh -l`, which reads `~/.profile` but not `~/.bashrc`, so a command off its PATH is looked for where Node's managers and installers keep one, as `proc.UserBinDirs` does here (`wslbin`): bun, `~/.local/bin`, volta, pnpm, nvm's default then the highest, fnm's default then the highest (`FNM_DIR`, `~/.local/share/fnm`, `~/.fnm`), mise's installs and shims, asdf, `~/.npmrc`'s prefix, cargo, deno and Homebrew (千里不再 on Discord: a Pi from fnm, not run yet so with no `~/.pi`, wasn't found). One on a Windows drive, which WSL's PATH reaches first when the distro's isn't on it, is looked past rather than taken as the only one (`wslcmd`, `wslwin`; `TestWSLProbeFindsNodeManagersBins`, `TestWSLProbeLooksPastWindowsCommand`). The shell isn't asked interactively for `~/.bashrc`'s PATH: under `timeout` such a bash stops itself on WSL and outlives the timeout. Where another tool shares one of them, the kind leaves it out: Gemini CLI is found by its command alone, because Antigravity keeps `~/.gemini` too. Antigravity CLI is found by its own `~/.gemini/antigravity-cli` or its `agy` command (mimi001234 on Discord). Goose is found by its folder alone, because a `goose` command can be pressly's migration tool. Reasonix also needs the version its command gives (`accept`), because the old npm client is named `reasonix` too. The gateway address and key follow the distro's networking: mirrored or NAT (`place`, `keyAt`). Under NAT the key is the gateway's WSL key (`gateway.WSLKey`, `-<agent>` after it where the agent's key names it), sharing on or off; the gateway listens at that address itself (gateway-routing's WSL under NAT). `ListsFor` keeps a twin's model picks under the Windows twin's id (#927). With Settings' Detect agents in WSL off (`NoWSLAgents`, #1264) magpie starts no wsl.exe at all: `proc.Command`, `CommandContext` and `ProbeContext` refuse one by any name or path with `proc.ErrWSLOff` (`wslOff` in [`proc/wsl.go`](../../internal/proc/wsl.go)), where every command magpie runs is made, so a path past agent's and wslrun's own gates (a request's Claude Code stand-in and classifier, #4872: on a computer without WSL each ask put up Windows' install window) asks nothing either (`TestWSLOffStartsNoWSL`, `TestWSLRunnerRefusedWhenOff`, `TestRunRefusedWhenOff`, `TestWSLStandInAsksNothingWhenOff`). | [`wsl.go`](../../internal/agent/wsl.go), [`gatewaykey.go`](../../internal/agent/gatewaykey.go), [`proc/wsl.go`](../../internal/proc/wsl.go) |
|
||||
| WSL folders that are links | Through `\\wsl.localhost` Windows can't follow a link the distro has: with `~/.codex` a link to `/mnt/c/Users/<user>/.codex`, a mkdir of it says it exists and nothing below it can be made, written, read or listed (#4502, linusxiong). The probe asks `readlink -f` there where each agent folder, its `skills` and the folders beside them lead (`wslLinkPaths`, `distro.Links`; a `$HOME` that is itself through a link is left as it was) and which drive each Windows mount is (`distro.Drives`). `distro.open` opens a path at or below a link where it leads: on a Windows drive the drive's own path (`C:\Users\<user>\.codex`), elsewhere in the distro through its root again; `native` spells such a path back through the link for the agent. A link `readlink -f` couldn't resolve is never guessed at: its agent is unreached (`Agent.Unreached`), says why in its notice and refuses each change and sync. Every writer goes through it: the agents' own files (`place.join`, `place.open`), the library's targets (`wslOpen`, a `wsl` problem per agent), RTK (`rtkAt`, `agent.WSLOpen`), the Sessions page's reads (`sessions.WSLHome.Open`) and the Copilot CLI's sign-in (`provider.CopilotWSLDirs`). Links deeper than the probed paths aren't resolved (`TestWSLOpenThroughLinks`, `TestWSLAgentFolderIsALink`, `TestWSLAgentFolderLinkUnresolved`, `TestWSLProbeLinks`, `TestWSLFolderIsALinkToC`, `TestRTKWSLFolderIsALink`). | [`wsl.go`](../../internal/agent/wsl.go), [`targets.go`](../../internal/library/targets.go), [`rtk_wsl.go`](../../internal/library/rtk_wsl.go) |
|
||||
| Settings tuned from use | Usage › Context's "Tuned for you" advises, per agent, the settings that would have spent the fewest tokens on the user's own calls of the range, and puts one in on a click. Package `tune` replays the calls `sessions.Calls` reads from the agents' session files under each candidate value (`Compact`, `CacheTTL`); `tuneOf` picks the agents and models (Claude Code per model, Codex pooled). `TuneRead`, `TuneApply` and `TuneUndo` know where each setting lives: Claude Code's `modelSettings.<model>.autoCompactWindow` (where its `/autocompact` saves), `promptCacheTtl` and `subagentPromptCacheTtl` in `~/.claude/settings.json`. Where Codex compacts, and Claude Code wherever magpie's own window is what it runs at, is one value with Long conversations in the agents' settings sheet (`settings.CompactAt`/`FullContext`, source `long`; 7eleven on Discord): the card reads it, Use sets it through `provider.SetCompactAt`, and Sync writes it into each agent's config as it does for the sheet; the note says it is Long conversations, shared by Codex and Claude Code (`compact-one-value.test.cjs`). The advice is weighed by tokens alone: it is labelled "Fewest tokens", and a compaction window it would change says it doesn't measure how well the agent keeps the task after a compaction, and that a lower window compacts more often (#1854, `context-tune.test.cjs`). A compaction row's "Other window…" opens the app menu with every value of the curve, each with its estimated tokens against the setting now (fewer or more, the setting itself marked "Your setting now", hayden4608 on Discord), "Fewest tokens" beside the leanest, and about how many compactions it would have made (`Point.compacts`, from the same replay), and puts the one picked in like Use (#1860). An agent whose files time its compactions also has their wait weighed (HirotaNagai on X): Claude Code's `compact_boundary` line says `compactMetadata.durationMs`, which `sessions` puts on the first call after it, and Codex compacts by a call of its own (the record a `compacted` line names, in rollouts since 2026-09), whose time is the compaction's (`Call.Compact`; an older rollout's compaction has no call and stays untimed). With 3 or more timed for a model (`minTimed`), `Facts.took` is their median seconds, each window says its wait (`Point.wait`, its compactions × `took`), and the row says what a compaction took, the wait at the advice against the window now, and the cheaper window the advice passed over for waiting longer (`Compaction.cheapest`, `wait_cheapest`) when it saves 3% or more; the advice is labelled "Tokens + wait", its caveat says tokens and waiting only, and the picker says each window's wait with "Fewest tokens" on the cheapest (`context-tune.test.cjs`). An agent or model with fewer timed reads and is advised as before. | [`internal/tune`](../../internal/tune/tune.go), [`tune.go`](../../internal/agent/tune.go), [`internal/gui/tune.go`](../../internal/gui/tune.go) |
|
||||
| Settings tuned from use | Usage › Context's "Tuned for you" advises, per agent, the settings that would have spent the fewest tokens on the user's own calls of the range, and puts one in on a click. Package `tune` replays the calls `sessions.Calls` reads from the agents' session files under each candidate value (`Compact`, `CacheTTL`), each model's tokens weighed at what magpie bills them where the agent asked for a model magpie wrote (a provider/model id resolves as the gateway resolves it and is weighed at that provider's price, `pricedWeights`, so a Claude model on Copilot has its 1-hour cache write at the 5-minute one Copilot bills, #3435), else at its maker's list ratios (`tune.WeightsFor`); `tuneOf` picks the agents and models (Claude Code per model, Codex pooled). `TuneRead`, `TuneApply` and `TuneUndo` know where each setting lives: Claude Code's `modelSettings.<model>.autoCompactWindow` (where its `/autocompact` saves), `promptCacheTtl` and `subagentPromptCacheTtl` in `~/.claude/settings.json`. Where Codex compacts, and Claude Code wherever magpie's own window is what it runs at, is one value with Long conversations in the agents' settings sheet (`settings.CompactAt`/`FullContext`, source `long`; 7eleven on Discord): the card reads it, Use sets it through `provider.SetCompactAt`, and Sync writes it into each agent's config as it does for the sheet; the note says it is Long conversations, shared by Codex and Claude Code (`compact-one-value.test.cjs`). The advice is weighed by tokens alone: it is labelled "Fewest tokens", and a compaction window it would change says it doesn't measure how well the agent keeps the task after a compaction, and that a lower window compacts more often (#1854, `context-tune.test.cjs`). A compaction row's "Other window…" opens the app menu with every value of the curve, each with its estimated tokens against the setting now (fewer or more, the setting itself marked "Your setting now", hayden4608 on Discord), "Fewest tokens" beside the leanest, and about how many compactions it would have made (`Point.compacts`, from the same replay), and puts the one picked in like Use (#1860). An agent whose files time its compactions also has their wait weighed (HirotaNagai on X): Claude Code's `compact_boundary` line says `compactMetadata.durationMs`, which `sessions` puts on the first call after it, and Codex compacts by a call of its own (the record a `compacted` line names, in rollouts since 2026-09), whose time is the compaction's (`Call.Compact`; an older rollout's compaction has no call and stays untimed). With 3 or more timed for a model (`minTimed`), `Facts.took` is their median seconds, each window says its wait (`Point.wait`, its compactions × `took`), and the row says what a compaction took, the wait at the advice against the window now, and the cheaper window the advice passed over for waiting longer (`Compaction.cheapest`, `wait_cheapest`) when it saves 3% or more; the advice is labelled "Tokens + wait", its caveat says tokens and waiting only, and the picker says each window's wait with "Fewest tokens" on the cheapest (`context-tune.test.cjs`). An agent or model with fewer timed reads and is advised as before. | [`internal/tune`](../../internal/tune/tune.go), [`tune.go`](../../internal/agent/tune.go), [`internal/gui/tune.go`](../../internal/gui/tune.go) |
|
||||
| Agents a plugin adds | A plugin's `magpie.agent` module (or a `*.agent.js` file) says where an agent magpie has no setup of its own keeps its model (`config`, `format`, `model`, `prefix`), and its `connect` returns the other keys to write. One with no `model` is connect only (#2374): its one field is `provider`, magpie or nothing, as an app whose one setting is magpie as its provider; `connect` is called without a model, must return keys, and is called again on a catalog change (`Sync`); `ListsModels` is set, so its list is the models picked for it. One whose agent keeps the model a new session starts on in a file apart from its provider list says so with `startup` (`config`, `format`, `model`, and `keys` written beside the model as they are) and has no `model`: PiG keeps its providers in `models.json` and `defaultProvider`/`defaultModel` in `settings.json` (str_ on Discord: its row only listed models, where Pi's picks the one it starts on). Its field is `model` again; picking one of magpie's writes `connect`'s keys into `config` and the model and `startup.keys` into `startup.config`, each file stashed under its own `plugin:<id>:<path>` (the startup one marked by its first string key, so a model picked in the agent among magpie's, with `defaultProvider` still `magpie`, reads as magpie's). A model of the agent's own picked in it while `connect`'s keys are still in `config` is `Beside`: connected, not drift, and Disconnect leaves that pick and takes the rest out. A magpie without `startup` reads the same module as connect only (`TestPluggedStartupModel`, `TestPluggedStartupOwnPickKept`, `TestPluggedStartupRestoreGone`). `agentplug` compiles each in moejs (via `jsmod`, as gateway middleware is), reloads it when plugins.json or the file changes, and keeps why one didn't load. `plugged` makes each an `Agent` with `Plugin` set, listed after magpie's own; an id one of magpie's own agents has is refused (`PluginErrors`). `connect` is given each model as `magpieModels` builds it, with `/v1/models`' `native_endpoints` (`provider.NativeEndpoints`; a routing group's, `provider.GroupEndpoints`, the APIs every member relays as it is; carried as `catalog.Model.Endpoints`) and `pricing` (`catalog.OpenRouterPricing` of the same `EntryPricer` price), each left out when not known ([`plugged_connect_facts_test.go`](../../internal/agent/plugged_connect_facts_test.go)). | [`agentplug.go`](../../internal/agentplug/agentplug.go), [`plugged.go`](../../internal/agent/plugged.go) |
|
||||
| Environment-only agents | Agents that read the gateway only from the environment get a `Launch` command. Antigravity CLI (agy) also gets a function `agy` in each shell's profile while it is on one of magpie's models, so typing `agy` in a new terminal starts it on magpie (bestony on Discord). The function runs `magpie agy run`, which starts the agy on PATH with `GEMINI_API_KEY`, `GOOGLE_GEMINI_BASE_URL` and `--model` (no `--model` when the user gives one) while settings.json's model is still magpie's, and unchanged otherwise. PowerShell's asks `magpie agy env` for them, since the Windows app is a GUI program PowerShell doesn't wait for. `Typed` says the function is there; the row then says plain `agy` works in a new terminal, and the `Launch` command is for a terminal open before. agy has no settings-only route: 1.4.7 refuses to start without `GEMINI_API_KEY` in the environment even with a key on the custom model. Cursor Private Inference instead gets user-level variables (`cursorLocalOn`, `KeepCursorLocalEnv`), and magpie writes none of Cursor's own files. It is found by its product.json in the apps folders, in the folder Windows' list of installed programs names (`cursorLocalInstalls`, any folder picked in its installer), or as its Linux AppImage (`Cursor_Private_Inference-…AppImage`) in the folders downloads are kept in (#1254). Its effort field is kept in magpie (`provider.AgentEffort`) and asked by the gateway, its levels those of the models it lists (`pickedEfforts`, #1003). Antigravity's app has the same field while it is on magpie: its picker lists the gateway's models with no level of its own, so one of Antigravity's families of levels went at its default (MDX-Tom, #4838). | [`cursorlocal.go`](../../internal/agent/cursorlocal.go) |
|
||||
| Claude Science | Its daemon (`claude-science`) reads the API's address only from its environment's `ANTHROPIC_BASE_URL` and has no setting for it. Connect restarts the daemon with that variable set to the gateway (`scienceOn`: `stop`, then `serve --detached --no-browser` on the port `status` said it was on) and notes the daemon in `claude-science.json` (url, pid, port); Disconnect restarts it without the variable, one in magpie's own environment taken out too. No variable is set for the user and no file of the app's is written. Setting it again while magpie's daemon runs on this gateway does nothing (`Pick` sets the field after `connect`). `KeepClaudeScience` starts it again on the gateway, on its port, when it isn't running (a restart of the computer), each minute while magpie serves; it never stops one running. `Check` reads the daemon's `operon.lock`, not `status` (seconds for a 130 MB Bun program), and calls a daemon with another pid drift: the app's window, opened while none ran, starts its own without the variable. It is found in the Mac app's bundle (`Claude Science.app/Contents/Resources/bin`), `%LOCALAPPDATA%\Programs\ClaudeScience` on Windows, `~/.local/bin`, else on PATH. The app still needs its own Claude sign-in; the gateway never passes it on (see gateway-routing). | [`claudescience.go`](../../internal/agent/claudescience.go), [`science.go`](../../internal/gateway/science.go) |
|
||||
|
||||
+33
-3
@@ -112,6 +112,7 @@ func tuneOf(cs []sessions.Call, days int, home string) tuneState {
|
||||
// adviseOf is tuneOf from each agent's calls made tune's already.
|
||||
func adviseOf(by map[string][]tune.Call, days int, home string) tuneState {
|
||||
out := tuneState{Days: days, Agents: []tuneAgent{}}
|
||||
weigh := pricedWeights(settings.Load())
|
||||
for _, name := range []string{"claude", "codex"} {
|
||||
calls := by[name]
|
||||
kept := agent.TuneKept(home, name)
|
||||
@@ -157,7 +158,7 @@ func adviseOf(by map[string][]tune.Call, days int, home string) tuneState {
|
||||
}
|
||||
}
|
||||
cur, _ := strconv.Atoi(s.Value)
|
||||
o := tune.CompactOpts{Min: 100000, Max: 1000000, Step: 10000, Reserve: 33000, Window: window, Current: cur}
|
||||
o := tune.CompactOpts{Min: 100000, Max: 1000000, Step: 10000, Reserve: 33000, Window: window, Current: cur, Weigh: weigh}
|
||||
if r := tune.Compact(mc, o); r != nil {
|
||||
ta.Advice = append(ta.Advice, tuneAdvice{Knob: agent.TuneCompact, Model: m, Setting: s, Compact: r})
|
||||
}
|
||||
@@ -173,7 +174,7 @@ func adviseOf(by map[string][]tune.Call, days int, home string) tuneState {
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if r := tune.CacheTTL(k.calls, s.Value); r != nil {
|
||||
if r := tune.CacheTTL(k.calls, s.Value, weigh); r != nil {
|
||||
ta.Advice = append(ta.Advice, tuneAdvice{Knob: k.knob, Setting: s, TTL: r})
|
||||
}
|
||||
}
|
||||
@@ -192,7 +193,7 @@ func adviseOf(by map[string][]tune.Call, days int, home string) tuneState {
|
||||
cur = told
|
||||
}
|
||||
// a value the user chose is never past the last one offered
|
||||
o := tune.CompactOpts{Min: 50000, Max: max(1000000, window, cur, st.CompactAt), Step: 10000, Window: window, Current: cur}
|
||||
o := tune.CompactOpts{Min: 50000, Max: max(1000000, window, cur, st.CompactAt), Step: 10000, Window: window, Current: cur, Weigh: weigh}
|
||||
if r := tune.Compact(calls, o); r != nil {
|
||||
ad := tuneAdvice{Knob: agent.TuneCompact, Setting: s, Compact: r}
|
||||
if own != "" && s.Source == agent.TuneLong && r.Current == told {
|
||||
@@ -221,6 +222,35 @@ func adviseOf(by map[string][]tune.Call, days int, home string) tuneState {
|
||||
return out
|
||||
}
|
||||
|
||||
// pricedWeights weighs a model's calls at what magpie bills them where the
|
||||
// agent asked for a model magpie wrote into its config (provider/model, as
|
||||
// Claude Code is given it, dashed): the price of the provider it resolves
|
||||
// to, as the usage pages count it, so a Claude model on Copilot has its
|
||||
// hour at the 5-minute write Copilot bills and one on Anthropic at 2× input
|
||||
// (#3435). By its name alone a provider/model id was weighed as no Claude
|
||||
// model, its hour costing what a 5-minute write does. A model the agent
|
||||
// named itself never went through magpie and is weighed at its maker's list
|
||||
// (tune.WeightsFor), as is one magpie has no cache price for.
|
||||
func pricedWeights(st settings.Settings) tune.Weigh {
|
||||
memo := map[string]tune.Weights{}
|
||||
return func(model string) tune.Weights {
|
||||
if w, ok := memo[model]; ok {
|
||||
return w
|
||||
}
|
||||
w := tune.WeightsFor(model)
|
||||
if strings.Contains(model, "/") {
|
||||
if p, m, ok := provider.Resolve(provider.ClaudeRead(model)); ok {
|
||||
if pr, ok := provider.EffectivePriceIn(st, p.ID, m); ok && pr.Input > 0 && pr.Output > 0 && pr.CacheRead > 0 && pr.CacheWrite > 0 {
|
||||
w = tune.Weights{Read: pr.CacheRead / pr.Input, Write: pr.CacheWrite / pr.Input,
|
||||
Write1h: pr.OneHour() / pr.Input, Out: pr.Output / pr.Input}
|
||||
}
|
||||
}
|
||||
}
|
||||
memo[model] = w
|
||||
return w
|
||||
}
|
||||
}
|
||||
|
||||
// codexWindow is the window Codex runs the calls' models to, and where
|
||||
// magpie has it compact them when its config.toml says nothing (told: the
|
||||
// largest of the models Long conversations moves, 0 when magpie tells it
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/agent"
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/tune"
|
||||
)
|
||||
|
||||
// Tuned for you weighs a model magpie routes at what magpie bills its
|
||||
// provider, not by its name (#3435). Claude Code is given magpie's models
|
||||
// as provider/model ids, which no name rule took for Claude: a Claude model
|
||||
// on an Anthropic-billed provider was weighed with an hour's cache write at
|
||||
// a 5-minute one's price, so calls seconds apart were left on the hour they
|
||||
// pay twice for. A model Claude Code named itself keeps the maker's weights.
|
||||
func TestTuneWeighsRoutedCallsAtTheirProvidersPrice(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
home := t.TempDir()
|
||||
os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755)
|
||||
// models.dev's entry as magpie's cache had it on 2026-10-24
|
||||
os.WriteFile(catalog.CachePath(), []byte(`{"anthropic":{"id":"anthropic","models":{
|
||||
"claude-opus-5-5":{"id":"claude-opus-5-5","cost":{"input":4,"output":20,"cache_read":0.2,"cache_write":5}}}}}`), 0o644)
|
||||
catalog.Reset()
|
||||
t.Cleanup(catalog.Reset)
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Anthropic: "http://127.0.0.1:1",
|
||||
Models: []string{"claude-opus-5-5"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
weigh := pricedWeights(settings.Load())
|
||||
if w := weigh("relay/claude-opus-5-5"); w != (tune.Weights{Read: 0.05, Write: 1.25, Write1h: 2, Out: 5}) {
|
||||
t.Errorf("relay/claude-opus-5-5 weighs %+v; want its price's: read 0.05, write 1.25, hour 2, out 5", w)
|
||||
}
|
||||
if w := weigh("claude-opus-5-5"); w != tune.WeightsFor("claude-opus-5-5") {
|
||||
t.Errorf("Claude Code's own claude-opus-5-5 weighs %+v; want the maker's, %+v", w, tune.WeightsFor("claude-opus-5-5"))
|
||||
}
|
||||
|
||||
// calls 20 seconds apart, the cache kept for an hour
|
||||
os.MkdirAll(filepath.Join(home, ".claude"), 0o755)
|
||||
os.WriteFile(filepath.Join(home, ".claude", "settings.json"), []byte(`{"promptCacheTtl": "1h"}`), 0o644)
|
||||
st := tuneOf(tuneCalls("claude", "relay/claude-opus-5-5", 80), 7, home)
|
||||
var ttl *tune.TTL
|
||||
for _, a := range st.Agents {
|
||||
for _, ad := range a.Advice {
|
||||
if a.Agent == "claude" && ad.Knob == agent.TuneCache {
|
||||
ttl = ad.TTL
|
||||
}
|
||||
}
|
||||
}
|
||||
if ttl == nil || ttl.Current != "1h" || ttl.Best != "5m" || ttl.Hour <= ttl.Short {
|
||||
t.Fatalf("cache advice for relay/claude-opus-5-5 = %+v; want 1h → 5m, the hour's writes dearer", ttl)
|
||||
}
|
||||
}
|
||||
+30
-11
@@ -85,6 +85,18 @@ func WeightsFor(model string) Weights {
|
||||
return Weights{Read: 0.1, Write: 1, Write1h: 1, Out: 8}
|
||||
}
|
||||
|
||||
// Weigh gives the weights a model's calls are replayed at: what magpie
|
||||
// bills the provider that served them, where the caller knows it (#3435:
|
||||
// Copilot bills an hour's cache write as a 5-minute one), else WeightsFor.
|
||||
type Weigh func(model string) Weights
|
||||
|
||||
func (w Weigh) of(model string) Weights {
|
||||
if w == nil {
|
||||
return WeightsFor(model)
|
||||
}
|
||||
return w(model)
|
||||
}
|
||||
|
||||
// Point is one setting tried and what the period would have cost with it,
|
||||
// and how many compactions it would have made there: what a window over
|
||||
// the leanest buys, said beside what it costs (#1860). Wait is the seconds
|
||||
@@ -156,6 +168,8 @@ type CompactOpts struct {
|
||||
// (zhemu on Discord: a 1M model magpie had no window for was offered
|
||||
// no more than the largest prompt it had been sent, 412K)
|
||||
Window int
|
||||
// Weigh prices the calls; nil weighs them at WeightsFor
|
||||
Weigh Weigh
|
||||
}
|
||||
|
||||
const (
|
||||
@@ -323,7 +337,7 @@ func Compact(cs []Call, o CompactOpts) *Compaction {
|
||||
return nil
|
||||
}
|
||||
model := cs[0].Model
|
||||
w := WeightsFor(model)
|
||||
w := o.Weigh.of(model)
|
||||
write := w.Write
|
||||
var wrote, wrote1 int
|
||||
for _, c := range cs {
|
||||
@@ -472,13 +486,18 @@ type TTL struct {
|
||||
}
|
||||
|
||||
// replayTTL is what the streams would have cost with the cache kept for
|
||||
// ttl at write per token: a call within it of the one before reads what
|
||||
// that one sent and writes what it adds; one after it, or after a
|
||||
// compaction, writes its whole prompt again.
|
||||
func replayTTL(ss [][]Call, ttl time.Duration, write float64) float64 {
|
||||
// ttl, each stream at its own model's weights (an hour's writes at Write1h):
|
||||
// a call within it of the one before reads what that one sent and writes
|
||||
// what it adds; one after it, or after a compaction, writes its whole
|
||||
// prompt again.
|
||||
func replayTTL(ss [][]Call, ttl time.Duration, hour bool, weigh Weigh) float64 {
|
||||
cost := 0.0
|
||||
for _, s := range ss {
|
||||
w := WeightsFor(s[0].Model)
|
||||
w := weigh.of(s[0].Model)
|
||||
write := w.Write
|
||||
if hour {
|
||||
write = w.Write1h
|
||||
}
|
||||
cost += float64(s[0].Prompt) * write
|
||||
for i := 1; i < len(s); i++ {
|
||||
p, c := s[i-1].Prompt, s[i].Prompt
|
||||
@@ -498,8 +517,9 @@ func replayTTL(ss [][]Call, ttl time.Duration, write float64) float64 {
|
||||
// CacheTTL advises Claude Code's cache lifetime for calls, all of the
|
||||
// main conversation or all beside it; nil when there is too little to go
|
||||
// on. current is the one set, "" when nothing sets one, and tune takes
|
||||
// it from what the calls' cache writes were kept for.
|
||||
func CacheTTL(cs []Call, current string) *TTL {
|
||||
// it from what the calls' cache writes were kept for. weigh prices the
|
||||
// calls; nil weighs them at WeightsFor.
|
||||
func CacheTTL(cs []Call, current string, weigh Weigh) *TTL {
|
||||
ss := streams(cs)
|
||||
f := observe(ss)
|
||||
if f.Calls < 50 {
|
||||
@@ -536,10 +556,9 @@ func CacheTTL(cs []Call, current string) *TTL {
|
||||
current = "1h"
|
||||
}
|
||||
}
|
||||
w := WeightsFor(cs[0].Model)
|
||||
r := &TTL{Current: current, Facts: f}
|
||||
r.Short = replayTTL(ss, 5*time.Minute, w.Write)
|
||||
r.Hour = replayTTL(ss, time.Hour, w.Write1h)
|
||||
r.Short = replayTTL(ss, 5*time.Minute, false, weigh)
|
||||
r.Hour = replayTTL(ss, time.Hour, true, weigh)
|
||||
r.Cost, r.Best, r.Low = r.Short, "5m", r.Short
|
||||
if current == "1h" {
|
||||
r.Cost = r.Hour
|
||||
|
||||
@@ -87,7 +87,7 @@ func TestCacheTTLPausesWantAnHour(t *testing.T) {
|
||||
cs := many(4, func(id string, t0 time.Time) []Call {
|
||||
return session(id, t0, 40, 30000, 3000, 0, 0, 20*time.Minute, false)
|
||||
})
|
||||
r := CacheTTL(cs, "")
|
||||
r := CacheTTL(cs, "", nil)
|
||||
if r == nil || r.Current != "5m" || r.Best != "1h" || r.Low >= r.Cost {
|
||||
t.Fatalf("got %+v, want 5m → 1h", r)
|
||||
}
|
||||
@@ -102,7 +102,7 @@ func TestCacheTTLQuickWantsFiveMinutes(t *testing.T) {
|
||||
cs := many(4, func(id string, t0 time.Time) []Call {
|
||||
return session(id, t0, 40, 30000, 3000, 0, 0, 20*time.Second, true)
|
||||
})
|
||||
r := CacheTTL(cs, "")
|
||||
r := CacheTTL(cs, "", nil)
|
||||
if r == nil || r.Current != "1h" || r.Best != "5m" {
|
||||
t.Fatalf("got %+v, want 1h (read from the writes) → 5m", r)
|
||||
}
|
||||
@@ -283,3 +283,21 @@ func TestCompactUnknownWindowCapsNothing(t *testing.T) {
|
||||
t.Fatalf("curve to %d, now %d, window %d; want 1000000, 1000000, 0", last, r.Current, r.Window)
|
||||
}
|
||||
}
|
||||
|
||||
// Calls are weighed at what Weigh says their model costs: on a provider
|
||||
// that bills an hour's cache write as a 5-minute one (Copilot, #3435) the
|
||||
// hour costs no more, so calls seconds apart are left on it, where at the
|
||||
// maker's weights (nil) they are moved to 5 minutes.
|
||||
func TestCacheTTLWeighedAtTheProvidersPrice(t *testing.T) {
|
||||
cs := many(4, func(id string, t0 time.Time) []Call {
|
||||
return session(id, t0, 40, 30000, 3000, 0, 0, 20*time.Second, true)
|
||||
})
|
||||
if r := CacheTTL(cs, "", nil); r == nil || r.Best != "5m" {
|
||||
t.Fatalf("at the maker's weights got %+v, want 1h → 5m", r)
|
||||
}
|
||||
copilot := func(string) Weights { return Weights{Read: 0.05, Write: 1.25, Write1h: 1.25, Out: 5} }
|
||||
r := CacheTTL(cs, "", copilot)
|
||||
if r == nil || r.Current != "1h" || r.Best != "1h" || r.Hour > r.Short {
|
||||
t.Fatalf("at an hour priced as 5 minutes got %+v, want it left on 1h", r)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user