kaxil commented on code in PR #71403: URL: https://github.com/apache/airflow/pull/71403#discussion_r3989293488
########## providers/common/ai/src/airflow/providers/common/ai/utils/usage.py: ########## @@ -0,0 +1,278 @@ +# 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 functools +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 + + [email protected]_cache(maxsize=1) +def _field_hints() -> dict[str, Any]: + # ``pydantic_ai.usage`` uses ``from __future__ import annotations``, so + # ``field.type`` is a string; ``get_type_hints`` resolves the real objects. + # ``get_type_hints`` parses every field's annotation in one call: if a + # future field's annotation can't be resolved at all (e.g. a forward ref + # only importable under ``TYPE_CHECKING``), that failure hits every caller + # of ``_get_field_type``, not just Dags that set that field -- unlike + # ``_resolve_field_type`` below, whose failures are scoped per field. + return typing.get_type_hints(UsageLimits) + + [email protected] +def _get_field_type(field: str) -> type: + # Resolved lazily and cached per field rather than for every field at + # import time: a future ``UsageLimits`` field typed e.g. ``Literal[...]`` + # or ``list[int] | None`` -- a shape ``_resolve_field_type`` itself + # rejects -- only breaks Dags that actually set that field, not every Dag + # that imports a common.ai operator module (see PR #71403 review + # discussion). This scoping doesn't extend to ``_field_hints()`` failing + # outright; see the comment above. ``lru_cache`` never caches a raised + # exception, so a field whose annotation is unsupported keeps raising the + # same way on every call -- it never gets silently "fixed" by caching. + return _resolve_field_type(field, _field_hints()[field]) + + +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_NAMES: frozenset[str] = frozenset(field.name for field in dataclasses.fields(UsageLimits)) + +# 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_NAMES)) + 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 the author's explicit choice to disable that limit under the + # default (string) rendering, where Jinja always renders a scalar leaf to + # ``str``. Under ``render_template_as_native_obj=True`` a ``None``-valued + # param (e.g. ``{{ params.budget }}`` where ``params.budget`` is ``None``) + # also renders to a real ``None``, indistinguishable here from the author's + # own ``None`` -- a known limitation, not something this function detects. + if value is None: + return value + + field_type = _get_field_type(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)) + elif field_type is int and isinstance(value, bool): + # bool is a subclass of int, so a plain isinstance(value, int) check below + # would silently accept it and build e.g. UsageLimits(request_limit=False), + # which only fails deep inside pydantic-ai. Exclude it explicitly here. + raise ValueError( + f"usage_limits[{field!r}] must be an integer, not a bool (got {value!r}); " + "if it is templated, check the rendered value." + ) + elif field_type is int and isinstance(value, float) and math.isfinite(value): + # Non-finite floats (inf/nan) deliberately fall through unchanged so the + # finite check in _validate_range below reports them as "not finite" -- + # checking is_integer() first would misreport them as "not an integer". + if not value.is_integer(): + raise ValueError( + f"usage_limits[{field!r}] must be an integer (got {value!r}); " + "if it is templated, check the rendered value." + ) + value = int(value) + + if field_type in (Decimal, int): Review Comment: Gating on `field_type in (Decimal, int)` leaves the one `bool` field with no shape check at all, so any non-`str` value reaches `UsageLimits` untouched. Running this module directly, `count_tokens_before_request` accepts `[]`, `{}`, `0`, `1.5` and `Decimal("0")`, all of which pydantic-ai then reads by truthiness, so the pre-flight token check is off while the Dag says it is on. That is the outcome the comment at line 96-100 says this module exists to prevent, just reached through a native-mode render rather than a string. The same gate lets `request_limit=Decimal("3.5")` through, slipping the non-integral check you added right above for a plain `3.5`. Keying the guard on the field's own declared type (`if not isinstance(value, field_type): raise ...`) covers all three. ########## providers/common/ai/docs/operators/llm.rst: ########## @@ -119,16 +119,51 @@ 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 -- a Variable that exists but is empty 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`` has no effect without halting execution (a + ``CostNotFoundWarning`` is emitted instead of a failure). And like the other knobs + above, setting ``cost_limit`` + alone still inherits the ``request_limit=50`` default — see the ``request_limit`` note + above. Note that ``cost_limit`` only caps the operator's own LLM calls -- + the meta-agent that ``LLMRetryPolicy`` runs to classify a failed task is a separate, + uncapped LLM call; see :doc:`../retry_policies`. For a budget tracked across runs + rather than this per-run cap, pass a + `SpendLimits <https://pydantic.dev/docs/ai/harness/spend/>`__ capability via + ``agent_params`` (see :ref:`capabilities-passthrough`; requires the ``code-mode`` extra). Review Comment: Correcting my own pointer above, which is what put this sentence here: `SpendLimits.store` defaults to `InMemorySpendStore`, whose docstring says "It does not enforce a budget across processes: every worker of a queue would keep its own count, which is what a shared store such as `RedisSpendStore` is for." Every Airflow task instance is a fresh worker process, so a `window='day'` budget resets on every run, which is the per-run ceiling this sentence is positioning against. The cross-run claim only holds once a shared store is passed, so the bullet should name that rather than leave the default implied. Also worth bumping the extra: `pydantic_ai_harness.spend` first appears in harness v0.17.0 and is absent in v0.16.0, while the `code-mode` floor is `pydantic-ai-harness[codemode]>=0.3.0`. ########## providers/common/ai/docs/operators/llm.rst: ########## @@ -119,16 +119,51 @@ 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 -- a Variable that exists but is empty 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`` has no effect without halting execution (a Review Comment: "has no effect without halting execution" reads as "has no effect unless execution halts", which is the opposite of the point. What you want to say is that it is inert but not silent, e.g. "`cost_limit` is not enforced; a `CostNotFoundWarning` is emitted rather than failing the run". The same phrase landed in `agent.rst:494` and `example_dags/example_llm.py:145`. -- 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]
