#!/bin/sh
# Price models in New API from models.dev's list prices.
# ./prices.sh PROVIDER:MODEL[=NAME] ...
# PROVIDER and MODEL are models.dev's IDs; NAME is the model name in New API
# (default MODEL). Each price becomes a billing expression in USD per million
# tokens: p input, c output, cr cache reads, cc cache writes, with a
# long-context tier where models.dev has one. Needs ./api next to it.
set -eu
cd "$(dirname "$0")"
[ $# -gt 0 ] || { sed -n '2,8s/^# \{0,1\}//p' "$0"; exit 1; }
curl -fsS https://models.dev/api.json -o /tmp/models.dev.json
new=$(printf '%s\n' "$@" | jq -R . | jq -sc --slurpfile md /tmp/models.dev.json '
def terms: "p * \(.input) + c * \(.output)"
+ (if .cache_read then " + cr * \(.cache_read)" else "" end)
+ (if .cache_write then " + cc * \(.cache_write)" else "" end);
map(capture("^(?
[^:]+):(?[^=]+)(=(?.+))?$") | . as $a
| ($md[0][$a.p].models[$a.m].cost // error("not on models.dev: \($a.p):\($a.m)")) as $c
| ([$c.tiers[]? | select(.tier.type == "context")] | first) as $t
| { (.n // .m): (if $t then "len <= \($t.tier.size) ? tier(\"standard\", \($c | terms)) : tier(\"long_context\", \($t | terms))"
else "tier(\"standard\", \($c | terms))" end) })
| add')
opts=$(./api GET /api/option/)
for key in billing_setting.billing_expr billing_setting.billing_mode; do
old=$(printf '%s' "$opts" | jq -r --arg k "$key" '.data[] | select(.key == $k) | .value')
[ -n "$old" ] || old='{}'
if [ "$key" = billing_setting.billing_expr ]; then
val=$(printf '%s' "$old" | jq -c --argjson new "$new" '. + $new')
else
val=$(printf '%s' "$old" | jq -c --argjson new "$new" '. + ($new | map_values("tiered_expr"))')
fi
./api PUT /api/option/ "$(jq -nc --arg k "$key" --arg v "$val" '{key: $k, value: $v}')" |
jq -e .success >/dev/null || { echo "prices: couldn't save $key" >&2; exit 1; }
done
printf '%s' "$new" | jq -r 'to_entries[] | "\(.key): \(.value)"'