def _record_token_usage_metrics()

in instrumentation/elastic-opentelemetry-instrumentation-openai/src/opentelemetry/instrumentation/openai/helpers.py [0:0]


def _record_token_usage_metrics(metric: Histogram, attributes: Attributes, usage: CompletionUsage):
    attribute_names = (
        GEN_AI_OPERATION_NAME,
        GEN_AI_REQUEST_MODEL,
        GEN_AI_RESPONSE_MODEL,
        GEN_AI_SYSTEM,
        SERVER_ADDRESS,
        SERVER_PORT,
    )
    token_usage_metric_attrs = {k: v for k, v in attributes.items() if k in attribute_names}
    metric.record(usage.prompt_tokens, {**token_usage_metric_attrs, GEN_AI_TOKEN_TYPE: "input"})
    # embeddings responses only have input tokens
    if hasattr(usage, "completion_tokens"):
        metric.record(usage.completion_tokens, {**token_usage_metric_attrs, GEN_AI_TOKEN_TYPE: "output"})