Skip to main content

Expense Tracking

Tasks Using External APIs

Tasks that directly use third-party or external APIs must include additional metadata, ProcessedUnit, to ensure their usage and cost can be measured and attributed correctly.

Ensure that ProcessedUnit accurately reflects all the units the vendor uses to calculate charges for the task.

Syntax

flow.meta().addProcessedUnit(ProcessedUnit.from('vendor', 'operation', 'model', getCount(result)));

Example

@Executor(Commands.OPENAI_IMAGE_EDITING)
export class OpenaiImageEditingExecutor implements TaskExecutor {

async processTask(
taskCommand: OpenAiImageEditingCommand,
meta: TaskMetadata,
flow: Flow,
): Promise<OpenAiImageEditingResult> {
const result = await this.openaiImageEditingService.editImage(taskCommand as OpenAiImageEditingCommand, flow);

flow.meta().addProcessedUnit(ProcessedUnit.from('openai', 'input_text_tokens', taskCommand.model, result.usage?.input_tokens_details.text_tokens / 1e6));
flow.meta().addProcessedUnit(ProcessedUnit.from('openai', 'input_image_tokens', taskCommand.model, result.usage?.input_tokens_details.image_tokens / 1e6));
flow.meta().addProcessedUnit(ProcessedUnit.from('openai', 'output_image_tokens', taskCommand.model, result.usage?.output_tokens / 1e6));

return { result: result.editedImageResult };
}
}

note

Ensure your project uses version 4.3.0 or higher of @picsart/pa-pluggable-workers-core.

Emitting a Datadog metric

By default, addProcessedUnit only writes to the access log. From @picsart/pa-pluggable-workers-core 7.1.0, you can additionally emit a worker.task.processed_units Datadog counter per unit by passing { emitMetric: true }:

flow.meta().addProcessedUnit(
ProcessedUnit.from('openai', 'output_tokens', taskCommand.model, count),
{ emitMetric: true },
);

The emitted counter is tagged with the unit's service / operation / model, the flow's task / touchpoint, and any dynamic labels set via flow.meta().setLabels(...).

warning

Only enable emitMetric when you actually need a Datadog counter — the access log already captures usage.