amoghrajesh commented on code in PR #71403: URL: https://github.com/apache/airflow/pull/71403#discussion_r3966532053
########## 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) + + +def _validate_range(field: str, value: Decimal | int | float) -> None: + if not _is_finite(value): + raise ValueError( + f"usage_limits[{field!r}] must be a finite number (got {value!r}); " + "a non-finite value would silently disable that limit." + ) + if value < 0: + raise ValueError(f"usage_limits[{field!r}] must not be negative (got {value!r})") + + +def _unknown_field_message(field: str) -> str: + valid_fields = ", ".join(sorted(_FIELD_TYPES)) + return f"usage_limits has no field {field!r}; valid fields are: {valid_fields}" + + +def _truncated_repr(value: Any, limit: int = 100) -> str: + # A container-shape error on a templated field usually means the render + # produced something that merely looks right (e.g. a long string that reads + # like a dict literal) -- the author needs to see what actually came out, not + # just its type. Truncate so a large rendered blob doesn't bloat the exception. + text = repr(value) + return text if len(text) <= limit else f"{text[:limit]}..." + + +def _coerce_value(field: str, value: Any) -> Any: Review Comment: A bad value here will crash with wrong error type. For example: `usage_limits={"cost_limit": []}`, falls through to `math.isfinite([])` and raises `TypeError`. Suggest checking the value's type before the finite check ########## 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) + + +def _validate_range(field: str, value: Decimal | int | float) -> None: + if not _is_finite(value): + raise ValueError( + f"usage_limits[{field!r}] must be a finite number (got {value!r}); " + "a non-finite value would silently disable that limit." + ) + if value < 0: + raise ValueError(f"usage_limits[{field!r}] must not be negative (got {value!r})") + + +def _unknown_field_message(field: str) -> str: + valid_fields = ", ".join(sorted(_FIELD_TYPES)) + return f"usage_limits has no field {field!r}; valid fields are: {valid_fields}" + + +def _truncated_repr(value: Any, limit: int = 100) -> str: + # A container-shape error on a templated field usually means the render + # produced something that merely looks right (e.g. a long string that reads + # like a dict literal) -- the author needs to see what actually came out, not + # just its type. Truncate so a large rendered blob doesn't bloat the exception. + text = repr(value) + return text if len(text) <= limit else f"{text[:limit]}..." + + +def _coerce_value(field: str, value: Any) -> Any: + # ``None`` is always the author's explicit choice to disable that limit -- + # Jinja never produces ``None`` from a string template -- so it passes through. + if value is None: + return value + + field_type = _FIELD_TYPES[field] + # Only ``str`` values are converted: Jinja only ever renders a scalar leaf to + # ``str``, so a non-``str`` value is exactly what the author wrote (a literal + # ``Decimal``, ``int``, or ``bool``) and is passed through unchanged. + if isinstance(value, str): + coercer = _COERCERS.get(field_type) + if coercer is None: + type_name = getattr(field_type, "__name__", field_type) + raise ValueError( + f"usage_limits[{field!r}] does not support templated (string) values " + f"(got {value!r}); pass a {type_name} value instead." + ) + value = coercer(field, value) + elif field_type is Decimal and isinstance(value, (int, float)): + # Decimal(str(x)), never Decimal(x): the latter bakes in binary-float noise + # for a value like 0.1, and normalizing through str routes inf/nan through + # the same finite check below as the templated-string path -- a bare + # ``float`` must not bypass the one safety promise this module makes. + value = _coerce_decimal(field, str(value)) + + if field_type in (Decimal, int): + _validate_range(field, value) + return value + + +def coerce_usage_limits(usage_limits: UsageLimits | dict[str, Any] | None) -> UsageLimits | None: Review Comment: Does this have to be a public interface? Only called inside common/ai code paths. ########## providers/common/ai/src/airflow/providers/common/ai/example_dags/example_llm.py: ########## @@ -148,6 +153,30 @@ def example_llm_operator_usage_limits(): example_llm_operator_usage_limits() +# [START howto_operator_llm_templated_usage_limits] +@dag(tags=["example"]) +def example_llm_operator_templated_usage_limits(): + LLMOperator( + task_id="capped_summary", + prompt="Summarize the trade-offs of a message queue vs. direct HTTP calls in three bullet points.", + llm_conn_id="pydanticai_default", + system_prompt="You are a concise technical reviewer.", + # A plain dict lets every UsageLimits field be templated -- e.g. driven by + # an Airflow Variable so the budget can change per environment without + # editing the Dag. This caps a single task run, not a day's total spend -- + # each run gets the full budget again. + usage_limits={ + "cost_limit": "{{ var.value.llm_cost_cap_per_task }}", Review Comment: If the variable doesn't exist, does it render to empty string or raises KeyError? Maybe we define that variable in this file? ########## 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) + + +def _validate_range(field: str, value: Decimal | int | float) -> None: + if not _is_finite(value): + raise ValueError( + f"usage_limits[{field!r}] must be a finite number (got {value!r}); " + "a non-finite value would silently disable that limit." + ) + if value < 0: + raise ValueError(f"usage_limits[{field!r}] must not be negative (got {value!r})") + + +def _unknown_field_message(field: str) -> str: + valid_fields = ", ".join(sorted(_FIELD_TYPES)) + return f"usage_limits has no field {field!r}; valid fields are: {valid_fields}" + + +def _truncated_repr(value: Any, limit: int = 100) -> str: + # A container-shape error on a templated field usually means the render + # produced something that merely looks right (e.g. a long string that reads + # like a dict literal) -- the author needs to see what actually came out, not + # just its type. Truncate so a large rendered blob doesn't bloat the exception. + text = repr(value) + return text if len(text) <= limit else f"{text[:limit]}..." + + +def _coerce_value(field: str, value: Any) -> Any: Review Comment: Suggest adding a test for this too. -- 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]
