Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

1.6 KB
Raw Blame
import { ActivepiecesAiCall, ActivepiecesAiConsumerSource, ActivepiecesAiCostEvent, AiChargeBasis } from '@activepieces/core-utils'
import { AiUsageCharge, ReportAiUsageRequest } from '@activepieces/shared'

export function aiUsageReportOf({ event, idempotencyKey }: AiUsageReportParams): ReportAiUsageRequest {
    const { billing, provider, providerConfigId, modelId, call } = event
    const baseProps: ReportAiUsageRequest = {
        billing,
        provider,
        providerConfigId,
        modelId,
        idempotencyKey,
        usage: chargeOf(call),
        generationId: call.generationId,
        inputTokens: call.inputTokens,
        outputTokens: call.outputTokens,
        cacheReadTokens: call.cacheReadTokens,
        cacheWriteTokens: call.cacheWriteTokens,
        reasoningTokens: call.reasoningTokens,
        observedCostUsd: call.observedCostUsd,
    }
    switch (billing.source) {
        case ActivepiecesAiConsumerSource.AI_STEP_IN_FLOW:
            return { ...baseProps, flowRun: billing.flowRun }
        case ActivepiecesAiConsumerSource.CHAT:
            return { ...baseProps, chat: billing.chat }
    }
}

function chargeOf(call: ActivepiecesAiCall): AiUsageCharge {
    if (call.charge === AiChargeBasis.FIXED_CREDITS) {
        return { type: AiChargeBasis.FIXED_CREDITS, credits: call.credits }
    }
    if (call.charge === AiChargeBasis.USAGE_ONLY) {
        return { type: AiChargeBasis.USAGE_ONLY }
    }
    return { type: AiChargeBasis.PROVIDER_REPORTED_COST, costUsd: call.costUsd }
}

export type AiUsageReportParams = {
    event: ActivepiecesAiCostEvent
    idempotencyKey: string
}