kaxil commented on code in PR #71403:
URL: https://github.com/apache/airflow/pull/71403#discussion_r3992382370
##########
providers/common/ai/docs/operators/llm.rst:
##########
@@ -119,16 +119,48 @@ 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
Review Comment:
Pricing keys on the model name, not the endpoint, so this is wrong for the
setup the provider's own docs recommend. `_cost.py` falls back to
`provider_id=provider_name` on `LookupError` (lines 41 and 48), and at the
2.23.0 floor `gpt-4o` behind `http://vllm.internal:8000/v1` prices fine while
`llama3.2` on the same endpoint raises. Since `self_hosted_models.rst` tells
vLLM users `openai:<model>` is the only option, that setup does get priced, at
OpenAI list rates rather than the gateway's real cost, so the cap can fire on
money nobody spent. `agent.rst:493` already keys the sentence on whether the
model can be priced, which is the wording that holds.
##########
providers/common/ai/src/airflow/providers/common/ai/utils/usage.py:
##########
@@ -0,0 +1,307 @@
+# 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:
Review Comment:
The templated-string path rejects integral values the native path accepts.
On `request_limit` at 2.23.0: `5.0` gives 5 but `"5.0"` raises, `1e3` gives
1000 but `"1e3"` raises, `Decimal("5.0")` gives 5 but `"5.000"` raises. Jinja
`/` is true division, so `{"request_limit": "{{ params.total / params.n }}"}`
hard-fails under the default renderer and succeeds under
`render_template_as_native_obj=True`, the same template decided by a Dag-level
flag, in the module whose job is making templated values behave like literals.
Falling back to the same integral test once `int(value)` raises would line the
two up and leave `"inf"` and `"abc"` on the current message.
##########
providers/common/ai/src/airflow/providers/common/ai/utils/usage.py:
##########
@@ -0,0 +1,307 @@
+# 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
Review Comment:
A single-parameter generic resolves to its element type rather than raising:
`list[int]` gives `int` and `set[str]` gives `str`, since both pass the
`len(args) == 1` gate and `isinstance(int, type)` holds. `dict[str, int]`
raises on arity, not on being a generic, so `test_parameterized_generic_raises`
is green for the wrong reason. A `typing.get_origin()` check ahead of the arity
reduction, rejecting any origin that is not a union, closes it. Nothing trips
this at 2.23.0, but future fields are the whole reason the resolution is lazy.
--
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]