Files
junction/tests/usage.sh
T
Hermes 04ba239633 Verbrauch und Kosten pro Anfrage, Preise aus einer Tabelle
Jede Antwort trägt jetzt, was sie gekostet hat:

  X-Junction-Tokens-In: 1200
  X-Junction-Tokens-Out: 300
  X-Junction-Cost-Usd: 0.000426

und im Log:

  usage model=deepseek-v4.1-flash in=1200 cached=1000 out=300 cost_usd=0.000426

Die Preise stehen in examples/prices.conf, abgeschrieben von der Preisseite des
Anbieters (ollama.com/pricing, 5.11.2026) — pro Million Token, mit Off-Peak-Preisen,
Monatsbudget und Anfragefenster für die Go-Modelle.

Zwei Entscheidungen, die wichtiger sind als die Zahlen:

  Kein "*"-Eintrag. Ein Modell ohne Zeile kostet unbekannt, nicht null, und das steht
  dann auch so im Log. Eine erfundene Null in einem Kostenbericht ist schlimmer als
  gar keine Zahl.

  Ohne Preistabelle wird gar nichts gerechnet — dann fehlt die Kopfzeile, statt eine
  Null zu zeigen.

Damit die Antwort vollständig vorliegt, wird bei gesetzter Tabelle auch ohne Cache
vollständig gelesen; ein nicht gestreamter JSON-Rumpf ist ohnehin endlich.

Dazu Single-Flight: gleiche Anfragen, die gleichzeitig eintreffen, warten auf die
erste und teilen ihr Ergebnis. Drei identische Anfragen an ein Ziel mit 3 s Antwortzeit
dauern 3 s statt 9, ein Aufruf geht raus, zwei werden bedient.

111 Prüfungen, keine Fehler.
2026-11-05 09:55:47 +00:00

100 lines
4.1 KiB
Bash

#!/bin/bash
# Wird von tests/run.sh eingebunden: Verbrauch und Kosten pro Anfrage.
echo "== 24. Verbrauch und Kosten pro Anfrage =="
UPORT=$((PORT+71))
USPORT=$((PORT+72))
cat > "$TMP/ustub.py" <<'PY'
import http.server, json, sys
class H(http.server.BaseHTTPRequestHandler):
def log_message(self, *a): pass
def do_POST(self):
n = int(self.headers.get("Content-Length", "0"))
self.rfile.read(n)
out = json.dumps({"id": "u",
"choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}}],
"usage": {"prompt_tokens": 1200, "completion_tokens": 300,
"prompt_tokens_details": {"cached_tokens": 1000}}}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(out)))
self.end_headers()
self.wfile.write(out)
http.server.HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
PY
python3 "$TMP/ustub.py" "$USPORT" & PIDS+=($!)
sleep 0.6
cat > "$TMP/prices.conf" <<'CFG'
# test/preis in cached out
test/preis 0.30 0.006 1.20
CFG
cat > "$TMP/usage.conf" <<CFG
listen 127.0.0.1:$UPORT
prices $TMP/prices.conf
cache_ttl 0
endpoint a { base http://127.0.0.1:$USPORT/v1; timeout 20 }
req for "*" pass a
CFG
./junction --config "$TMP/usage.conf" > "$TMP/usage.log" 2>&1 &
PIDS+=($!)
sleep 0.8
hdr() {
curl -s -m 10 -D - -o /dev/null -X POST -H 'Content-Type: application/json' -d "$1" \
"http://127.0.0.1:$UPORT/v1/chat/completions" | tr -d '\r' \
| sed -n "s/^[Xx]-[Jj]unction-${2}: //p"
}
PRICED='{"model":"test/preis","messages":[{"role":"user","content":"hi"}],"max_tokens":50}'
# Eine Anfrage, alle Kopfzeilen — sonst zählt der Test drei Aufrufe statt einem.
ALL=$(curl -s -m 10 -D - -o /dev/null -X POST -H 'Content-Type: application/json' -d "$PRICED" \
"http://127.0.0.1:$UPORT/v1/chat/completions" | tr -d '\r')
IN=$(printf '%s' "$ALL" | sed -n 's/^[Xx]-[Jj]unction-[Tt]okens-[Ii]n: //p')
OUT=$(printf '%s' "$ALL" | sed -n 's/^[Xx]-[Jj]unction-[Tt]okens-[Oo]ut: //p')
COST=$(printf '%s' "$ALL" | sed -n 's/^[Xx]-[Jj]unction-[Cc]ost-[Uu]sd: //p')
[ "$IN" = "1200" ] && ok "input tokens are reported in the response headers" \
|| bad "input tokens missing (got '${IN:-none}')"
[ "$OUT" = "300" ] && ok "output tokens are reported in the response headers" \
|| bad "output tokens missing (got '${OUT:-none}')"
# 1000 von 1200 Eingaben waren zwischengespeichert: 200*0.30 + 1000*0.006 + 300*1.20,
# alles durch eine Million.
WANT="0.000426"
[ "$COST" = "$WANT" ] && ok "cost uses the cached-input price where the provider reports it" \
|| bad "cost was '${COST:-none}', expected $WANT"
UNKNOWN='{"model":"gibt-es-nicht","messages":[{"role":"user","content":"hi"}],"max_tokens":50}'
UCOST=$(hdr "$UNKNOWN" "Cost-Usd")
[ "$UCOST" = "unknown" ] && ok "a model without a price reports unknown, not zero" \
|| bad "unpriced model reported '${UCOST:-none}'"
STATUS=$(curl -s -m 5 "http://127.0.0.1:$UPORT/status")
case "$STATUS" in
*'"cost_unknown":1'*) ok "/status counts the unpriced request separately" ;;
*) bad "/status does not count unpriced requests" ;;
esac
case "$STATUS" in
*'"tokens_in":2400'*) ok "/status accumulates tokens across requests" ;;
*) bad "/status token totals are wrong" ;;
esac
# Ohne Preistabelle darf gar nichts gerechnet werden — nur gezählt.
cat > "$TMP/noprice.conf" <<CFG
listen 127.0.0.1:$((UPORT+1))
cache_ttl 0
endpoint a { base http://127.0.0.1:$USPORT/v1; timeout 20 }
req for "*" pass a
CFG
./junction --config "$TMP/noprice.conf" > "$TMP/noprice.log" 2>&1 &
PIDS+=($!)
sleep 0.8
NP=$(curl -s -m 10 -D - -o /dev/null -X POST -H 'Content-Type: application/json' -d "$PRICED" \
"http://127.0.0.1:$((UPORT+1))/v1/chat/completions" | tr -d '\r' | sed -n 's/^[Xx]-[Jj]unction-[Cc]ost-Usd: //p')
[ -z "$NP" ] && ok "without a price table no cost header is invented" \
|| bad "a cost was reported without any price table ('$NP')"