diff --git a/tokens/tokens.go b/tokens/tokens.go index 6dd7904..a0c3468 100644 --- a/tokens/tokens.go +++ b/tokens/tokens.go @@ -21,6 +21,10 @@ func Estimate(msgs []llm.Message, systemPrompt string, tools []llm.ToolDef) int for _, tc := range m.ToolCalls { total += len(tc.ID) + len(tc.Name) + len(tc.Input) } + // Images are not part of Content (Images is json:"-"); approximate + // each attached image's token cost. perImageTokens is expressed in + // tokens, so multiply by 4 to survive the final divide-by-4. + total += len(m.Images) * perImageTokens * 4 } for _, t := range tools { total += len(t.Name) + len(t.Description) + len(t.Parameters) @@ -33,6 +37,12 @@ func Estimate(msgs []llm.Message, systemPrompt string, tools []llm.ToolDef) int // since the final divide-by-4 maps it back to tokens. const perMessageOverhead = 3 +// perImageTokens approximates the token cost of one attached image. Vision +// models bill images by tiles/resolution; ~1500 tokens is a deliberately +// conservative flat estimate so image-heavy sessions trigger preventive +// compaction rather than hitting a reactive overflow. +const perImageTokens = 1500 + // ContextWindow returns the maximum input tokens for the given // "provider/model" identifier. // diff --git a/tokens/tokens_test.go b/tokens/tokens_test.go index 41cb69a..d70a145 100644 --- a/tokens/tokens_test.go +++ b/tokens/tokens_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/sausheong/harness/llm" ) @@ -97,6 +98,17 @@ func TestContextWindowProxyProviderDetectedByModelFamily(t *testing.T) { } } +func TestEstimate_CountsImages(t *testing.T) { + textOnly := []llm.Message{{Role: "user", Content: "hello"}} + withImg := []llm.Message{{Role: "user", Content: "hello", Images: []llm.ImageContent{ + {MimeType: "image/png", Data: []byte("x")}, + {MimeType: "image/png", Data: []byte("y")}, + }}} + base := Estimate(textOnly, "", nil) + withImages := Estimate(withImg, "", nil) + require.GreaterOrEqual(t, withImages-base, 2*perImageTokens) +} + 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"))