Model usage was recorded per call and never read, so an org could not see what it spent. Add the read side: - model_usage carries identity_id. Task calls take it from the task row, chat and curator calls from the calling principal carried in the usage record, so an outbox replay keeps its attribution. Existing task rows are backfilled from tasks. - StatsService.UsageTotals sums the caller org's rows by UTC day, source, provider, model and identity. The org comes from the principal, with no org parameter, so cross-org reads do not exist. - GET /api/usage prices tokens at the catalog's list rate, netting cache hits, and reports calls to unpriced models as tokens only. The published catalog view now carries each model's cost. - A new org Usage page behind a read_usage grant: admin and owner only, with a 7, 30 or 90 day range, totals, the daily series, and model, source and identity breakdowns. The org shell keeps it on the caller's own org.
86 lines
3.1 KiB
Go
86 lines
3.1 KiB
Go
package taskmcp
|
|
|
|
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"
|
|
)
|
|
|
|
// SamplingHandler answers MCP sampling requests with the task's model.
|
|
// Without a runtime or model the request is refused. record receives each
|
|
// call's model ref and token usage.
|
|
func SamplingHandler(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")
|
|
}
|
|
model, err := config.ResolveModel(cfg.Models, "", config.PurposeAgent)
|
|
if err != nil {
|
|
return mcp.SamplingResult{}, fmt.Errorf("mcp sampling: %w", err)
|
|
}
|
|
messages, err := modelloop.SamplingMessages(req)
|
|
if err != nil {
|
|
return mcp.SamplingResult{}, err
|
|
}
|
|
limits := cfg.ModelLimits[model]
|
|
options := core.GenerateOptions{
|
|
Messages: messages,
|
|
System: req.SystemPrompt,
|
|
MaxSteps: 1,
|
|
MaxTokens: modelloop.SamplingMaxTokens(req.MaxTokens, limits.MaxOutputTokens),
|
|
}
|
|
if req.Temperature != nil {
|
|
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)
|
|
}
|
|
return mcp.SamplingResult{
|
|
Model: model,
|
|
Role: "assistant",
|
|
Content: mcp.SamplingContent{Type: "text", Text: result.Text},
|
|
StopReason: string(result.FinishReason),
|
|
}, nil
|
|
}
|
|
}
|
|
|
|
// usageWriteTimeout bounds the usage write: a dead store must not hold the
|
|
// sampling result beyond a few seconds.
|
|
const usageWriteTimeout = 5 * time.Second
|
|
|
|
// UsageRecorder records a task's MCP sampling calls against the task.
|
|
// A failed write is logged, never fails the call: the store client queues the
|
|
// record and retries it until the store accepts it.
|
|
func UsageRecorder(store usage.Recorder, 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",
|
|
Identity: t.Identity,
|
|
InputTokens: int64(used.PromptTokens), OutputTokens: int64(used.CompletionTokens),
|
|
CachedTokens: int64(used.CachedTokens), At: time.Now().UTC(),
|
|
}.WithRef(model)
|
|
writeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), usageWriteTimeout)
|
|
defer cancel()
|
|
if err := store.RecordUsage(writeCtx, record); err != nil && log != nil {
|
|
log.WarnContext(ctx, "record model usage failed", "model", model, "err", err)
|
|
}
|
|
}
|
|
}
|