Cost Tracking

AgentFlow automatically tracks Claude API token costs per node, per pipeline, and across your team. Monitor spend over time and optimize your workflows.

How Costs Are Captured

Only AI Task nodes incur token costs. When Claude CLI finishes executing, it prints cost information to stderr. AgentFlow parses this automatically.

Cost extraction patterns
text
# AgentFlow scans Claude CLI stderr for these patterns:

"Total cost: $0.0342"
"total_cost_usd: 0.0342"

# The extracted value is stored as a REAL (float) in:
# run_steps.cost_usd

Info

Shell, Git, Parallel, Loop, Approval Gate, and Sub-pipeline nodes do not have direct costs. Sub-pipeline and Loop costs are the sum of all AI Task nodes within them. Loop costs are multiplied by the number of iterations.

Available Metrics

Total Cost

Sum of all cost_usd across all runs

SUM(cost_usd) FROM run_steps

Cost per Run

Total cost grouped by run_id

SUM(cost_usd) GROUP BY run_id

Avg Cost per Run

Total cost divided by number of runs

total_cost / COUNT(runs)

Avg Cost per AI Step

Total divided by AI steps with cost > 0

total / COUNT(WHERE cost_usd > 0)

Top 10 Expensive Nodes

Nodes ranked by cost

ORDER BY cost_usd DESC LIMIT 10

Top 10 Expensive Pipelines

Pipelines ranked by total cost

GROUP BY pipeline_name ORDER BY SUM

Avg Run Duration

Average time from start to finish

AVG(finished_at - started_at)

Run Count per Pipeline

How many times each pipeline has been run

COUNT(*) GROUP BY pipeline_name

Cost Dashboard

The Cost Dashboard panel in AgentFlow shows a comprehensive overview of your AI spending:

  • Summary cards: Total cost, total runs, total AI steps, average cost per run, average cost per AI step, average duration
  • Run breakdown: Each run listed with pipeline name, status, cost, and duration
  • Top nodes: The 10 most expensive individual node executions
  • Top pipelines: The 10 most expensive pipelines by cumulative cost

Budget Limits

Set a maximum cost per pipeline run. When the accumulated cost exceeds the budget, execution halts automatically — no more nodes are started.

  • Configure budget in the Pipeline Settings panel
  • Budget is checked after each AI Task node completes
  • Remaining nodes are marked as cancelled when the budget is exceeded
  • The run is recorded with a budget-exceeded status for review

Pre-Run Cost Estimates

Before starting a pipeline run, AgentFlow estimates the total cost based on historical per-node averages from previous executions. This helps you decide whether to proceed or adjust the pipeline.

Tip

Cost estimates improve with more historical data. After 3-5 runs of the same pipeline, estimates become reliable enough for budget planning.

Loop-Aware Cost Estimation

Pre-run cost estimates account for loop iteration counts. When a loop node contains AI Task children, the estimated cost is multiplied by the expected number of iterations.

  • The iteration count is determined from the loop's instructions (number of items in the list)
  • Child AI Task costs are multiplied by the iteration count
  • Setting max_iterations caps the estimated cost even if the list is longer
  • Actual costs may differ if iterations fail early or are skipped

Per-Node Model Selection

Each AI Task node can be configured to use a specific Claude model, letting you optimize cost vs. capability per step:

  • Opus: Most capable, best for complex reasoning and code generation
  • Sonnet: Balanced performance and cost for general tasks
  • Haiku: Fastest and cheapest, ideal for simple classification or formatting

Set the model in the node configuration panel. If unset, the node uses the pipeline-level or global default model.

Output Caching

AgentFlow can skip re-execution of nodes whose instructions haven't changed since their last successful run. This saves both time and tokens during iterative pipeline development.

  • Instruction hashes (SHA-256) are compared against the most recent cached step
  • If the hash matches a successful prior step, the cached result is reused
  • Cached steps show cost_usd = 0 in the current run
  • Database indexes on run_steps ensure fast cache lookups

IPC Commands

get_cost_summary(){ totalCost: number, runs: CostRun[] }

Returns total cost and per-run cost breakdown.

get_usage_stats()UsageStats

Comprehensive statistics: total cost, run counts, averages, top nodes, top pipelines.

get_avg_ai_cost()number | null

Returns the average cost per AI task execution across all runs.

UsageStats Type

UsageStats interface
typescript
interface UsageStats {
  totalCost: number;            // Sum of all AI task costs
  totalRuns: number;            // Total pipeline executions
  totalAiSteps: number;         // Total AI task node executions
  avgCostPerRun: number;        // totalCost / totalRuns
  avgCostPerAiStep: number;     // totalCost / totalAiSteps
  avgDurationSecs: number;      // Average run duration in seconds

  runs: {
    runId: string;
    pipelineName: string;
    status: string;
    cost: number;
    durationSecs: number;
    startedAt: string;          // ISO 8601
  }[];

  topNodes: {
    nodeId: string;
    nodeName: string;
    runId: string;
    cost: number;
  }[];

  topPipelines: {
    pipelineName: string;
    totalCost: number;
    runCount: number;
  }[];
}

Cost & Resume

When resuming a failed pipeline:

  • Previously successful steps are reused (not re-executed), so they incur zero additional cost
  • Reused steps retain their original cost_usd in the new run record
  • Only newly executed nodes incur fresh costs
  • The new run's total cost includes both reused and new costs

Cost optimization

Use the Cost Dashboard to identify your most expensive nodes and pipelines. Consider breaking large AI tasks into smaller, focused steps to reduce per-invocation token usage.