Convert per-token pricing from upstream into per-1M-token ModelPricing.
(raw: dict | None)
| 150 | # --------------------------------------------------------------------------- |
| 151 | |
| 152 | def _parse_upstream_pricing(raw: dict | None) -> ModelPricing: |
| 153 | """Convert per-token pricing from upstream into per-1M-token ModelPricing.""" |
| 154 | if not raw or not isinstance(raw, dict): |
| 155 | return ModelPricing(5.0, 25.0) |
| 156 | if "prompt" not in raw or "completion" not in raw: |
| 157 | return ModelPricing(5.0, 25.0) |
| 158 | try: |
| 159 | prompt_price = float(raw.get("prompt", 0)) |
| 160 | completion_price = float(raw.get("completion", 0)) |
| 161 | if ( |
| 162 | not math.isfinite(prompt_price) |
| 163 | or not math.isfinite(completion_price) |
| 164 | or prompt_price < 0 |
| 165 | or completion_price < 0 |
| 166 | ): |
| 167 | return ModelPricing(5.0, 25.0) |
| 168 | input_price = prompt_price * 1_000_000 |
| 169 | output_price = completion_price * 1_000_000 |
| 170 | cached_input = raw.get("input_cache_reads") |
| 171 | cache_write = raw.get("input_cache_writes") |
| 172 | |
| 173 | def optional_price(value: object) -> float | None: |
| 174 | if value in (None, ""): |
| 175 | return None |
| 176 | parsed = float(value) |
| 177 | if not math.isfinite(parsed) or parsed < 0: |
| 178 | return None |
| 179 | return round(parsed * 1_000_000, 4) |
| 180 | |
| 181 | return ModelPricing( |
| 182 | input_price=round(input_price, 4), |
| 183 | output_price=round(output_price, 4), |
| 184 | cached_input_price=optional_price(cached_input), |
| 185 | cache_write_price=optional_price(cache_write), |
| 186 | ) |
| 187 | except (ValueError, TypeError): |
| 188 | return ModelPricing(5.0, 25.0) |
| 189 | |
| 190 | |
| 191 | # --------------------------------------------------------------------------- |