Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

fix(ai): record patrol and QuickAnalysis token usage in cost store for budget enforcement

rcourtmand85296469618
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index cf82978f11..34d0565f8a 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -689,7 +689,12 @@ func (s *Service) ExecutePatrolStream(ctx context.Context, req PatrolRequest, ca
log.Warn().Err(saveErr).Msg("Failed to save patrol message after error")
}
}
- return nil, err
+ // Return a partial response with accumulated token counts so callers
+ // can still record usage for budget tracking even on failure.
+ return &PatrolResponse{
+ InputTokens: tempLoop.GetTotalInputTokens(),
+ OutputTokens: tempLoop.GetTotalOutputTokens(),
+ }, err
}
// Save result messages
diff --git a/internal/ai/patrol_ai.go b/internal/ai/patrol_ai.go
index bcaf316918..ee889167a7 100644
--- a/internal/ai/patrol_ai.go
+++ b/internal/ai/patrol_ai.go
@@ -13,8 +13,10 @@ import (
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/baseline"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/cost"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/memory"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/tools"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rs/zerolog/log"
)
@@ -430,6 +432,11 @@ func (p *PatrolService) runAIAnalysis(ctx context.Context, state models.StateSna
})
if chatErr != nil {
+ // Record partial token usage even on failure so budget enforcement
+ // stays accurate for tokens consumed before the error.
+ if chatResp != nil {
+ p.recordPatrolUsage("patrol", chatResp.InputTokens, chatResp.OutputTokens)
+ }
if !noStream {
p.setStreamPhase("idle")
p.broadcast(PatrolStreamEvent{Type: "error", Content: chatErr.Error()})
@@ -444,6 +451,9 @@ func (p *PatrolService) runAIAnalysis(ctx context.Context, state models.StateSna
inputTokens = chatResp.InputTokens
outputTokens = chatResp.OutputTokens
+ // Record patrol token usage for cost tracking and budget enforcement
+ p.recordPatrolUsage("patrol", inputTokens, outputTokens)
+
// Clean thinking tokens
finalContent = CleanThinkingTokens(finalContent)
@@ -732,6 +742,10 @@ func (p *PatrolService) runEvaluationPass(ctx context.Context, adapter *patrolFi
})
if err != nil {
+ // Record partial token usage even on failure
+ if resp != nil {
+ p.recordPatrolUsage("patrol-eval", resp.InputTokens, resp.OutputTokens)
+ }
log.Warn().Err(err).Msg("AI Patrol: Evaluation pass failed")
return nil, err
}
@@ -741,9 +755,35 @@ func (p *PatrolService) runEvaluationPass(ctx context.Context, adapter *patrolFi
Int("output_tokens", resp.OutputTokens).
Msg("AI Patrol: Evaluation pass complete")
+ // Record evaluation pass token usage for cost tracking
+ p.recordPatrolUsage("patrol-eval", resp.InputTokens, resp.OutputTokens)
+
return resp, nil
}
+// recordPatrolUsage records token usage from a patrol or evaluation pass into the cost store.
+func (p *PatrolService) recordPatrolUsage(useCase string, inputTokens, outputTokens int) {
+ if p.aiService == nil || (inputTokens == 0 && outputTokens == 0) {
+ return
+ }
+ patrolModel := ""
+ if cfg := p.aiService.GetAIConfig(); cfg != nil {
+ patrolModel = cfg.GetPatrolModel()
+ if patrolModel == "" {
+ patrolModel = cfg.GetChatModel()
+ }
+ }
+ providerName, _ := config.ParseModelString(patrolModel)
+ p.aiService.RecordUsage(cost.UsageEvent{
+ Timestamp: time.Now(),
+ Provider: providerName,
+ RequestModel: patrolModel,
+ UseCase: useCase,
+ InputTokens: inputTokens,
+ OutputTokens: outputTokens,
+ })
+}
+
// buildEvalSystemPrompt returns the system prompt for the evaluation pass.
func buildEvalSystemPrompt() string {
return `You are a patrol evaluation agent reviewing infrastructure signals that were
diff --git a/internal/ai/service.go b/internal/ai/service.go
index a9c4711da6..a090644edf 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -293,6 +293,17 @@ func (s *Service) CheckBudget(useCase string) error {
return s.enforceBudget(useCase)
}
+// RecordUsage records a token usage event in the cost store for budget tracking.
+// This should be called by any code path that consumes LLM tokens (patrol, investigations, etc.).
+func (s *Service) RecordUsage(event cost.UsageEvent) {
+ s.mu.RLock()
+ store := s.costStore
+ s.mu.RUnlock()
+ if store != nil {
+ store.Record(event)
+ }
+}
+
// SetStateProvider sets the state provider for infrastructure context
func (s *Service) SetStateProvider(sp StateProvider) {
s.mu.Lock()
@@ -1254,6 +1265,22 @@ func (s *Service) QuickAnalysis(ctx context.Context, prompt string) (string, err
return "", fmt.Errorf("Pulse Assistant analysis failed: %w", err)
}
+ // Record token usage for cost tracking
+ if resp.InputTokens > 0 || resp.OutputTokens > 0 {
+ providerName, _ := config.ParseModelString(model)
+ if providerName == "" || model == "" {
+ providerName = provider.Name()
+ }
+ s.RecordUsage(cost.UsageEvent{
+ Timestamp: time.Now(),
+ Provider: providerName,
+ RequestModel: model,
+ UseCase: "patrol",
+ InputTokens: resp.InputTokens,
+ OutputTokens: resp.OutputTokens,
+ })
+ }
+
if resp.Content == "" {
return "", fmt.Errorf("Pulse Assistant returned empty response")
}
diff --git a/internal/api/chat_service_adapter.go b/internal/api/chat_service_adapter.go
index c609286f57..6844f9d2eb 100644
--- a/internal/api/chat_service_adapter.go
+++ b/internal/api/chat_service_adapter.go
@@ -42,6 +42,14 @@ func (a *chatServiceAdapter) ExecutePatrolStream(ctx context.Context, req ai.Pat
MaxTotalTokens: req.MaxTotalTokens,
}, adaptCallback(callback))
if err != nil {
+ // Propagate partial response (with token counts) alongside the error
+ // so callers can still record usage for budget tracking on failure.
+ if resp != nil {
+ return &ai.PatrolStreamResponse{
+ InputTokens: resp.InputTokens,
+ OutputTokens: resp.OutputTokens,
+ }, err
+ }
return nil, err
}
return &ai.PatrolStreamResponse{