chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

+233
View File
@@ -0,0 +1,233 @@
// Package token provides token estimation for LLM context window management.
//
// The primary source of truth for token counts is the model API's Usage field
// (types.TokenUsage), returned with every LLM response. This package serves as
// a supplementary estimator used in two scenarios:
//
// 1. Delta estimation — after an LLM call, new messages (assistant reply +
// tool results) are appended before the next call. The Estimator computes
// the token cost of these new messages so the engine can decide whether
// context compression is needed without making an extra API round-trip.
//
// 2. First-round fallback — on the very first round of a session, no prior
// API Usage is available, so the Estimator provides a full estimate.
//
// The encoding used (cl100k_base) is an approximation. Different model families
// use different tokenizers, so the numbers will not be exact for non-OpenAI
// models. This is acceptable because the estimate only needs to be close enough
// to trigger compression at roughly the right time; over- or under-estimating
// by a small margin is corrected on the next API call.
package token
import (
"encoding/json"
"fmt"
"math"
"strings"
"sync/atomic"
"academy/internal/models/chat"
"github.com/tiktoken-go/tokenizer"
)
const (
perMessageOverhead = 3
perConversationTail = 3
perToolCallOverhead = 4
perToolDefOverhead = 8
// estimatedImageTokens is the assumed cost of one image. Providers bill
// images by tile count, so neither the URL nor the base64 blob is any
// guide: a short https:// link and a megabyte data URI can cost the same.
// 1200 tokens is ~4800 characters at the usual 4-chars-per-token heuristic.
estimatedImageTokens = 1200
)
// Scale bounds. cl100k counts Chinese at about one token a character, where
// Qwen and DeepSeek spend about 0.6, so a scale near the floor is expected for
// Chinese sessions on those models. Anything outside the bounds says more
// about a provider's usage report than about its tokenizer.
const (
MinScale = 0.5
MaxScale = 1.5
)
// Estimator counts tokens for messages and strings using BPE tokenization.
// It is intended for incremental (delta) estimation between LLM calls; the
// authoritative token count comes from the API's Usage response.
//
// cl100k is not the provider's tokenizer, so text counts are multiplied by a
// scale learned from the provider's own counts (see SetScale). Every budget an
// estimate is compared with is in provider tokens, so one scaled estimator
// keeps them all consistent: history loading, the compaction trigger, and
// compaction's own cut point and summarizer budget.
type Estimator struct {
codec tokenizer.Codec
// scale holds float64 bits. The engine recalibrates between rounds, which
// must not race an estimate a tool is still taking.
scale atomic.Uint64
}
// NewEstimator creates a token estimator using the cl100k_base encoding, at
// scale 1.
func NewEstimator() (*Estimator, error) {
codec, err := tokenizer.Get(tokenizer.Cl100kBase)
if err != nil {
return nil, fmt.Errorf("token: failed to initialize tokenizer: %w", err)
}
e := &Estimator{codec: codec}
e.SetScale(1)
return e, nil
}
// Scale is the factor text counts are multiplied by.
func (e *Estimator) Scale() float64 {
return math.Float64frombits(e.scale.Load())
}
// SetScale sets the factor text counts are multiplied by, clamped to
// [MinScale, MaxScale]. A non-positive scale means uncalibrated, which is 1.
func (e *Estimator) SetScale(scale float64) {
if scale <= 0 || math.IsNaN(scale) {
scale = 1
}
scale = min(max(scale, MinScale), MaxScale)
e.scale.Store(math.Float64bits(scale))
}
// Unscaled returns an estimator with the same tokenizer at scale 1, for
// measuring the raw count a scale is derived from.
func (e *Estimator) Unscaled() *Estimator {
u := &Estimator{codec: e.codec}
u.SetScale(1)
return u
}
// EstimateMessages returns the estimated token count for a slice of messages.
// Prefer using API Usage for the full context and this method only for deltas.
func (e *Estimator) EstimateMessages(messages []chat.Message) int {
total := 0
for i := range messages {
total += e.EstimateMessage(&messages[i])
}
total += perConversationTail
return total
}
// EstimateString returns the token count for a string using BPE tokenization.
func (e *Estimator) EstimateString(s string) int {
if len(s) == 0 {
return 0
}
count := (len(s) + 3) / 4
if ids, _, err := e.codec.Encode(s); err == nil {
count = len(ids)
}
if scale := e.Scale(); scale != 1 {
return int(math.Round(float64(count) * scale))
}
return count
}
// EstimateMessage returns the token count for a single message.
//
// Every field that goes out on the wire has to be counted here, including the
// ones that are easy to forget. Reasoning content is the expensive one:
// thinking models (DeepSeek V3.2/V4, MiMo) require the previous turns'
// reasoning_content to be sent back verbatim, and it is typically several times
// longer than the visible reply. Omitting it made a 130k context measure as
// 26k — compaction then cut in the wrong place, freed almost nothing, and ran
// again the next round. Reasoning content is counted alongside text and tool
// calls for that reason.
//
// The reasoning artifacts that travel with it are counted too. They are opaque
// to us but not to the provider's billing: an Anthropic thinking signature is a
// few hundred base64 characters, and an OpenAI Responses encrypted reasoning
// item (or an OpenRouter reasoning_details blob) is several kilobytes replayed
// on every assistant turn. Leaving them out reproduces exactly the
// under-measurement described above, one replayed turn at a time.
func (e *Estimator) EstimateMessage(msg *chat.Message) int {
tokens := perMessageOverhead
tokens += e.EstimateString(msg.Role)
tokens += e.EstimateString(msg.Content)
tokens += e.EstimateString(msg.Name)
tokens += e.EstimateString(msg.ToolCallID)
tokens += e.EstimateString(msg.ReasoningContent)
tokens += e.EstimateReasoningArtifacts(msg)
tokens += e.estimateImageParts(msg)
for _, tc := range msg.ToolCalls {
tokens += e.EstimateString(tc.Function.Name)
tokens += e.EstimateString(tc.Function.Arguments)
tokens += e.estimateProviderMetadata(tc.ProviderMetadata)
tokens += perToolCallOverhead
}
return tokens
}
// EstimateReasoningArtifacts counts the opaque provider state replayed with an
// assistant turn. The signature carries a protocol tag that is stripped before
// it goes out, so only the payload after the tag is billed; the metadata is
// sent as-is, one JSON value per namespace key.
func (e *Estimator) EstimateReasoningArtifacts(msg *chat.Message) int {
tokens := 0
if sig := msg.ReasoningSignature; sig != "" {
if _, payload, found := strings.Cut(sig, ":"); found {
sig = payload
}
tokens += e.EstimateString(sig)
}
tokens += e.estimateProviderMetadata(msg.ReasoningMetadata)
return tokens
}
// estimateProviderMetadata counts one opaque provider-state map, one JSON
// value per namespace key, the way it goes out on the wire.
//
// The same accounting applies per tool call as it does per turn: a Gemini
// thought signature and an OpenAI Responses item id ride on the tool call, not
// on the message, and are replayed on every subsequent turn. A signature runs
// to kilobytes, so a round of parallel calls left uncounted under-measures the
// context exactly the way the missing reasoning content did.
func (e *Estimator) estimateProviderMetadata(md map[string]json.RawMessage) int {
tokens := 0
for key, raw := range md {
tokens += e.EstimateString(key)
tokens += e.EstimateString(string(raw))
}
return tokens
}
// estimateImageParts counts multimodal content. MultiContent is the assembled
// representation actually sent to the provider, so when it is present the raw
// Images list is the same pictures counted a second time.
func (e *Estimator) estimateImageParts(msg *chat.Message) int {
if len(msg.MultiContent) == 0 {
return len(msg.Images) * estimatedImageTokens
}
tokens := 0
for _, part := range msg.MultiContent {
if part.ImageURL != nil || part.Type == "image_url" {
tokens += estimatedImageTokens
continue
}
tokens += e.EstimateString(part.Text)
}
return tokens
}
// EstimateTools returns the token cost of the tool schemas sent with every
// request. They are part of the prompt the provider bills. They are not part
// of the compaction trigger, which estimates messages only; use this for
// diagnostics and request-budget clamping, not for ShouldCompact.
func (e *Estimator) EstimateTools(tools []chat.Tool) int {
total := 0
for _, tool := range tools {
total += e.EstimateString(tool.Function.Name)
total += e.EstimateString(tool.Function.Description)
total += e.EstimateString(string(tool.Function.Parameters))
total += perToolDefOverhead
}
return total
}
+178
View File
@@ -0,0 +1,178 @@
package token
import (
"fmt"
"math"
"strings"
"testing"
"academy/internal/models/chat"
"github.com/stretchr/testify/assert"
)
func TestEstimator(t *testing.T) {
e, err := NewEstimator()
if err != nil {
t.Fatalf("Failed to create estimator: %v", err)
}
t.Run("empty string", func(t *testing.T) {
assert.Equal(t, 0, e.EstimateString(""))
})
t.Run("english text", func(t *testing.T) {
tokens := e.EstimateString("hello world")
assert.Equal(t, 2, tokens)
})
t.Run("chinese text", func(t *testing.T) {
tokens := e.EstimateString("你好世界测试数据中文")
fmt.Println(tokens)
assert.Greater(t, tokens, 0)
})
t.Run("CJK produces more tokens per char than latin", func(t *testing.T) {
latin := strings.Repeat("a", 100)
cjk := strings.Repeat("中", 100)
latinTokens := e.EstimateString(latin)
cjkTokens := e.EstimateString(cjk)
fmt.Println(latinTokens, cjkTokens)
assert.Greater(t, cjkTokens, latinTokens,
"CJK text should produce more tokens per character")
})
t.Run("message estimation includes overhead", func(t *testing.T) {
msg := chat.Message{
Role: "assistant",
Content: "hello",
}
tokens := e.EstimateMessage(&msg)
contentTokens := e.EstimateString("hello")
fmt.Println(tokens, contentTokens)
assert.Greater(t, tokens, contentTokens,
"message tokens should include overhead beyond just content")
})
t.Run("message with tool calls", func(t *testing.T) {
msg := chat.Message{
Role: "assistant",
Content: "thinking...",
ToolCalls: []chat.ToolCall{
{
Function: chat.FunctionCall{
Name: "knowledge_search",
Arguments: `{"query": "test"}`,
},
},
},
}
tokens := e.EstimateMessage(&msg)
assert.Greater(t, tokens, 10)
})
t.Run("estimate messages", func(t *testing.T) {
messages := []chat.Message{
{Role: "system", Content: "You are a helpful assistant."},
{Role: "user", Content: "Hello"},
{Role: "assistant", Content: "Hi there!"},
}
tokens := e.EstimateMessages(messages)
assert.Greater(t, tokens, 10)
})
}
// Thinking models (DeepSeek V3.2/V4, MiMo) require prior reasoning_content to
// be sent back verbatim, and it typically dwarfs the visible reply. Leaving it
// out of the estimate made a 130k context measure as 26k, so compaction cut in
// the wrong place, freed almost nothing, and ran again every round.
func TestEstimateMessageCountsReasoningContent(t *testing.T) {
e, err := NewEstimator()
assert.NoError(t, err)
reasoning := strings.Repeat("let me think about this step by step. ", 200)
plain := chat.Message{Role: "assistant", Content: "short answer"}
thinking := chat.Message{Role: "assistant", Content: "short answer", ReasoningContent: reasoning}
assert.Greater(t, e.EstimateMessage(&thinking), e.EstimateMessage(&plain)+1000,
"reasoning content must be counted, it is sent on the wire")
assert.InDelta(t, e.EstimateString(reasoning),
e.EstimateMessage(&thinking)-e.EstimateMessage(&plain), 2)
}
// Providers bill images by tile count, so neither a short https:// URL nor a
// megabyte data URI says anything useful about the cost.
func TestEstimateMessageCountsImages(t *testing.T) {
e, err := NewEstimator()
assert.NoError(t, err)
withImages := chat.Message{Role: "user", Content: "what is this", Images: []string{"https://x/a.png"}}
assert.Greater(t, e.EstimateMessage(&withImages), estimatedImageTokens)
multi := chat.Message{Role: "user", MultiContent: []chat.MessageContentPart{
{Type: "text", Text: "describe"},
{Type: "image_url", ImageURL: &chat.ImageURL{URL: "data:image/png;base64,AAAA"}},
}}
assert.Greater(t, e.EstimateMessage(&multi), estimatedImageTokens)
// MultiContent is the representation actually sent; counting Images too
// would bill the same picture twice.
both := chat.Message{
Role: "user",
Images: []string{"https://x/a.png"},
MultiContent: multi.MultiContent,
}
assert.Equal(t, e.EstimateMessage(&multi), e.EstimateMessage(&both))
}
// Tool schemas are part of the billed prompt but never appear in the message
// list, so omitting them biases every estimate low by a constant.
func TestEstimateTools(t *testing.T) {
e, err := NewEstimator()
assert.NoError(t, err)
assert.Zero(t, e.EstimateTools(nil))
tools := []chat.Tool{{
Type: "function",
Function: chat.FunctionDef{
Name: "shell_exec",
Description: strings.Repeat("run a shell command in the sandbox. ", 20),
Parameters: []byte(`{"type":"object","properties":{"command":{"type":"string"}}}`),
},
}}
assert.Greater(t, e.EstimateTools(tools), 100)
}
// Text counts carry the provider's scale; per-message overhead and the fixed
// image cost do not, since they are not text the provider tokenizes.
func TestEstimatorScalesTextOnly(t *testing.T) {
e, err := NewEstimator()
assert.NoError(t, err)
text := strings.Repeat("知识库文档检索结果,", 100)
raw := e.EstimateString(text)
e.SetScale(0.6)
assert.InDelta(t, float64(raw)*0.6, float64(e.EstimateString(text)), 1)
assert.Equal(t, raw, e.Unscaled().EstimateString(text), "Unscaled measures the raw count")
msg := chat.Message{Role: "user", Content: text}
withoutText := chat.Message{Role: "user"}
assert.InDelta(t, float64(raw)*0.6,
float64(e.EstimateMessage(&msg)-e.EstimateMessage(&withoutText)), 1)
}
// The scale is clamped: outside the bounds it says more about a provider's
// usage report than about its tokenizer. Unset or invalid means uncalibrated.
func TestEstimatorScaleIsClamped(t *testing.T) {
e, err := NewEstimator()
assert.NoError(t, err)
assert.Equal(t, 1.0, e.Scale())
e.SetScale(0.1)
assert.Equal(t, MinScale, e.Scale())
e.SetScale(9)
assert.Equal(t, MaxScale, e.Scale())
e.SetScale(0)
assert.Equal(t, 1.0, e.Scale())
e.SetScale(math.NaN())
assert.Equal(t, 1.0, e.Scale())
}
@@ -0,0 +1,127 @@
package token
import (
"encoding/json"
"strings"
"testing"
"academy/internal/models/chat"
"academy/internal/types"
)
// TestEstimateMessageCountsReasoningArtifacts pins the fix for the compaction
// trigger under-measuring replayed assistant turns. An OpenAI Responses
// encrypted reasoning item or an Anthropic signature rides on every replayed
// assistant message; leaving it out of the estimate is the same class of bug
// the package comment describes for reasoning_content.
func TestEstimateMessageCountsReasoningArtifacts(t *testing.T) {
est, err := NewEstimator()
if err != nil {
t.Fatalf("NewEstimator: %v", err)
}
plain := chat.Message{Role: "assistant", Content: "ok"}
blob, err := json.Marshal([]string{strings.Repeat("QUJDRA", 800)})
if err != nil {
t.Fatalf("marshal: %v", err)
}
withArtifacts := plain
withArtifacts.ReasoningSignature = "anthropic-messages:" + strings.Repeat("c2ln", 200)
withArtifacts.ReasoningMetadata = types.ProviderMetadata{"openai_responses_reasoning": blob}
base := est.EstimateMessage(&plain)
full := est.EstimateMessage(&withArtifacts)
if full <= base {
t.Fatalf("reasoning artifacts not counted: base=%d full=%d", base, full)
}
// The blobs are kilobytes, so the delta must be substantial rather than
// the handful of tokens a key name alone would add.
if delta := full - base; delta < 500 {
t.Errorf("artifact cost looks under-counted: delta=%d", delta)
}
}
// TestEstimateReasoningArtifactsSkipsProtocolTag checks the stored signature's
// "<protocol>:" prefix is not billed: api.SignatureFor strips it before the
// signature goes out on the wire.
func TestEstimateReasoningArtifactsSkipsProtocolTag(t *testing.T) {
est, err := NewEstimator()
if err != nil {
t.Fatalf("NewEstimator: %v", err)
}
payload := strings.Repeat("c2ln", 50)
tagged := &chat.Message{Role: "assistant", ReasoningSignature: "anthropic-messages:" + payload}
untagged := &chat.Message{Role: "assistant", ReasoningSignature: payload}
if got, want := est.EstimateReasoningArtifacts(tagged), est.EstimateReasoningArtifacts(untagged); got != want {
t.Errorf("protocol tag billed: tagged=%d untagged=%d", got, want)
}
}
// TestEstimateReasoningArtifactsEmpty keeps the common case free of cost.
func TestEstimateReasoningArtifactsEmpty(t *testing.T) {
est, err := NewEstimator()
if err != nil {
t.Fatalf("NewEstimator: %v", err)
}
if got := est.EstimateReasoningArtifacts(&chat.Message{Role: "user", Content: "hi"}); got != 0 {
t.Errorf("expected 0 for a message without artifacts, got %d", got)
}
}
// Gemini thought signatures and OpenAI Responses item ids ride on the tool
// call, not on the message, and are replayed on every later turn. Counting
// only name+arguments under-measured a parallel tool round by kilobytes —
// the same failure mode as the message-level artifacts above.
func TestEstimateMessageCountsToolCallProviderMetadata(t *testing.T) {
est, err := NewEstimator()
if err != nil {
t.Fatalf("NewEstimator: %v", err)
}
signature, err := json.Marshal(strings.Repeat("CtoBCr8B", 400))
if err != nil {
t.Fatalf("marshal: %v", err)
}
call := chat.ToolCall{
ID: "call_1", Type: "function",
Function: chat.FunctionCall{Name: "search", Arguments: `{"q":"x"}`},
}
plain := chat.Message{Role: "assistant", ToolCalls: []chat.ToolCall{call}}
withMetadata := call
withMetadata.ProviderMetadata = types.ToolCallMetadata{"thought_signature": signature}
annotated := chat.Message{Role: "assistant", ToolCalls: []chat.ToolCall{withMetadata}}
base := est.EstimateMessage(&plain)
full := est.EstimateMessage(&annotated)
if full <= base {
t.Fatalf("tool-call provider metadata not counted: base=%d full=%d", base, full)
}
// It must be accounted like the message-level artifacts: the payload, not
// just the namespace key.
if delta := full - base; delta < 500 {
t.Errorf("tool-call metadata looks under-counted: delta=%d", delta)
}
}
// Every call in a parallel round carries its own signature, so the cost has
// to scale with the number of calls.
func TestEstimateMessageCountsMetadataPerToolCall(t *testing.T) {
est, err := NewEstimator()
if err != nil {
t.Fatalf("NewEstimator: %v", err)
}
md := types.ToolCallMetadata{"thought_signature": json.RawMessage(`"` + strings.Repeat("CtoB", 200) + `"`)}
call := chat.ToolCall{
ID: "c", Type: "function",
Function: chat.FunctionCall{Name: "f", Arguments: "{}"}, ProviderMetadata: md,
}
one := chat.Message{Role: "assistant", ToolCalls: []chat.ToolCall{call}}
two := chat.Message{Role: "assistant", ToolCalls: []chat.ToolCall{call, call}}
single := est.EstimateMessage(&one) - est.EstimateMessage(&chat.Message{Role: "assistant"})
double := est.EstimateMessage(&two) - est.EstimateMessage(&chat.Message{Role: "assistant"})
if double < single*2-perToolCallOverhead {
t.Errorf("metadata counted once for a parallel round: single=%d double=%d", single, double)
}
}