kaxil commented on code in PR #77084:
URL: https://github.com/apache/airflow/pull/77084#discussion_r4688654122


##########
providers/common/ai/src/airflow/providers/common/ai/utils/logging.py:
##########
@@ -56,6 +58,14 @@ def log_run_summary(
     )
     _log_cache_and_cost(logger, usage)
 
+    emit_usage_metrics(

Review Comment:
   This double counts on the tool-approval path. `_complete_run` calls 
`log_run_summary` before it pauses, and on resume `_run_usage_base` is set so 
the summary covers both sides of the pause. That's right for a log line, but 
`Stats.incr` adds, so each resume sends the pre-pause requests and tokens again 
(a run that made 2 requests reports 3). Could this skip emission when 
`result.output` is `DeferredToolRequests` and let the final segment report the 
total? A pause/resume test that sums `llm_requests` would pin it.



##########
providers/common/ai/src/airflow/providers/common/ai/get_provider_info.py:
##########
@@ -142,6 +142,20 @@ def get_provider_info():
                         "example": "False",
                         "default": "False",
                     },
+                    "emit_usage_metrics": {
+                        "description": "Emit Airflow task metrics (Stats) for 
live LLM token usage and cost.\n\n"
+                                       "When enabled, each task attempt 
aggregates its usage per model and emits\n"
+                                       "``common_ai.llm_requests``, 
``common_ai.llm_input_tokens``,\n"
+                                       "``common_ai.llm_output_tokens`` and, 
when a price is known,\n"
+                                       "``common_ai.llm_cost``. Metrics carry 
only ``provider`` and ``model``\n"

Review Comment:
   The code emits `common_ai.llm_cost_micros`, not `common_ai.llm_cost`, so an 
alert set up from this text gets no data. Can this use the real name and say 
the unit is micro-USD?



##########
providers/common/ai/src/airflow/providers/common/ai/get_provider_info.py:
##########
@@ -142,6 +142,20 @@ def get_provider_info():
                         "example": "False",
                         "default": "False",
                     },
+                    "emit_usage_metrics": {
+                        "description": "Emit Airflow task metrics (Stats) for 
live LLM token usage and cost.\n\n"
+                                       "When enabled, each task attempt 
aggregates its usage per model and emits\n"
+                                       "``common_ai.llm_requests``, 
``common_ai.llm_input_tokens``,\n"
+                                       "``common_ai.llm_output_tokens`` and, 
when a price is known,\n"
+                                       "``common_ai.llm_cost``. Metrics carry 
only ``provider`` and ``model``\n"
+                                       "tags to keep StatsD cardinality 
bounded.\n\n"
+                                       "Off by default. Cached and replayed 
responses from durable execution are\n"
+                                       "not counted; only live model traffic 
is reported.\n",
+                        "version_added": "0.5.0",

Review Comment:
   This file is generated from `provider.yaml` (`prek run 
update-providers-build-files`), so the option needs to be added there. 
Otherwise the next regeneration drops it and it never shows up in the config 
reference. `version_added` should also be the next release: 0.5.0 shipped a 
while ago and main is at 1.2.0.



##########
providers/common/ai/src/airflow/providers/common/ai/observability.py:
##########
@@ -209,3 +209,42 @@ def __getattr__(self, name: str) -> Any:
         if tracer is None:
             raise AttributeError(name)
         return getattr(tracer, name)
+
+
+def _usage_metrics_enabled() -> bool:
+    return conf.getboolean(SECTION, "emit_usage_metrics", fallback=False)
+
+
+def emit_usage_metrics(
+    *,
+    model: str,
+    provider: str | None = None,
+    requests: int = 0,
+    input_tokens: int = 0,
+    output_tokens: int = 0,
+    cost: float | None = None,
+) -> None:
+    """
+    Emit Airflow Stats counters for one task attempt's LLM usage.
+
+    No-op unless ``[common.ai] emit_usage_metrics`` is enabled. Callers must
+    pass live traffic only -- replayed durable responses must not reach here.
+    """
+    if not _usage_metrics_enabled() or requests <= 0:
+        return
+
+    from airflow.providers.common.compat.sdk import Stats
+
+    tags = {"model": model}

Review Comment:
   With `statsd_influxdb_enabled` the tags are appended to the stat name before 
validation, and `:` isn't an allowed character there. So Ollama names like 
`llama3.1:8b` or Bedrock ids ending in `:0` drop all four counters, each with 
an `Invalid stat name` traceback. Could the tag values be normalized to the 
allowed characters?



##########
providers/common/ai/src/airflow/providers/common/ai/observability.py:
##########
@@ -209,3 +209,42 @@ def __getattr__(self, name: str) -> Any:
         if tracer is None:
             raise AttributeError(name)
         return getattr(tracer, name)
+
+
+def _usage_metrics_enabled() -> bool:
+    return conf.getboolean(SECTION, "emit_usage_metrics", fallback=False)
+
+
+def emit_usage_metrics(
+    *,
+    model: str,
+    provider: str | None = None,
+    requests: int = 0,
+    input_tokens: int = 0,
+    output_tokens: int = 0,
+    cost: float | None = None,
+) -> None:
+    """
+    Emit Airflow Stats counters for one task attempt's LLM usage.
+
+    No-op unless ``[common.ai] emit_usage_metrics`` is enabled. Callers must
+    pass live traffic only -- replayed durable responses must not reach here.
+    """
+    if not _usage_metrics_enabled() or requests <= 0:
+        return
+
+    from airflow.providers.common.compat.sdk import Stats

Review Comment:
   Any reason to import `Stats` inside the function? `conf` already comes from 
the same `compat.sdk` module at the top, and `tool_metrics.py` imports `Stats` 
at module level.



##########
providers/common/ai/tests/unit/common/ai/test_observability.py:
##########
@@ -248,3 +248,28 @@ def 
test_wraps_a_copy_without_mutating_or_nesting_shared_settings(self):
         assert isinstance(agent1.instrument.tracer, 
observability._IdentityTracer)
         assert agent1.instrument.tracer._tracer is original_tracer
         assert agent2.instrument.tracer._tracer is original_tracer
+
+
[email protected](observability, "_usage_metrics_enabled", return_value=False)
+def test_emit_usage_metrics_disabled(_):
+    with patch("airflow.providers.common.compat.sdk.Stats") as stats:
+        observability.emit_usage_metrics(model="gpt-4o", requests=1, 
input_tokens=10)
+    stats.incr.assert_not_called()
+
+
[email protected](observability, "_usage_metrics_enabled", return_value=True)

Review Comment:
   These patch `_usage_metrics_enabled` and `Stats` without `autospec`, and 
check 2 of the 4 counters, so a typo in the config key or swapped input/output 
tokens still passes. Could they set the option with `conf_vars`, use 
`autospec=True` and assert the full `call_args_list`? A `log_run_summary` test 
would also cover the one real call site, which nothing tests right now.



##########
providers/common/ai/src/airflow/providers/common/ai/get_provider_info.py:
##########
@@ -142,6 +142,20 @@ def get_provider_info():
                         "example": "False",
                         "default": "False",
                     },
+                    "emit_usage_metrics": {
+                        "description": "Emit Airflow task metrics (Stats) for 
live LLM token usage and cost.\n\n"
+                                       "When enabled, each task attempt 
aggregates its usage per model and emits\n"

Review Comment:
   On the open question in the description, I'd do the failure path in this PR. 
`log_run_usage` doesn't emit, so a run stopped by `cost_limit` reports nothing, 
and that's the run someone alerting on cost most wants to see. This text also 
already says every task attempt is counted.



##########
providers/common/ai/src/airflow/providers/common/ai/observability.py:
##########
@@ -209,3 +209,42 @@ def __getattr__(self, name: str) -> Any:
         if tracer is None:
             raise AttributeError(name)
         return getattr(tracer, name)
+
+
+def _usage_metrics_enabled() -> bool:
+    return conf.getboolean(SECTION, "emit_usage_metrics", fallback=False)
+
+
+def emit_usage_metrics(
+    *,
+    model: str,
+    provider: str | None = None,
+    requests: int = 0,
+    input_tokens: int = 0,
+    output_tokens: int = 0,
+    cost: float | None = None,
+) -> None:
+    """
+    Emit Airflow Stats counters for one task attempt's LLM usage.
+
+    No-op unless ``[common.ai] emit_usage_metrics`` is enabled. Callers must
+    pass live traffic only -- replayed durable responses must not reach here.
+    """
+    if not _usage_metrics_enabled() or requests <= 0:
+        return
+
+    from airflow.providers.common.compat.sdk import Stats
+
+    tags = {"model": model}
+    if provider:

Review Comment:
   The only caller never passes `provider`, so this branch never runs and every 
metric goes out with just `model`, though the option text promises both tags. 
`result.response.provider_name` is available in `log_run_summary`. 
`ModelResponse.model_name` can also be `None` (the `getattr` default only 
covers a missing attribute), so `model` can end up as `None` too.



##########
providers/common/ai/src/airflow/providers/common/ai/get_provider_info.py:
##########
@@ -142,6 +142,20 @@ def get_provider_info():
                         "example": "False",
                         "default": "False",
                     },
+                    "emit_usage_metrics": {

Review Comment:
   `common_ai.tool_calls` is emitted without a switch, and anyone who doesn't 
want it can drop it with core's `[metrics] metrics_block_list`. Could these 
counters work the same way instead of adding an option? If the switch stays, 
what does it cover that the block list doesn't?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to