Lee-W commented on code in PR #71403: URL: https://github.com/apache/airflow/pull/71403#discussion_r3947689720
########## 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: since we're checking [here](https://github.com/apache/airflow/pull/71403/changes#diff-6244833c78931d8bc47724577d529b43e1771f086f2ec1fcdc69d511bd560567R178), I think it's not going to happen. WDYT? -- 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]
