ColtenOuO commented on code in PR #71403:
URL: https://github.com/apache/airflow/pull/71403#discussion_r3888073869


##########
providers/common/ai/docs/operators/llm.rst:
##########
@@ -119,16 +119,46 @@ calls within a single task.
     :start-after: [START howto_operator_llm_usage_limits]
     :end-before: [END howto_operator_llm_usage_limits]
 
+A plain ``dict`` can be passed instead of a ``UsageLimits`` instance, which 
lets
+Jinja template individual fields -- e.g. a per-run cost cap driven by an 
Airflow
+Variable so the budget can change per environment without editing the Dag:
+
+.. exampleinclude:: 
/../../ai/src/airflow/providers/common/ai/example_dags/example_llm.py
+    :language: python
+    :start-after: [START howto_operator_llm_templated_usage_limits]
+    :end-before: [END howto_operator_llm_templated_usage_limits]
+
+Each dict value is rendered by Jinja like any other ``template_fields`` entry,
+then coerced to that field's type (``Decimal``, ``int``, or ``bool``). A value
+that doesn't parse -- an unset Variable renders to ``""``, a typo renders to a
+non-numeric string -- fails the task with a ``ValueError`` naming the field and
+the rendered value, instead of silently disabling the limit. A ``UsageLimits``
+instance passed directly is used as-is and is not templated or validated.
+
 Common knobs on ``UsageLimits``:
 
 - ``request_limit`` — max model requests per run (caps retry/tool-loop 
blow-ups).
   pydantic-ai applies a default of ``50`` when ``UsageLimits()`` is constructed
   without an explicit value, so passing 
``UsageLimits(input_tokens_limit=4_000)``
-  silently inherits that 50-request cap. Set ``request_limit=None`` to disable
-  it explicitly when you only want a token cap.
+  (or the dict form ``{"input_tokens_limit": 4_000}``) silently inherits that
+  50-request cap. Set ``request_limit=None`` explicitly when you only want a
+  token cap.
 - ``input_tokens_limit`` / ``output_tokens_limit`` — per-run token caps.
 - ``total_tokens_limit`` — combined input + output cap.
 - ``tool_calls_limit`` — max tool invocations (``AgentOperator`` only).
+- ``cost_limit`` — a ``Decimal`` cap on the run's estimated USD cost. This is 
**not** a
+  hard guarantee against overspend: the response that crosses the limit has 
already been
+  produced and billed — pydantic-ai checks the accumulated cost *after* each 
response and
+  then fails the run with ``UsageLimitExceeded``. It protects you from further 
spend, not
+  from the request that broke the budget; even a single-request run fails as 
soon as that
+  request's cost pushes the total over the limit. For self-hosted or unknown
+  models (e.g. Ollama, custom endpoints) pydantic-ai cannot price the 
response, so cost
+  is ``None`` and ``cost_limit`` silently has no effect (a 
``CostNotFoundWarning`` is

Review Comment:
   ```suggestion
     is ``None`` and ``cost_limit`` has no effect without halting execution (a 
``CostNotFoundWarning`` is
   ```
   
   The original phrasing feels a bit contradictory: it says `silently has no 
effect`; but a warning is actually emitted.



##########
providers/common/ai/src/airflow/providers/common/ai/utils/usage.py:
##########
@@ -0,0 +1,228 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Coerce a templated ``usage_limits`` dict into a real ``UsageLimits`` 
instance."""
+
+from __future__ import annotations
+
+import dataclasses
+import math
+import typing
+from collections.abc import Callable
+from decimal import Decimal, InvalidOperation
+from typing import Any
+
+from pydantic_ai.usage import UsageLimits
+
+
+def _resolve_field_type(field: str, hint: Any) -> type:
+    # Only ``X`` or ``X | None`` are supported shapes -- anything else (a 
Union of
+    # two real types, a parameterized generic, a Literal, ...) has no single
+    # unambiguous coercion target, so it must raise here rather than silently
+    # picking one member and hiding the ambiguity behind a tripwire that never 
fires.
+    args = [arg for arg in typing.get_args(hint) if arg is not type(None)]
+    if not args:
+        resolved = hint
+    elif len(args) == 1:
+        resolved = args[0]
+    else:
+        raise TypeError(f"UsageLimits.{field} has an unsupported annotation 
{hint!r}")
+    if not isinstance(resolved, type):
+        raise TypeError(f"UsageLimits.{field} resolved to a non-type 
{resolved!r}")
+    return resolved
+
+
+def _build_field_types() -> dict[str, type]:
+    # ``pydantic_ai.usage`` uses ``from __future__ import annotations``, so
+    # ``field.type`` is a string; ``get_type_hints`` resolves the real objects.
+    hints = typing.get_type_hints(UsageLimits)
+    return {
+        field.name: _resolve_field_type(field.name, hints[field.name])
+        for field in dataclasses.fields(UsageLimits)
+    }
+
+
+def _coerce_decimal(field: str, value: str) -> Decimal:
+    try:
+        parsed = Decimal(value)
+    except InvalidOperation:
+        raise ValueError(
+            f"usage_limits[{field!r}] must be a number (got {value!r}); "
+            "if it is templated, check the rendered value."
+        ) from None
+    return parsed
+
+
+def _coerce_int(field: str, value: str) -> int:
+    try:
+        return int(value)
+    except ValueError:
+        raise ValueError(
+            f"usage_limits[{field!r}] must be an integer (got {value!r}); "
+            "if it is templated, check the rendered value."
+        ) from None
+
+
+# Deliberately the same vocabulary as 
``airflow.utils.strings.TRUE_LIKE_VALUES`` so a
+# Dag author who knows Airflow's config parsing already knows this one. Unlike
+# ``to_boolean``, an unrecognized string raises instead of silently becoming 
``False`` --
+# this flag gates a pre-flight token-limit check, and silently turning it off 
would
+# defeat the safeguard this PR exists to add.
+_TRUE_LIKE = {"on", "t", "true", "y", "yes", "1"}
+_FALSE_LIKE = {"off", "f", "false", "n", "no", "0"}
+
+
+def _coerce_bool(field: str, value: str) -> bool:
+    normalized = value.strip().lower()
+    if normalized in _TRUE_LIKE:
+        return True
+    if normalized in _FALSE_LIKE:
+        return False
+    raise ValueError(
+        f"usage_limits[{field!r}] must be one of {sorted(_TRUE_LIKE | 
_FALSE_LIKE)} "
+        f"(got {value!r}); if it is templated, check the rendered value."
+    )
+
+
+_FIELD_TYPES: dict[str, type] = _build_field_types()
+
+# Keyed by the field's declared type rather than the field name so a new
+# ``UsageLimits`` field of an already-supported type (another ``int`` cap, say)
+# needs no change here. A field of an unsupported type raises loudly (see
+# ``_coerce_value``) instead of the templated string silently reaching the
+# dataclass unconverted and failing deep inside pydantic-ai instead.
+_COERCERS: dict[type, Callable[[str, str], Any]] = {
+    Decimal: _coerce_decimal,
+    int: _coerce_int,
+    bool: _coerce_bool,
+}
+
+
+def _is_finite(value: Decimal | int | float) -> bool:
+    # Dispatch by type instead of calling math.isfinite directly on everything:
+    # math.isfinite converts its argument to float first, which overflows a 
large
+    # int into OverflowError and raises outright on a Decimal signaling NaN --
+    # neither looks like "not finite", they look like an unhandled crash. 
Decimal
+    # has no float-sized exponent limit either, so a huge-but-finite Decimal 
must
+    # not be misreported as non-finite just because float can't represent it.
+    if isinstance(value, Decimal):
+        return value.is_finite()
+    if isinstance(value, int):
+        return True
+    return math.isfinite(value)

Review Comment:
   If I'm not mistaken, if value is an invalid native value such as `[]`, it 
will still reach `_validate_range()` and eventually raise a raw `TypeError` 
from `math.isfinite([])`, rather than the documented field-specific 
`ValueError`.
   
   Perhaps this is a small detail we should keep an eye on and pay special 
attention to.



-- 
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