diff --git a/logfire/_internal/integrations/llm_providers/openai.py b/logfire/_internal/integrations/llm_providers/openai.py index 8fd977cd8..7c0d8df37 100644 --- a/logfire/_internal/integrations/llm_providers/openai.py +++ b/logfire/_internal/integrations/llm_providers/openai.py @@ -229,6 +229,13 @@ def get_attributes(self, span_data: dict[str, Any]) -> dict[str, Any]: response = self.get_response_data() if response: span_data['events'] = span_data['events'] + responses_output_events(response) + usage = getattr(response, 'usage', None) + input_tokens = getattr(usage, 'input_tokens', None) + output_tokens = getattr(usage, 'output_tokens', None) + if isinstance(input_tokens, int): + span_data[INPUT_TOKENS] = input_tokens + if isinstance(output_tokens, int): + span_data[OUTPUT_TOKENS] = output_tokens return span_data diff --git a/tests/otel_integrations/test_openai.py b/tests/otel_integrations/test_openai.py index 674d9d49c..de491e9ab 100644 --- a/tests/otel_integrations/test_openai.py +++ b/tests/otel_integrations/test_openai.py @@ -1954,6 +1954,8 @@ def test_responses_stream(exporter: TestExporter) -> None: 'async': False, 'gen_ai.operation.name': 'chat', 'duration': 1.0, + 'gen_ai.usage.input_tokens': 13, + 'gen_ai.usage.output_tokens': 9, 'logfire.json_schema': { 'type': 'object', 'properties': { @@ -1964,6 +1966,8 @@ def test_responses_stream(exporter: TestExporter) -> None: 'async': {}, 'gen_ai.operation.name': {}, 'duration': {}, + 'gen_ai.usage.input_tokens': {}, + 'gen_ai.usage.output_tokens': {}, }, }, 'logfire.tags': ('LLM',),