返回 DeepSeek-Reasonix
context_usage.go
根目录 / internal / agent / context_usage.go
1 package agent
2
3 import "reasonix/internal/tool"
4
5 // contextUsage memoises the projected prompt size. The estimate walks every
6 // visible message, and status gauges redraw far more often than the view moves,
7 // so it is keyed on everything that can change the answer: the transcript,
8 // projection, calibration, and provider-visible tool schemas.
9 type contextUsage struct {
10 transcriptVersion uint64
11 projectionVersion uint64
12 calibration *promptTokenCalibration
13 tools *tool.Registry
14 toolSchemaRevision uint64
15 tokens int
16 }
17
18 // ContextUsedTokens is the number ContextManager compares against its
19 // thresholds: the estimated prompt size of the view the next request sends. A
20 // gauge fed from the last turn's usage instead lags a turn, counts completion
21 // tokens the trigger ignores, and reads zero on a rebound session — which is
22 // how a session displays 8% while it is compacting.
23 func (a *Agent) ContextUsedTokens() int {
24 if a == nil {
25 return 0
26 }
27 session := a.Session()
28 if session == nil {
29 return 0
30 }
31 transcriptVersion := session.TranscriptVersion()
32 projectionVersion := a.currentProjectionVersion()
33 calibration := a.sess.output.promptCalibration.Load()
34 tools := a.svc.tools
35 toolSchemaRevision := tools.SchemaRevision()
36 if cached := a.sess.output.contextUsage.Load(); cached != nil &&
37 cached.transcriptVersion == transcriptVersion &&
38 cached.projectionVersion == projectionVersion &&
39 cached.calibration == calibration &&
40 cached.tools == tools &&
41 cached.toolSchemaRevision == toolSchemaRevision {
42 return cached.tokens
43 }
44 tokens := a.estimatedVisibleRequestTokens(a.modelVisibleMessages())
45 a.sess.output.contextUsage.Store(&contextUsage{
46 transcriptVersion: transcriptVersion,
47 projectionVersion: projectionVersion,
48 calibration: calibration,
49 tools: tools,
50 toolSchemaRevision: toolSchemaRevision,
51 tokens: tokens,
52 })
53 return tokens
54 }
55
55 lines GO