feat(statestore): record a usage row for every model call

Task agent runs and MCP sampling record against their task (billed to the
task's org); gateway chat turns, titles, sampling and curators record
against the system org. Rows carry source, workflow, step, alias,
provider/model and tokens for later chargeback.
This commit is contained in:
sam committed 2026-10-10 18:32:43 +11:00
1 parent 12b9a57404
commit e4ea2eaabc
31 files changed
+1068 -322

No files matched your search

+27 -2
View File
@@ -4,18 +4,24 @@ import (
"context"
"errors"
"fmt"
"log/slog"
"time"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/ai-sdk/runtime"
"github.com/samcharles93/archie-core/internal/agentexec/modelloop"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/usage"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/tools/mcp"
)
// taskSamplingHandler answers MCP sampling requests with the task's model.
// Without a runtime or model the request is refused.
func taskSamplingHandler(llm *runtime.Runtime, cfg config.TaskConfig) mcp.SamplingHandler {
// Without a runtime or model the request is refused. record receives each
// call's model ref and token usage.
func taskSamplingHandler(llm *runtime.Runtime, cfg config.TaskConfig, record func(context.Context, string, chat.Usage)) mcp.SamplingHandler {
return func(ctx context.Context, req mcp.SamplingRequest) (mcp.SamplingResult, error) {
if llm == nil {
return mcp.SamplingResult{}, errors.New("mcp sampling: no model runtime is configured")
@@ -39,6 +45,7 @@ func taskSamplingHandler(llm *runtime.Runtime, cfg config.TaskConfig) mcp.Sampli
options.Temperature = float32(*req.Temperature)
}
result, err := llm.Chat(ctx, model, options)
record(ctx, model, result.TotalUsage)
if err != nil {
return mcp.SamplingResult{}, fmt.Errorf("mcp sampling: %w", err)
}
@@ -50,3 +57,21 @@ func taskSamplingHandler(llm *runtime.Runtime, cfg config.TaskConfig) mcp.Sampli
}, nil
}
}
// samplingUsageRecorder records a task's MCP sampling calls against the task.
// A failed write is logged, never fails the call.
func samplingUsageRecorder(store workflow.Store, t *workflow.Task, log *slog.Logger) func(context.Context, string, chat.Usage) {
return func(ctx context.Context, model string, used chat.Usage) {
if store == nil || t == nil {
return
}
record := usage.Record{
Source: usage.SourceTask, TaskID: t.ID, Attempt: t.Attempt, Workflow: t.Workflow, Step: "mcp-sampling",
InputTokens: int64(used.PromptTokens), OutputTokens: int64(used.CompletionTokens),
CachedTokens: int64(used.CachedTokens), At: time.Now().UTC(),
}.WithRef(model)
if err := store.RecordUsage(ctx, record); err != nil && log != nil {
log.Warn("record model usage failed", "model", model, "err", err)
}
}
}
+1 -1
View File
@@ -233,7 +233,7 @@ func runTask(ctx context.Context, req taskrun.Request, dependencies taskDependen
if len(req.MCPServers) > 0 {
llm = modelloop.NewRuntime(req.Providers, req.Cfg.ModelLimits)
}
mcpSet, mcpErr := startMCPProviders(ctx, req.MCPServers, taskSamplingHandler(llm, req.Cfg), log)
mcpSet, mcpErr := startMCPProviders(ctx, req.MCPServers, taskSamplingHandler(llm, req.Cfg, samplingUsageRecorder(dependencies.store, req.Task, log)), log)
if mcpSet != nil {
defer mcpSet.cleanup(ctx, log)
}
+25 -14
View File
@@ -15,6 +15,7 @@ import (
"github.com/samcharles93/archie-core/internal/agentexec/modelloop"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/domain/usage"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
@@ -39,8 +40,10 @@ type chatSetup struct {
// or model-aliases update swaps the runtime wholesale (ai-sdk's
// Runtime caches the provider instances it built), so the pointer cannot
// be captured at construction. nil means no model runtime is configured.
LLM func() *runtime.Runtime
ChatModels gateway.ModelManager
LLM func() *runtime.Runtime
ChatModels gateway.ModelManager
// Usage records each model call; nil records nothing.
Usage *usageSink
ToolReg *tools.Registry
Soul gateway.SoulSource
ChatTasks gateway.TaskCreator
@@ -129,7 +132,7 @@ func newChatTurnRunner(
Sessions: sessionStore,
Models: s.ChatModels,
Soul: s.Soul,
Model: newChatTurnModel(s.LLM, s.ToolReg, cfg.Chat.MaxSteps, s.ToolLimits, s.ProviderOutcomes),
Model: newChatTurnModel(s.LLM, s.ToolReg, cfg.Chat.MaxSteps, s.ToolLimits, s.ProviderOutcomes, s.Usage),
TaskLister: s.ChatTaskLister,
Tasks: s.ChatTasks,
TaskLogs: s.ChatTaskLogs,
@@ -191,31 +194,38 @@ func chatRepoEnv(cfg config.Config, identity string) []gateway.RepoEnv {
// and records at its own adapter (curatorLLMRunner). Anything that reaches the
// runtime without recording leaves /status reporting a stale last-known
// outcome, which is a /status that lies about the provider.
func sendChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, options core.GenerateOptions, turn gateway.TurnStream, outcomes *providerOutcomeRecorder, icons map[string]string) (string, error) {
text, err := runChatTurn(ctx, llm, chatModel, options, turn, icons)
func sendChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, options core.GenerateOptions, turn gateway.TurnStream, outcomes *providerOutcomeRecorder, usageRecords *usageSink, icons map[string]string) (string, error) {
text, used, err := runChatTurn(ctx, llm, chatModel, options, turn, icons)
usageRecords.record(ctx, usage.SourceChat, chatModel, used)
// record tolerates a nil recorder: a setup built without one (tests, a
// deployment whose health surface is unwired) still makes its calls.
outcomes.record(chatModel, err)
return text, err
}
func runChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, options core.GenerateOptions, turn gateway.TurnStream, icons map[string]string) (string, error) {
// runChatTurn returns the reply and the tokens the call used, which a
// failed call may still report.
func runChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, options core.GenerateOptions, turn gateway.TurnStream, icons map[string]string) (string, chat.Usage, error) {
if turn == nil {
result, err := llm.Chat(ctx, chatModel, options)
if err != nil {
return "", fmt.Errorf("llm chat: %w", err)
return "", result.TotalUsage, fmt.Errorf("llm chat: %w", err)
}
return result.Text, nil
return result.Text, result.TotalUsage, nil
}
stream, err := llm.ChatStream(ctx, chatModel, options)
if err != nil {
return "", fmt.Errorf("llm chat stream: %w", err)
return "", chat.Usage{}, fmt.Errorf("llm chat stream: %w", err)
}
text := drainChatStream(stream.FullStream, turn, icons)
if _, err := stream.FinishReason(); err != nil {
return "", fmt.Errorf("llm chat stream: %w", err)
var used chat.Usage
if stream.Usage != nil {
used, _ = stream.Usage()
}
return text, nil
if _, err := stream.FinishReason(); err != nil {
return "", used, fmt.Errorf("llm chat stream: %w", err)
}
return text, used, nil
}
// drainChatStream consumes a model stream to close, reporting assistant text
@@ -324,6 +334,7 @@ type chatTitleGenerator struct {
log *slog.Logger
llm func() *runtime.Runtime
chatModels gateway.ModelManager
usage *usageSink
}
// newChatTitleGenerator wires an LLM-backed title generator for a chat
@@ -333,7 +344,7 @@ func newChatTitleGenerator(s chatSetup) gateway.TitleGenerator {
if s.LLM == nil || s.ChatModels == nil {
return nil
}
return &chatTitleGenerator{log: s.Log, llm: s.LLM, chatModels: s.ChatModels}
return &chatTitleGenerator{log: s.Log, llm: s.LLM, chatModels: s.ChatModels, usage: s.Usage}
}
func (g *chatTitleGenerator) GenerateTitle(ctx context.Context, sessionID, firstMessage string) (string, error) {
@@ -357,7 +368,7 @@ func (g *chatTitleGenerator) GenerateTitle(ctx context.Context, sessionID, first
return "", fmt.Errorf("no model runtime is configured")
}
text, err := sendChatTurn(ctx, llm, g.chatModels.ActiveModel(),
core.GenerateOptions{Messages: messages, MaxSteps: 1}, nil, nil, nil)
core.GenerateOptions{Messages: messages, MaxSteps: 1}, nil, nil, g.usage, nil)
if err != nil {
if g.log != nil {
g.log.Error("session title generation failed", "session", sessionID, "err", err)
@@ -29,6 +29,7 @@ type chatTurnModel struct {
limits func() modelloop.ToolLimits
// outcomes records each call's result for /status (see sendChatTurn).
outcomes *providerOutcomeRecorder
usage *usageSink
}
func newChatTurnModel(
@@ -37,6 +38,7 @@ func newChatTurnModel(
maxSteps int,
limits func() modelloop.ToolLimits,
outcomes *providerOutcomeRecorder,
usageRecords *usageSink,
) gateway.TurnModel {
return &chatTurnModel{
llm: llm,
@@ -44,6 +46,7 @@ func newChatTurnModel(
maxSteps: maxSteps,
limits: limits,
outcomes: outcomes,
usage: usageRecords,
}
}
@@ -70,6 +73,7 @@ func (m *chatTurnModel) Prepare(
toolInfo: toolSummaries(options.Tools),
toolTokens: gateway.EstimateTokens(string(toolSchema)),
outcomes: m.outcomes,
usage: m.usage,
icons: toolIcons(m.registry),
}, nil
}
@@ -81,6 +85,7 @@ type preparedChatTurnModel struct {
toolInfo []gateway.ToolSummary
toolTokens int
outcomes *providerOutcomeRecorder
usage *usageSink
// icons maps tool name to the icon that tool registered, for chat
// surfaces to render. A nil map yields "" for every lookup, which is
// the no-icon rendering.
@@ -202,5 +207,5 @@ func (m *preparedChatTurnModel) Generate(
if m.llm == nil {
return "", fmt.Errorf("llm chat: no model runtime is configured")
}
return sendChatTurn(ctx, m.llm, m.model, options, stream, m.outcomes, m.icons)
return sendChatTurn(ctx, m.llm, m.model, options, stream, m.outcomes, m.usage, m.icons)
}
+4 -1
View File
@@ -14,6 +14,7 @@ import (
"github.com/samcharles93/archie-core/internal/app/controlplane"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/curator"
"github.com/samcharles93/archie-core/internal/domain/usage"
"github.com/samcharles93/archie-core/internal/events"
infraMemory "github.com/samcharles93/archie-core/internal/infrastructure/memory"
"github.com/samcharles93/archie-core/internal/infrastructure/sessioncurator"
@@ -34,7 +35,7 @@ func (b *server) setupCurators(ctx context.Context) {
MemoryEngines: b.memEngines,
Skills: skillcurator.NewStore(skillsRoot),
Conversations: sessioncurator.NewAdapter(b.chatSessionStore, b.cfg.BotUser),
LLM: curatorLLMRunner{llm: b.chatLLM, outcomes: b.providerOutcomes},
LLM: curatorLLMRunner{llm: b.chatLLM, outcomes: b.providerOutcomes, usage: b.usage},
Model: b.chatModels.ActiveModel(),
})
@@ -107,6 +108,7 @@ type curatorLLMRunner struct {
// provider is demonstrably reachable -- or worse, keeps showing a much
// older chat outcome as current.
outcomes *providerOutcomeRecorder
usage *usageSink
}
func (r curatorLLMRunner) Chat(ctx context.Context, req curator.ChatRequest) (curator.ChatResult, error) {
@@ -136,6 +138,7 @@ func (r curatorLLMRunner) Chat(ctx context.Context, req curator.ChatRequest) (cu
MaxSteps: max(req.MaxSteps, 1),
})
r.outcomes.record(req.Model, err)
r.usage.record(ctx, usage.SourceCurator, req.Model, res.TotalUsage)
if err != nil {
return curator.ChatResult{}, err
}
@@ -74,6 +74,10 @@ func (b *server) setupChatRuntime(ctx context.Context, cfg config.Config, actor
// later carries both: the recorder is written by sendChatTurn, the source
// is read by /status.
b.providerOutcomes = newProviderOutcomeRecorder()
b.usage = &usageSink{models: b.chatModels, log: b.log}
if b.stateStore != nil {
b.usage.store = b.stateStore
}
b.statusHealth = newStatusHealth(b)
b.setupChatTasks(cfg)
@@ -253,6 +257,7 @@ func (b *server) setupGatewayChat(ctx context.Context, actor gateway.ChatTaskAct
// The Gateway executes the web chat's turns, so it is the process
// that must record their outcomes for /status.
ProviderOutcomes: b.providerOutcomes,
Usage: b.usage,
}
router.LLM, router.LLMStream = makeChatLLMResponder(ctx, "web", setup, b.chatSessionStore, router)
router.Titles = newChatTitleGenerator(setup)
@@ -8,6 +8,7 @@ import (
"github.com/samcharles93/ai-sdk/core"
"github.com/samcharles93/archie-core/internal/agentexec/modelloop"
"github.com/samcharles93/archie-core/internal/domain/usage"
"github.com/samcharles93/archie-core/internal/tools/mcp"
)
@@ -48,6 +49,7 @@ func (b *server) mcpSamplingHandler() mcp.SamplingHandler {
// recorded for /status like every other one; a nil recorder records
// nothing.
b.providerOutcomes.record(model, err)
b.usage.record(ctx, usage.SourceChat, model, result.TotalUsage)
if err != nil {
return mcp.SamplingResult{}, fmt.Errorf("mcp sampling: %w", err)
}
+1
View File
@@ -92,6 +92,7 @@ type server struct {
curatorRegistry *curator.Registry
curatorRuntime *curator.Runtime
providerOutcomes *providerOutcomeRecorder
usage *usageSink
statusHealth gateway.HealthSource
updateService *releaseupdate.Service
+45
View File
@@ -0,0 +1,45 @@
package archiegateway
import (
"context"
"log/slog"
"time"
"github.com/samcharles93/ai-sdk/chat"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/usage"
"github.com/samcharles93/archie-core/internal/gateway"
)
const usageWriteTimeout = 5 * time.Second
// usageSink records the gateway's model calls. Chat has no org of its own
// yet, so its records belong to the system org. A nil sink records nothing.
type usageSink struct {
store usage.Recorder
models gateway.ModelManager
log *slog.Logger
}
// record appends one call's usage. It never fails the call: the write is
// detached from the caller's cancellation and a failure is only logged.
func (u *usageSink) record(ctx context.Context, source usage.Source, ref string, used chat.Usage) {
if u == nil || u.store == nil || ref == "" {
return
}
alias := ""
if u.models != nil && u.models.ActiveModel() == ref {
alias = u.models.ActiveAlias()
}
record := usage.Record{
Org: storecontract.DefaultOrgID, Source: source, Alias: alias,
InputTokens: int64(used.PromptTokens), OutputTokens: int64(used.CompletionTokens),
CachedTokens: int64(used.CachedTokens), At: time.Now().UTC(),
}.WithRef(ref)
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), usageWriteTimeout)
defer cancel()
if err := u.store.RecordUsage(ctx, record); err != nil && u.log != nil {
u.log.Warn("record model usage failed", "source", source, "model", ref, "err", err)
}
}
+4
View File
@@ -26,6 +26,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/presence"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/storepkg"
"github.com/samcharles93/archie-core/internal/domain/usage"
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
"github.com/samcharles93/archie-core/internal/infrastructure/readiness"
@@ -375,6 +376,9 @@ func (b *server) executionDeps(deps *staterpc.Deps) {
if ec, ok := b.st.(storecontract.ExecutionCanceller); ok {
deps.Canceller = ec
}
if ur, ok := b.st.(usage.Recorder); ok {
deps.Usage = ur
}
if sr, ok := b.st.(storecontract.StepReader); ok {
deps.StepReader = sr
}