|
| 1 | +package cogito |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "sync/atomic" |
| 6 | + |
| 7 | + "github.com/sashabaranov/go-openai" |
| 8 | +) |
| 9 | + |
| 10 | +// usageCounter accumulates token usage across every LLM call routed through a |
| 11 | +// countingLLM. Safe for concurrent use (sub-agents run in their own goroutines, |
| 12 | +// each with its own counter, but streaming delivery may add from a goroutine). |
| 13 | +type usageCounter struct { |
| 14 | + prompt atomic.Int64 |
| 15 | + completion atomic.Int64 |
| 16 | + total atomic.Int64 |
| 17 | +} |
| 18 | + |
| 19 | +func (c *usageCounter) add(u LLMUsage) { |
| 20 | + c.prompt.Add(int64(u.PromptTokens)) |
| 21 | + c.completion.Add(int64(u.CompletionTokens)) |
| 22 | + c.total.Add(int64(u.TotalTokens)) |
| 23 | +} |
| 24 | + |
| 25 | +func (c *usageCounter) snapshot() LLMUsage { |
| 26 | + return LLMUsage{ |
| 27 | + PromptTokens: int(c.prompt.Load()), |
| 28 | + CompletionTokens: int(c.completion.Load()), |
| 29 | + TotalTokens: int(c.total.Load()), |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +// countingLLM wraps an LLM, accumulating token usage from every call into |
| 34 | +// counter. CreateChatCompletion returns usage directly; Ask discards it from |
| 35 | +// its signature but records it on the returned fragment's Status.LastUsage, |
| 36 | +// which is where we read it. |
| 37 | +type countingLLM struct { |
| 38 | + LLM |
| 39 | + counter *usageCounter |
| 40 | +} |
| 41 | + |
| 42 | +func (c *countingLLM) CreateChatCompletion(ctx context.Context, req openai.ChatCompletionRequest) (LLMReply, LLMUsage, error) { |
| 43 | + reply, usage, err := c.LLM.CreateChatCompletion(ctx, req) |
| 44 | + if err == nil { |
| 45 | + c.counter.add(usage) |
| 46 | + } |
| 47 | + return reply, usage, err |
| 48 | +} |
| 49 | + |
| 50 | +// Ask recovers per-call usage from the returned fragment's Status.LastUsage, |
| 51 | +// which every cogito Ask implementation (and the test mock) refreshes on each |
| 52 | +// call. If a future Ask returned a fragment carrying a stale LastUsage, this |
| 53 | +// would re-add it — the assumption is that Ask always sets LastUsage fresh. |
| 54 | +func (c *countingLLM) Ask(ctx context.Context, f Fragment) (Fragment, error) { |
| 55 | + res, err := c.LLM.Ask(ctx, f) |
| 56 | + if err == nil && res.Status != nil { |
| 57 | + c.counter.add(res.Status.LastUsage) |
| 58 | + } |
| 59 | + return res, err |
| 60 | +} |
| 61 | + |
| 62 | +// countingStreamingLLM preserves StreamingLLM so wrapping does not disable the |
| 63 | +// streaming code path for callers that use it. Usage is accumulated from the |
| 64 | +// StreamEventDone event's Usage field. |
| 65 | +// |
| 66 | +// NOTE: cogito's bundled clients (clients/openai_client.go, clients/localai_client.go) |
| 67 | +// do not currently populate StreamEvent.Usage on the done event, so streaming-path |
| 68 | +// token accumulation is zero in production until those clients request usage from |
| 69 | +// the API (e.g. StreamOptions{IncludeUsage: true}). The non-streaming path |
| 70 | +// (CreateChatCompletion / Ask) is fully counted. |
| 71 | +type countingStreamingLLM struct { |
| 72 | + countingLLM |
| 73 | + streaming StreamingLLM |
| 74 | +} |
| 75 | + |
| 76 | +func (c *countingStreamingLLM) CreateChatCompletionStream(ctx context.Context, req openai.ChatCompletionRequest) (<-chan StreamEvent, error) { |
| 77 | + in, err := c.streaming.CreateChatCompletionStream(ctx, req) |
| 78 | + if err != nil { |
| 79 | + return nil, err |
| 80 | + } |
| 81 | + // Buffer to match the client convention (clients/openai_client.go) and make |
| 82 | + // the forward context-aware so a stopped consumer cannot leak this goroutine. |
| 83 | + out := make(chan StreamEvent, 64) |
| 84 | + go func() { |
| 85 | + defer close(out) |
| 86 | + for ev := range in { |
| 87 | + if ev.Type == StreamEventDone { |
| 88 | + c.counter.add(ev.Usage) |
| 89 | + } |
| 90 | + select { |
| 91 | + case out <- ev: |
| 92 | + case <-ctx.Done(): |
| 93 | + return |
| 94 | + } |
| 95 | + } |
| 96 | + }() |
| 97 | + return out, nil |
| 98 | +} |
| 99 | + |
| 100 | +// newCountingLLM wraps llm so token usage accumulates into counter. When llm is |
| 101 | +// streaming-capable, the returned wrapper is too, so the streaming path is |
| 102 | +// preserved. |
| 103 | +func newCountingLLM(llm LLM, counter *usageCounter) LLM { |
| 104 | + base := countingLLM{LLM: llm, counter: counter} |
| 105 | + if s, ok := llm.(StreamingLLM); ok { |
| 106 | + return &countingStreamingLLM{countingLLM: base, streaming: s} |
| 107 | + } |
| 108 | + return &base |
| 109 | +} |
0 commit comments