Initial commit: Go agentic harness extracted from Felix
This commit is contained in:
commit
1f2c471ff9
89 files changed
+19388
No files matched your search
@@ -0,0 +1,132 @@
|
||||
package tokens
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// CalibratorStore persists Calibrator state to disk so a long-running
|
||||
// session retains its learned chars→tokens ratio across Runtime
|
||||
// reconstructions (every chat.send rebuilds the Runtime, which would
|
||||
// otherwise drop the calibration).
|
||||
//
|
||||
// Layout: one JSON file per (agentID, sessionKey) under baseDir, named
|
||||
// <agentID>__<sessionKey>.json. The double-underscore separator avoids
|
||||
// collisions because session keys are validated to be filesystem-safe at
|
||||
// the gateway boundary.
|
||||
//
|
||||
// Concurrency: the file mutex is held only around read/write. The store
|
||||
// is shared process-wide so calls from different chats don't race on the
|
||||
// same JSON file (very unlikely in practice — one session per chat — but
|
||||
// cheap to guarantee).
|
||||
type CalibratorStore struct {
|
||||
baseDir string
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// NewCalibratorStore creates a store rooted at baseDir. The directory is
|
||||
// created lazily on the first Save call.
|
||||
func NewCalibratorStore(baseDir string) *CalibratorStore {
|
||||
return &CalibratorStore{baseDir: baseDir}
|
||||
}
|
||||
|
||||
// persisted is the on-disk shape. Versioned so a future schema change can
|
||||
// be detected and ignored gracefully.
|
||||
type persisted struct {
|
||||
Version int `json:"v"`
|
||||
Ratio float64 `json:"ratio"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
const persistedVersion = 1
|
||||
|
||||
func (s *CalibratorStore) path(agentID, sessionKey string) string {
|
||||
if s == nil || s.baseDir == "" || agentID == "" || sessionKey == "" {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(s.baseDir, agentID+"__"+sessionKey+".json")
|
||||
}
|
||||
|
||||
// Load returns the persisted (ratio, count) for the given session, or
|
||||
// (1.0, 0) if no record exists. Never returns an error — corrupt or
|
||||
// missing files just yield the default, since calibration is advisory.
|
||||
func (s *CalibratorStore) Load(agentID, sessionKey string) (ratio float64, count int) {
|
||||
p := s.path(agentID, sessionKey)
|
||||
if p == "" {
|
||||
return 1.0, 0
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
data, err := os.ReadFile(p)
|
||||
if err != nil {
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
slog.Debug("calibrator load error", "path", p, "error", err)
|
||||
}
|
||||
return 1.0, 0
|
||||
}
|
||||
var rec persisted
|
||||
if jerr := json.Unmarshal(data, &rec); jerr != nil {
|
||||
slog.Debug("calibrator parse error; ignoring", "path", p, "error", jerr)
|
||||
return 1.0, 0
|
||||
}
|
||||
if rec.Version != persistedVersion || rec.Ratio <= 0 || rec.Count < 0 {
|
||||
return 1.0, 0
|
||||
}
|
||||
return rec.Ratio, rec.Count
|
||||
}
|
||||
|
||||
// Save writes the (ratio, count) for the given session via a write-rename
|
||||
// dance so a crash mid-write can't corrupt the file. No-op when the store
|
||||
// is nil or the path resolution fails.
|
||||
func (s *CalibratorStore) Save(agentID, sessionKey string, ratio float64, count int) {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
p := s.path(agentID, sessionKey)
|
||||
if p == "" {
|
||||
return
|
||||
}
|
||||
if ratio <= 0 || count <= 0 {
|
||||
// No useful information to persist yet.
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if err := os.MkdirAll(s.baseDir, 0o755); err != nil {
|
||||
slog.Warn("calibrator dir create failed", "dir", s.baseDir, "error", err)
|
||||
return
|
||||
}
|
||||
data, err := json.Marshal(persisted{Version: persistedVersion, Ratio: ratio, Count: count})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
tmp := p + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, 0o644); err != nil {
|
||||
slog.Debug("calibrator write failed", "path", tmp, "error", err)
|
||||
return
|
||||
}
|
||||
if err := os.Rename(tmp, p); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
slog.Debug("calibrator rename failed", "path", p, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Forget removes the persisted record for a session — call from the same
|
||||
// site that calls session.Store.Delete so deleted sessions don't leak
|
||||
// calibrator files into the data dir.
|
||||
func (s *CalibratorStore) Forget(agentID, sessionKey string) {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
p := s.path(agentID, sessionKey)
|
||||
if p == "" {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
_ = os.Remove(p)
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
// Package tokens provides char-based token estimation for LLM payloads
|
||||
// with a self-calibrating ratio learned from provider usage stats.
|
||||
package tokens
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
|
||||
// Estimate returns a rough token count for the given LLM payload using the
|
||||
// industry-standard chars/4 heuristic. It is intentionally cheap and free
|
||||
// of provider-specific tokenizer dependencies.
|
||||
func Estimate(msgs []llm.Message, systemPrompt string, tools []llm.ToolDef) int {
|
||||
total := len(systemPrompt)
|
||||
for _, m := range msgs {
|
||||
// Per-message framing overhead (role markers, separators) — mirrors
|
||||
// the ~3-token-per-message budget used by tiktoken-style estimators.
|
||||
total += len(m.Role) + len(m.Content) + len(m.ToolCallID) + perMessageOverhead
|
||||
for _, tc := range m.ToolCalls {
|
||||
total += len(tc.ID) + len(tc.Name) + len(tc.Input)
|
||||
}
|
||||
}
|
||||
for _, t := range tools {
|
||||
total += len(t.Name) + len(t.Description) + len(t.Parameters)
|
||||
}
|
||||
return total / 4
|
||||
}
|
||||
|
||||
// perMessageOverhead approximates the per-message framing tokens emitted by
|
||||
// every chat-style provider (role tags, separators). Expressed in characters
|
||||
// since the final divide-by-4 maps it back to tokens.
|
||||
const perMessageOverhead = 3
|
||||
|
||||
// ContextWindow returns the maximum input tokens for the given
|
||||
// "provider/model" identifier.
|
||||
//
|
||||
// For "local"/"ollama" providers, the registered ollama context (probed
|
||||
// at startup via /api/show) is used. For all other providers, lookup is
|
||||
// driven by the modelID family — not the provider prefix — so proxies
|
||||
// and relays that expose Claude/GPT/Gemini under a custom provider name
|
||||
// (e.g. "platformai/claude-sonnet-4-6-asia-southeast1", AWS Bedrock,
|
||||
// Vertex AI) still get the right window.
|
||||
//
|
||||
// When neither the registry nor the family detector matches, the
|
||||
// fallback differs by provider type:
|
||||
// - local/ollama: defaultLocalUnknownWindow (32k) — most modern small
|
||||
// models (qwen, gemma, phi, mistral) advertise 32k or larger; if
|
||||
// the probe failed, 32k is a reasonable middle ground.
|
||||
// - everything else: defaultRemoteUnknownWindow (128k) — frontier
|
||||
// models behind unknown proxies are vastly more likely to be 128k+
|
||||
// than 32k. Reactive compaction handles the rare overflow case.
|
||||
//
|
||||
// Use ContextWindowFor when an agent has an explicit per-agent override
|
||||
// (config.AgentConfig.ContextWindow). This raw form is for callers that
|
||||
// don't have agent context.
|
||||
func ContextWindow(model string) int {
|
||||
if model == "" {
|
||||
return defaultRemoteUnknownWindow
|
||||
}
|
||||
provider, modelID := splitProviderModel(model)
|
||||
|
||||
isLocal := provider == "local" || provider == "ollama"
|
||||
|
||||
// Ollama-bundled local models register their advertised window at
|
||||
// startup; honour that before falling through to family detection.
|
||||
if isLocal {
|
||||
ollamaCtxMu.RLock()
|
||||
v, ok := ollamaCtx[modelID]
|
||||
ollamaCtxMu.RUnlock()
|
||||
if ok {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
if w := windowByModelFamily(modelID); w > 0 {
|
||||
return w
|
||||
}
|
||||
|
||||
if isLocal {
|
||||
return defaultLocalUnknownWindow
|
||||
}
|
||||
return defaultRemoteUnknownWindow
|
||||
}
|
||||
|
||||
// ContextWindowFor returns the effective context window for an agent.
|
||||
// When override > 0, it wins over the auto-detected window — surfaced
|
||||
// to users as the per-agent "context window" setting for cases where
|
||||
// the auto-detection is wrong (e.g. a proxy exposing a non-standard
|
||||
// window, or a local model where you want to clamp below the advertised
|
||||
// limit to leave room for output tokens).
|
||||
func ContextWindowFor(model string, override int) int {
|
||||
if override > 0 {
|
||||
return override
|
||||
}
|
||||
return ContextWindow(model)
|
||||
}
|
||||
|
||||
// windowByModelFamily picks the context window from the model identifier
|
||||
// alone, ignoring provider prefix. This is the path that handles
|
||||
// proxies (platformai, openrouter, bedrock, vertex) where the provider
|
||||
// label doesn't match the underlying model family. modelID may itself
|
||||
// be nested (e.g. "openai/gpt-4o-2024-08-06" passed by openrouter); we
|
||||
// match on both the full id and its leaf segment.
|
||||
func windowByModelFamily(modelID string) int {
|
||||
id := strings.ToLower(modelID)
|
||||
leaf := id
|
||||
if i := strings.LastIndex(leaf, "/"); i >= 0 {
|
||||
leaf = leaf[i+1:]
|
||||
}
|
||||
switch {
|
||||
case strings.Contains(id, "claude"):
|
||||
// All current Claude chat models share a 200k window.
|
||||
return 200000
|
||||
case strings.HasPrefix(leaf, "gpt-4o"), strings.HasPrefix(leaf, "gpt-4-turbo"):
|
||||
return 128000
|
||||
case strings.HasPrefix(leaf, "gpt-4"):
|
||||
return 8192
|
||||
case strings.HasPrefix(leaf, "gpt-3.5"):
|
||||
return 16385
|
||||
case strings.Contains(id, "gemini-1.5-pro"):
|
||||
return 2000000
|
||||
case strings.Contains(id, "gemini-1.5-flash"),
|
||||
strings.Contains(id, "gemini-2"):
|
||||
return 1000000
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
const (
|
||||
// defaultLocalUnknownWindow is the fallback for local/ollama models
|
||||
// when the /api/show probe didn't register a window. 32k matches the
|
||||
// real window of most modern small models (qwen, gemma, phi-3) and
|
||||
// is conservative enough that genuinely smaller models (4k-8k legacy
|
||||
// llama variants) just hit reactive compaction instead of crashing.
|
||||
defaultLocalUnknownWindow = 32000
|
||||
// defaultRemoteUnknownWindow is the fallback for any non-local
|
||||
// provider when neither the family detector nor an explicit override
|
||||
// matches. 128k reflects that frontier models behind unknown proxies
|
||||
// (custom relays, internal gateways) are overwhelmingly 128k+ —
|
||||
// erring high here saves preventive compaction calls for the common
|
||||
// case, and reactive compaction handles the rare overflow.
|
||||
defaultRemoteUnknownWindow = 128000
|
||||
)
|
||||
|
||||
func splitProviderModel(s string) (string, string) {
|
||||
parts := strings.SplitN(s, "/", 2)
|
||||
if len(parts) == 2 {
|
||||
return parts[0], parts[1]
|
||||
}
|
||||
return "", s
|
||||
}
|
||||
|
||||
// RegisterOllamaContext records the context length advertised by an Ollama
|
||||
// model. Call this at startup after probing /api/show.
|
||||
func RegisterOllamaContext(modelID string, ctx int) {
|
||||
ollamaCtxMu.Lock()
|
||||
defer ollamaCtxMu.Unlock()
|
||||
if ollamaCtx == nil {
|
||||
ollamaCtx = make(map[string]int)
|
||||
}
|
||||
ollamaCtx[modelID] = ctx
|
||||
}
|
||||
|
||||
// ResetOllamaContexts is for tests.
|
||||
func ResetOllamaContexts() {
|
||||
ollamaCtxMu.Lock()
|
||||
defer ollamaCtxMu.Unlock()
|
||||
ollamaCtx = nil
|
||||
}
|
||||
|
||||
var (
|
||||
ollamaCtxMu sync.RWMutex
|
||||
ollamaCtx map[string]int
|
||||
)
|
||||
|
||||
// Calibrator learns a per-session multiplier between Estimate() output and
|
||||
// the provider-reported actual input tokens. Use one instance per session.
|
||||
type Calibrator struct {
|
||||
mu sync.Mutex
|
||||
ratio float64 // actual / estimated; defaults 1.0
|
||||
count int
|
||||
}
|
||||
|
||||
// NewCalibrator returns a Calibrator with ratio 1.0.
|
||||
func NewCalibrator() *Calibrator {
|
||||
return &Calibrator{ratio: 1.0}
|
||||
}
|
||||
|
||||
// Update folds a new observation into the running ratio. Both inputs must
|
||||
// be positive; bad samples are silently ignored so the calibrator does not
|
||||
// drift on the back of a single bad usage report.
|
||||
func (c *Calibrator) Update(actual, estimated int) {
|
||||
if actual <= 0 || estimated <= 0 {
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
sample := float64(actual) / float64(estimated)
|
||||
c.count++
|
||||
// Simple running mean — converges, never gets stuck on early outliers.
|
||||
c.ratio += (sample - c.ratio) / float64(c.count)
|
||||
}
|
||||
|
||||
// Adjust applies the learned ratio to a fresh estimate.
|
||||
func (c *Calibrator) Adjust(estimated int) int {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return int(float64(estimated) * c.ratio)
|
||||
}
|
||||
|
||||
// Snapshot returns the current (ratio, count) so the value can be persisted
|
||||
// across Runtime reconstructions. Both fields are read under the same lock
|
||||
// so a concurrent Update() can't tear them.
|
||||
func (c *Calibrator) Snapshot() (ratio float64, count int) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.ratio, c.count
|
||||
}
|
||||
|
||||
// Restore overwrites the calibrator's ratio + count from previously
|
||||
// snapshotted values. Used at Runtime construction to seed the calibrator
|
||||
// with whatever was learned in earlier turns of the same session — without
|
||||
// this, every chat.send rebuild loses the calibration and starts at 1.0
|
||||
// again, defeating the point of preventive compaction during the first few
|
||||
// turns of a long session.
|
||||
//
|
||||
// Bad inputs (non-positive ratio, negative count) are silently ignored so
|
||||
// a corrupt persistence file can't poison the in-memory state.
|
||||
func (c *Calibrator) Restore(ratio float64, count int) {
|
||||
if ratio <= 0 || count < 0 {
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.ratio = ratio
|
||||
c.count = count
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package tokens
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
|
||||
func TestEstimateBasic(t *testing.T) {
|
||||
msgs := []llm.Message{
|
||||
{Role: "user", Content: "hello world"}, // 11 chars
|
||||
{Role: "assistant", Content: "hi there"}, // 8 chars
|
||||
}
|
||||
got := Estimate(msgs, "", nil)
|
||||
// Total = 11 + 8 + len("user")*2 + len("assistant") + len("user") = 11 + 8 + 4 + 9 + 4 = 36
|
||||
// /4 = 9
|
||||
assert.GreaterOrEqual(t, got, 9)
|
||||
assert.LessOrEqual(t, got, 12)
|
||||
}
|
||||
|
||||
func TestEstimateWithSystemPromptAndTools(t *testing.T) {
|
||||
msgs := []llm.Message{{Role: "user", Content: "hi"}}
|
||||
tools := []llm.ToolDef{
|
||||
{Name: "read_file", Description: "read a file", Parameters: []byte(`{"type":"object"}`)},
|
||||
}
|
||||
withoutSys := Estimate(msgs, "", nil)
|
||||
withSys := Estimate(msgs, "you are a helpful assistant", tools)
|
||||
assert.Greater(t, withSys, withoutSys, "system prompt + tools should bump estimate")
|
||||
}
|
||||
|
||||
func TestContextWindowKnown(t *testing.T) {
|
||||
tests := []struct {
|
||||
model string
|
||||
want int
|
||||
}{
|
||||
{"anthropic/claude-3-5-sonnet-20241022", 200000},
|
||||
{"anthropic/claude-3-opus-20240229", 200000},
|
||||
{"anthropic/claude-3-haiku-20240307", 200000},
|
||||
{"openai/gpt-4o", 128000},
|
||||
{"openai/gpt-4o-mini", 128000},
|
||||
{"openai/gpt-4-turbo", 128000},
|
||||
{"google/gemini-1.5-pro", 2000000},
|
||||
{"google/gemini-1.5-flash", 1000000},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.model, func(t *testing.T) {
|
||||
assert.Equal(t, tc.want, ContextWindow(tc.model))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextWindowUnknownRemoteReturnsRemoteFallback(t *testing.T) {
|
||||
// Non-local unknown models default to 128k — frontier proxies are
|
||||
// overwhelmingly 128k+, and reactive compaction handles overflow.
|
||||
assert.Equal(t, 128000, ContextWindow("weird/unknown-model"))
|
||||
assert.Equal(t, 128000, ContextWindow(""))
|
||||
}
|
||||
|
||||
func TestContextWindowUnknownLocalReturnsLocalFallback(t *testing.T) {
|
||||
// Local/ollama unknown models default to 32k — conservative for
|
||||
// genuinely small models without a probed registration.
|
||||
assert.Equal(t, 32000, ContextWindow("local/some-unprobed-model"))
|
||||
assert.Equal(t, 32000, ContextWindow("ollama/some-unprobed-model"))
|
||||
}
|
||||
|
||||
func TestContextWindowForOverrideWins(t *testing.T) {
|
||||
// Per-agent override is honoured over auto-detection (e.g. when an
|
||||
// auto-detected 200k Claude is too aggressive for a slow proxy).
|
||||
assert.Equal(t, 64000, ContextWindowFor("anthropic/claude-3-opus", 64000))
|
||||
// Zero override falls through to auto-detection.
|
||||
assert.Equal(t, 200000, ContextWindowFor("anthropic/claude-3-opus", 0))
|
||||
// Negative override is ignored (treated as "no override").
|
||||
assert.Equal(t, 200000, ContextWindowFor("anthropic/claude-3-opus", -1))
|
||||
}
|
||||
|
||||
// TestContextWindowProxyProviderDetectedByModelFamily covers the case
|
||||
// where the provider prefix is a relay/proxy (platformai, openrouter,
|
||||
// bedrock, vertex) — the model family in the suffix should still drive
|
||||
// the window, not the provider label.
|
||||
func TestContextWindowProxyProviderDetectedByModelFamily(t *testing.T) {
|
||||
tests := []struct {
|
||||
model string
|
||||
want int
|
||||
}{
|
||||
{"platformai/claude-sonnet-4-6-asia-southeast1", 200000},
|
||||
{"openrouter/anthropic/claude-3-opus", 200000},
|
||||
{"bedrock/anthropic.claude-3-haiku", 200000},
|
||||
{"vertex/gemini-1.5-pro-001", 2000000},
|
||||
{"openrouter/openai/gpt-4o-2024-08-06", 128000},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.model, func(t *testing.T) {
|
||||
assert.Equal(t, tc.want, ContextWindow(tc.model))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextWindowOllamaDefault(t *testing.T) {
|
||||
// Without RegisterOllamaContext call, ollama models fall back to a sane default
|
||||
assert.Equal(t, 32000, ContextWindow("local/qwen2.5:3b-instruct"))
|
||||
}
|
||||
|
||||
func TestContextWindowOllamaRegistered(t *testing.T) {
|
||||
RegisterOllamaContext("qwen2.5:3b-instruct", 32768)
|
||||
defer ResetOllamaContexts()
|
||||
assert.Equal(t, 32768, ContextWindow("local/qwen2.5:3b-instruct"))
|
||||
assert.Equal(t, 32768, ContextWindow("ollama/qwen2.5:3b-instruct"))
|
||||
}
|
||||
|
||||
func TestCalibratorStartsAtOne(t *testing.T) {
|
||||
c := NewCalibrator()
|
||||
assert.Equal(t, 100, c.Adjust(100))
|
||||
}
|
||||
|
||||
func TestCalibratorConvergesTowardActual(t *testing.T) {
|
||||
c := NewCalibrator()
|
||||
// After 5 identical samples of (actual=150, estimated=100), the running mean
|
||||
// should reach exactly 1.5, so Adjust(100) returns 150.
|
||||
c.Update(150, 100)
|
||||
c.Update(150, 100)
|
||||
c.Update(150, 100)
|
||||
c.Update(150, 100)
|
||||
c.Update(150, 100)
|
||||
got := c.Adjust(100)
|
||||
assert.GreaterOrEqual(t, got, 148, "calibrator should learn ratio≈1.5")
|
||||
assert.LessOrEqual(t, got, 150)
|
||||
}
|
||||
|
||||
func TestCalibratorIgnoresZeroOrNegative(t *testing.T) {
|
||||
c := NewCalibrator()
|
||||
c.Update(0, 100)
|
||||
c.Update(100, 0)
|
||||
c.Update(-5, 100)
|
||||
assert.Equal(t, 100, c.Adjust(100), "bad samples must be ignored")
|
||||
}
|
||||
Reference in new issue
Block a user