|
| 1 | +"""Canonicalize the two OpenAI output-token fields onto a single field. |
| 2 | +
|
| 3 | +WHY THIS EXISTS |
| 4 | +--------------- |
| 5 | +The OpenAI chat schema carries two output-token fields: the original |
| 6 | +``max_tokens`` and its replacement ``max_completion_tokens``. A request can |
| 7 | +arrive with both — most commonly because a proxy deployment configures one of |
| 8 | +them as a ceiling in ``litellm_params`` while the client sends the other. When |
| 9 | +that happens today, what reaches the provider depends on the order the |
| 10 | +provider's ``map_openai_params`` happens to iterate, and the result is wrong in |
| 11 | +two different ways: |
| 12 | +
|
| 13 | + * Providers that collapse both onto one field do so with LAST-WINS |
| 14 | + semantics, because both branches assign the same output key. ``anthropic`` |
| 15 | + (``max_tokens``) and ``bedrock`` converse (``maxTokens``) both do this, and |
| 16 | + ``max_completion_tokens`` is iterated second, so a client asking for 50 |
| 17 | + output tokens against a deployment configured with a 64000 ceiling gets |
| 18 | + 64000 — the caller's limit is silently discarded. ``openai_like`` is worse: |
| 19 | + it replaces unconditionally, so the ceiling always wins. |
| 20 | +
|
| 21 | + * Providers that forward both fields unchanged send both to the API. |
| 22 | + Azure 2025+ API versions reject that outright: |
| 23 | +
|
| 24 | + AzureException BadRequestError - Setting 'max_tokens' and |
| 25 | + 'max_completion_tokens' at the same time is not supported. |
| 26 | +
|
| 27 | +Neither failure mode is provider-specific in nature, so neither belongs in a |
| 28 | +provider transform. This module resolves both fields to one, once, before the |
| 29 | +provider mapping runs. |
| 30 | +
|
| 31 | +THE RULES |
| 32 | +--------- |
| 33 | +1. TIGHTER WINS. When both fields carry a usable value, the smaller one is |
| 34 | + kept. A deployment ceiling can therefore never be RAISED by a client, and a |
| 35 | + client's tighter request can never be widened to the ceiling. |
| 36 | +
|
| 37 | +2. ONE FIELD OUT. When a preferred field is known, only that field survives. |
| 38 | + The preference comes from the provider config |
| 39 | + (``BaseConfig.get_preferred_max_tokens_param``), or from an explicit |
| 40 | + per-request/per-deployment ``use_max_completion_tokens`` directive, which |
| 41 | + overrides the provider's own detection. |
| 42 | +
|
| 43 | +3. NEVER INVENT A VALUE. If neither field holds a positive integer, nothing is |
| 44 | + changed. A ``max_tokens`` of ``0``, ``None``, a string, or a bool must not |
| 45 | + become a ``max_completion_tokens`` that truncates every response. |
| 46 | +""" |
| 47 | + |
| 48 | +from typing import Any, Dict, Optional, Sequence |
| 49 | + |
| 50 | +MAX_TOKENS_PARAM = "max_tokens" |
| 51 | +MAX_COMPLETION_TOKENS_PARAM = "max_completion_tokens" |
| 52 | + |
| 53 | +MAX_TOKENS_PARAMS = (MAX_TOKENS_PARAM, MAX_COMPLETION_TOKENS_PARAM) |
| 54 | + |
| 55 | + |
| 56 | +def preferred_param_for_directive( |
| 57 | + use_max_completion_tokens: Optional[bool], |
| 58 | +) -> Optional[str]: |
| 59 | + """Translate the ``use_max_completion_tokens`` directive to a field name. |
| 60 | +
|
| 61 | + ``None`` means "no directive given" — fall back to provider detection. |
| 62 | + """ |
| 63 | + if use_max_completion_tokens is None: |
| 64 | + return None |
| 65 | + return ( |
| 66 | + MAX_COMPLETION_TOKENS_PARAM |
| 67 | + if use_max_completion_tokens |
| 68 | + else MAX_TOKENS_PARAM |
| 69 | + ) |
| 70 | + |
| 71 | + |
| 72 | +def _positive_int(value: Any) -> Optional[int]: |
| 73 | + """Return ``value`` as a positive int, or None if it isn't one. |
| 74 | +
|
| 75 | + ``bool`` is rejected explicitly because it is an ``int`` subclass. |
| 76 | + """ |
| 77 | + if isinstance(value, bool) or not isinstance(value, int): |
| 78 | + return None |
| 79 | + return value if value > 0 else None |
| 80 | + |
| 81 | + |
| 82 | +def resolve_max_tokens_params( |
| 83 | + non_default_params: Dict[str, Any], |
| 84 | + supported_params: Sequence[str], |
| 85 | + preferred_param: Optional[str] = None, |
| 86 | +) -> Optional[str]: |
| 87 | + """Collapse ``max_tokens`` / ``max_completion_tokens`` in place. |
| 88 | +
|
| 89 | + Args: |
| 90 | + non_default_params: mutated in place; the params about to be mapped. |
| 91 | + supported_params: the params this model/provider accepts. A preference |
| 92 | + for a field the provider does not accept is ignored rather than |
| 93 | + forced, so the resolution can never leave a request with no |
| 94 | + output-token ceiling at all. |
| 95 | + preferred_param: the field to keep, or None to let the caller's own |
| 96 | + field stand when only one was sent. |
| 97 | +
|
| 98 | + Returns: |
| 99 | + The field that survived, or None when nothing was changed. |
| 100 | + """ |
| 101 | + present = [p for p in MAX_TOKENS_PARAMS if p in non_default_params] |
| 102 | + if not present: |
| 103 | + return None |
| 104 | + |
| 105 | + values = [ |
| 106 | + v |
| 107 | + for v in (_positive_int(non_default_params[p]) for p in present) |
| 108 | + if v is not None |
| 109 | + ] |
| 110 | + if not values: |
| 111 | + # Rule 3 — nothing usable to move or tighten. Still strip a field the |
| 112 | + # provider is known to reject: an unusable value (0, a string) is not a |
| 113 | + # ceiling worth preserving, and leaving it on a field the provider |
| 114 | + # rejects turns a garbage request into a guaranteed 400. |
| 115 | + if preferred_param is not None and preferred_param in supported_params: |
| 116 | + for param in MAX_TOKENS_PARAMS: |
| 117 | + if param != preferred_param: |
| 118 | + non_default_params.pop(param, None) |
| 119 | + return None |
| 120 | + resolved = min(values) |
| 121 | + |
| 122 | + target: Optional[str] = None |
| 123 | + if preferred_param is not None and preferred_param in supported_params: |
| 124 | + target = preferred_param |
| 125 | + elif len(present) == 1: |
| 126 | + # One field, no preference: the caller's choice already is canonical. |
| 127 | + return None |
| 128 | + else: |
| 129 | + # Both fields with no provider preference. Collapsing is still |
| 130 | + # required — leaving both is what makes the last-wins provider maps |
| 131 | + # pick the looser value. Prefer `max_tokens`: every provider |
| 132 | + # understands it, and the reasoning-model configs that want |
| 133 | + # `max_completion_tokens` rename it themselves downstream. |
| 134 | + target = ( |
| 135 | + MAX_TOKENS_PARAM |
| 136 | + if MAX_TOKENS_PARAM in supported_params |
| 137 | + else MAX_COMPLETION_TOKENS_PARAM |
| 138 | + ) |
| 139 | + |
| 140 | + for param in MAX_TOKENS_PARAMS: |
| 141 | + if param != target: |
| 142 | + non_default_params.pop(param, None) |
| 143 | + non_default_params[target] = resolved |
| 144 | + return target |
0 commit comments