Spaces:
Sleeping
Sleeping
File size: 69,545 Bytes
260d3dd 29ea1dd 260d3dd dbe5f96 260d3dd e370b75 260d3dd cd16e60 260d3dd 29ea1dd 3dcdd9b 29ea1dd 3dcdd9b 29ea1dd e370b75 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 | # SPDX-License-Identifier: MIT
# Copyright (c) 2026 Mirrowel
import time
import uuid
# Phase 1: Minimal imports for arg parsing and TUI
import asyncio
import os
from pathlib import Path
import sys
import argparse
import logging
# --- Argument Parsing (BEFORE heavy imports) ---
parser = argparse.ArgumentParser(description="API Key Proxy Server")
parser.add_argument(
"--host", type=str, default="0.0.0.0", help="Host to bind the server to."
)
parser.add_argument("--port", type=int, default=8000, help="Port to run the server on.")
parser.add_argument(
"--enable-request-logging",
action="store_true",
help="Enable transaction logging in the library (logs request/response with provider correlation).",
)
parser.add_argument(
"--enable-raw-logging",
action="store_true",
help="Enable raw I/O logging at proxy boundary (captures unmodified HTTP data, disabled by default).",
)
parser.add_argument(
"--add-credential",
action="store_true",
help="Launch the interactive tool to add a new OAuth credential.",
)
# [CONCURRENCY FIX #1] - Multi-worker support for handling 10-20+ concurrent requests
parser.add_argument(
"--workers",
type=int,
default=int(os.getenv("UVICORN_WORKERS", "1")),
help="Number of Uvicorn worker processes. For I/O-bound proxy work, use 2-4x CPU count. (env: UVICORN_WORKERS, default: 1)",
)
args, _ = parser.parse_known_args()
# Add the 'src' directory to the Python path
sys.path.append(str(Path(__file__).resolve().parent.parent))
# Check if we should launch TUI (no arguments = TUI mode)
if len(sys.argv) == 1:
# TUI MODE - Load ONLY what's needed for the launcher (fast path!)
from proxy_app.launcher_tui import run_launcher_tui
run_launcher_tui()
# Launcher modifies sys.argv and returns, or exits if user chose Exit
# If we get here, user chose "Run Proxy" and sys.argv is modified
# Re-parse arguments with modified sys.argv
args = parser.parse_args()
# Check if credential tool mode (also doesn't need heavy proxy imports)
if args.add_credential:
from rotator_library.credential_tool import run_credential_tool
run_credential_tool()
sys.exit(0)
# If we get here, we're ACTUALLY running the proxy - NOW show startup messages and start timer
_start_time = time.time()
# Load all .env files from root folder (main .env first, then any additional *.env files)
from dotenv import load_dotenv
from glob import glob
# Get the application root directory (EXE dir if frozen, else CWD)
# Inlined here to avoid triggering heavy rotator_library imports before loading screen
if getattr(sys, "frozen", False):
_root_dir = Path(sys.executable).parent
else:
_root_dir = Path.cwd()
# [HUGGING FACE SUPPORT] If a bulk environment block is provided via Secret, save it to a file
# This allows users to paste their entire .env content into a single HF Secret called CONFIG_ENV
_bulk_env = os.getenv("CONFIG_ENV")
if _bulk_env:
_bulk_env_file = _root_dir / "bulk_config.env"
with open(_bulk_env_file, "w", encoding="utf-8") as _f:
_f.write(_bulk_env)
print(f"📝 Detected 'CONFIG_ENV' secret, saved to '{_bulk_env_file.name}'")
# Load main .env first
load_dotenv(_root_dir / ".env")
# Load any additional .env files (e.g., antigravity_all_combined.env, gemini_cli_all_combined.env)
_env_files_found = list(_root_dir.glob("*.env"))
for _env_file in sorted(_root_dir.glob("*.env")):
if _env_file.name != ".env": # Skip main .env (already loaded)
load_dotenv(_env_file, override=False) # Don't override existing values
# Log discovered .env files for deployment verification
if _env_files_found:
_env_names = [_ef.name for _ef in _env_files_found]
print(f"📁 Loaded {len(_env_files_found)} .env file(s): {', '.join(_env_names)}")
# Get proxy API key for display
proxy_api_key = os.getenv("PROXY_API_KEY")
if proxy_api_key:
key_display = f"✓ {proxy_api_key}"
else:
key_display = "✗ Not Set (INSECURE - anyone can access!)"
print("━" * 70)
print(f"Starting proxy on {args.host}:{args.port}")
print(f"Proxy API Key: {key_display}")
print(f"GitHub: https://github.com/Mirrowel/LLM-API-Key-Proxy")
print("━" * 70)
print("Loading server components...")
# Phase 2: Load Rich for loading spinner (lightweight)
from rich.console import Console
_console = Console()
# Phase 3: Heavy dependencies with granular loading messages
print(" → Loading FastAPI framework...")
with _console.status("[dim]Loading FastAPI framework...", spinner="dots"):
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse, JSONResponse
from fastapi.security import APIKeyHeader
print(" → Loading core dependencies...")
with _console.status("[dim]Loading core dependencies...", spinner="dots"):
from dotenv import load_dotenv
import colorlog
import json
from typing import AsyncGenerator, Any, List, Optional, Union
from pydantic import BaseModel, ConfigDict, Field
# --- Early Log Level Configuration ---
logging.getLogger("LiteLLM").setLevel(logging.WARNING)
print(" → Loading LiteLLM library...")
with _console.status("[dim]Loading LiteLLM library...", spinner="dots"):
import litellm
# Phase 4: Application imports with granular loading messages
print(" → Initializing proxy core...")
with _console.status("[dim]Initializing proxy core...", spinner="dots"):
from rotator_library import RotatingClient
from rotator_library.credential_manager import CredentialManager
from rotator_library.background_refresher import BackgroundRefresher
from rotator_library.model_info_service import init_model_info_service
from proxy_app.request_logger import log_request_to_console
from proxy_app.batch_manager import EmbeddingBatcher
from proxy_app.detailed_logger import RawIOLogger
print(" → Discovering provider plugins...")
# Provider lazy loading happens during import, so time it here
_provider_start = time.time()
with _console.status("[dim]Discovering provider plugins...", spinner="dots"):
from rotator_library import (
PROVIDER_PLUGINS,
) # This triggers lazy load via __getattr__
_provider_time = time.time() - _provider_start
# Get count after import (without timing to avoid double-counting)
_plugin_count = len(PROVIDER_PLUGINS)
# --- Pydantic Models ---
class EmbeddingRequest(BaseModel):
model: str
input: Union[str, List[str]]
input_type: Optional[str] = None
dimensions: Optional[int] = None
user: Optional[str] = None
class ModelCard(BaseModel):
"""Basic model card for minimal response."""
id: str
object: str = "model"
created: int = Field(default_factory=lambda: int(time.time()))
owned_by: str = "Mirro-Proxy"
class ModelCapabilities(BaseModel):
"""Model capability flags."""
tool_choice: bool = False
function_calling: bool = False
reasoning: bool = False
vision: bool = False
system_messages: bool = True
prompt_caching: bool = False
assistant_prefill: bool = False
class EnrichedModelCard(BaseModel):
"""Extended model card with pricing and capabilities."""
id: str
object: str = "model"
created: int = Field(default_factory=lambda: int(time.time()))
owned_by: str = "unknown"
# Pricing (optional - may not be available for all models)
input_cost_per_token: Optional[float] = None
output_cost_per_token: Optional[float] = None
cache_read_input_token_cost: Optional[float] = None
cache_creation_input_token_cost: Optional[float] = None
# Limits (optional)
max_input_tokens: Optional[int] = None
max_output_tokens: Optional[int] = None
context_window: Optional[int] = None
# Capabilities
mode: str = "chat"
supported_modalities: List[str] = Field(default_factory=lambda: ["text"])
supported_output_modalities: List[str] = Field(default_factory=lambda: ["text"])
capabilities: Optional[ModelCapabilities] = None
# Debug info (optional)
_sources: Optional[List[str]] = None
_match_type: Optional[str] = None
model_config = ConfigDict(extra="allow") # Allow extra fields from the service
class ModelList(BaseModel):
"""List of models response."""
object: str = "list"
data: List[ModelCard]
class EnrichedModelList(BaseModel):
"""List of enriched models with pricing and capabilities."""
object: str = "list"
data: List[EnrichedModelCard]
# --- Anthropic API Models (imported from library) ---
from rotator_library.anthropic_compat import (
AnthropicMessagesRequest,
AnthropicCountTokensRequest,
)
# Calculate total loading time
_elapsed = time.time() - _start_time
print(
f"✓ Server ready in {_elapsed:.2f}s ({_plugin_count} providers discovered in {_provider_time:.2f}s)"
)
# Clear screen and reprint header for clean startup view
# This pushes loading messages up (still in scroll history) but shows a clean final screen
import os as _os_module
_os_module.system("cls" if _os_module.name == "nt" else "clear")
# Reprint header
print("━" * 70)
print(f"Starting proxy on {args.host}:{args.port}")
print(f"Proxy API Key: {key_display}")
print(f"GitHub: https://github.com/Mirrowel/LLM-API-Key-Proxy")
print("━" * 70)
print(
f"✓ Server ready in {_elapsed:.2f}s ({_plugin_count} providers discovered in {_provider_time:.2f}s)"
)
# Note: Debug logging will be added after logging configuration below
# --- Logging Configuration ---
# Import path utilities here (after loading screen) to avoid triggering heavy imports early
from rotator_library.utils.paths import get_logs_dir, get_data_file
LOG_DIR = get_logs_dir(_root_dir)
# Configure a console handler with color (INFO and above only, no DEBUG)
console_handler = colorlog.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
formatter = colorlog.ColoredFormatter(
"%(log_color)s%(message)s",
log_colors={
"DEBUG": "cyan",
"INFO": "green",
"WARNING": "yellow",
"ERROR": "red",
"CRITICAL": "red,bg_white",
},
)
console_handler.setFormatter(formatter)
# Configure a file handler for INFO-level logs and higher
info_file_handler = logging.FileHandler(LOG_DIR / "proxy.log", encoding="utf-8")
info_file_handler.setLevel(logging.INFO)
info_file_handler.setFormatter(
logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
)
# Configure a dedicated file handler for all DEBUG-level logs
debug_file_handler = logging.FileHandler(LOG_DIR / "proxy_debug.log", encoding="utf-8")
debug_file_handler.setLevel(logging.DEBUG)
debug_file_handler.setFormatter(
logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
)
# Create a filter to ensure the debug handler ONLY gets DEBUG messages from the rotator_library
class RotatorDebugFilter(logging.Filter):
def filter(self, record):
return record.levelno == logging.DEBUG and record.name.startswith(
"rotator_library"
)
debug_file_handler.addFilter(RotatorDebugFilter())
# Configure a console handler with color
console_handler = colorlog.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
formatter = colorlog.ColoredFormatter(
"%(log_color)s%(message)s",
log_colors={
"DEBUG": "cyan",
"INFO": "green",
"WARNING": "yellow",
"ERROR": "red",
"CRITICAL": "red,bg_white",
},
)
console_handler.setFormatter(formatter)
# Add a filter to prevent any LiteLLM logs from cluttering the console
class NoLiteLLMLogFilter(logging.Filter):
def filter(self, record):
return not record.name.startswith("LiteLLM")
console_handler.addFilter(NoLiteLLMLogFilter())
# Get the root logger and set it to DEBUG to capture all messages
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG)
# Add all handlers to the root logger
root_logger.addHandler(info_file_handler)
root_logger.addHandler(console_handler)
root_logger.addHandler(debug_file_handler)
# Silence other noisy loggers by setting their level higher than root
logging.getLogger("uvicorn").setLevel(logging.WARNING)
logging.getLogger("httpx").setLevel(logging.WARNING)
# Isolate LiteLLM's logger to prevent it from reaching the console.
# We will capture its logs via the logger_fn callback in the client instead.
litellm_logger = logging.getLogger("LiteLLM")
litellm_logger.handlers = []
litellm_logger.propagate = False
# Now that logging is configured, log the module load time to debug file only
logging.debug(f"Modules loaded in {_elapsed:.2f}s")
# Load environment variables from .env file
load_dotenv(_root_dir / ".env")
# --- Configuration ---
USE_EMBEDDING_BATCHER = False
ENABLE_REQUEST_LOGGING = args.enable_request_logging
ENABLE_RAW_LOGGING = args.enable_raw_logging
if ENABLE_REQUEST_LOGGING:
logging.info(
"Transaction logging is enabled (library-level with provider correlation)."
)
if ENABLE_RAW_LOGGING:
logging.info("Raw I/O logging is enabled (proxy boundary, unmodified HTTP data).")
PROXY_API_KEY = os.getenv("PROXY_API_KEY")
# Note: PROXY_API_KEY validation moved to server startup to allow credential tool to run first
# Discover API keys from environment variables
api_keys = {}
for key, value in os.environ.items():
if "_API_KEY" in key and key != "PROXY_API_KEY":
provider = key.split("_API_KEY")[0].lower()
if provider not in api_keys:
api_keys[provider] = []
api_keys[provider].append(value)
# Load model ignore lists from environment variables
ignore_models = {}
for key, value in os.environ.items():
if key.startswith("IGNORE_MODELS_"):
provider = key.replace("IGNORE_MODELS_", "").lower()
models_to_ignore = [
model.strip() for model in value.split(",") if model.strip()
]
ignore_models[provider] = models_to_ignore
logging.debug(
f"Loaded ignore list for provider '{provider}': {models_to_ignore}"
)
# Load model whitelist from environment variables
whitelist_models = {}
for key, value in os.environ.items():
if key.startswith("WHITELIST_MODELS_"):
provider = key.replace("WHITELIST_MODELS_", "").lower()
models_to_whitelist = [
model.strip() for model in value.split(",") if model.strip()
]
whitelist_models[provider] = models_to_whitelist
logging.debug(
f"Loaded whitelist for provider '{provider}': {models_to_whitelist}"
)
# Load max concurrent requests per key from environment variables
max_concurrent_requests_per_key = {}
for key, value in os.environ.items():
if key.startswith("MAX_CONCURRENT_REQUESTS_PER_KEY_"):
provider = key.replace("MAX_CONCURRENT_REQUESTS_PER_KEY_", "").lower()
try:
max_concurrent = int(value)
if max_concurrent < 1:
logging.warning(
f"Invalid max_concurrent value for provider '{provider}': {value}. Must be >= 1. Using default (1)."
)
max_concurrent = 1
max_concurrent_requests_per_key[provider] = max_concurrent
logging.debug(
f"Loaded max concurrent requests for provider '{provider}': {max_concurrent}"
)
except ValueError:
logging.warning(
f"Invalid max_concurrent value for provider '{provider}': {value}. Using default (1)."
)
# --- Lifespan Management ---
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Manage the RotatingClient's lifecycle with the app's lifespan."""
# [MODIFIED] Perform skippable OAuth initialization at startup
skip_oauth_init = os.getenv("SKIP_OAUTH_INIT_CHECK", "false").lower() == "true"
# The CredentialManager now handles all discovery, including .env overrides.
# We pass all environment variables to it for this purpose.
cred_manager = CredentialManager(os.environ)
oauth_credentials = cred_manager.discover_and_prepare()
if not skip_oauth_init and oauth_credentials:
logging.info("Starting OAuth credential validation and deduplication...")
processed_emails = {} # email -> {provider: path}
credentials_to_initialize = {} # provider -> [paths]
final_oauth_credentials = {}
# --- Pass 1: Pre-initialization Scan & Deduplication ---
# logging.info("Pass 1: Scanning for existing metadata to find duplicates...")
for provider, paths in oauth_credentials.items():
if provider not in credentials_to_initialize:
credentials_to_initialize[provider] = []
for path in paths:
# Skip env-based credentials (virtual paths) - they don't have metadata files
if path.startswith("env://"):
credentials_to_initialize[provider].append(path)
continue
try:
with open(path, "r") as f:
data = json.load(f)
metadata = data.get("_proxy_metadata", {})
email = metadata.get("email")
if email:
if email not in processed_emails:
processed_emails[email] = {}
if provider in processed_emails[email]:
original_path = processed_emails[email][provider]
logging.warning(
f"Duplicate for '{email}' on '{provider}' found in pre-scan: '{Path(path).name}'. Original: '{Path(original_path).name}'. Skipping."
)
continue
else:
processed_emails[email][provider] = path
credentials_to_initialize[provider].append(path)
except (FileNotFoundError, json.JSONDecodeError) as e:
logging.warning(
f"Could not pre-read metadata from '{path}': {e}. Will process during initialization."
)
credentials_to_initialize[provider].append(path)
# --- Pass 2: Parallel Initialization of Filtered Credentials ---
# logging.info("Pass 2: Initializing unique credentials and performing final check...")
async def process_credential(provider: str, path: str, provider_instance):
"""Process a single credential: initialize and fetch user info."""
try:
await provider_instance.initialize_token(path)
if not hasattr(provider_instance, "get_user_info"):
return (provider, path, None, None)
user_info = await provider_instance.get_user_info(path)
email = user_info.get("email")
return (provider, path, email, None)
except Exception as e:
logging.error(
f"Failed to process OAuth token for {provider} at '{path}': {e}"
)
return (provider, path, None, e)
# Collect all tasks for parallel execution
tasks = []
for provider, paths in credentials_to_initialize.items():
if not paths:
continue
provider_plugin_class = PROVIDER_PLUGINS.get(provider)
if not provider_plugin_class:
continue
provider_instance = provider_plugin_class()
for path in paths:
tasks.append(process_credential(provider, path, provider_instance))
# Execute all credential processing tasks in parallel
results = await asyncio.gather(*tasks, return_exceptions=True)
# --- Pass 3: Sequential Deduplication and Final Assembly ---
for result in results:
# Handle exceptions from gather
if isinstance(result, Exception):
logging.error(f"Credential processing raised exception: {result}")
continue
provider, path, email, error = result
# Skip if there was an error
if error:
continue
# If provider doesn't support get_user_info, add directly
if email is None:
if provider not in final_oauth_credentials:
final_oauth_credentials[provider] = []
final_oauth_credentials[provider].append(path)
continue
# Handle empty email
if not email:
logging.warning(
f"Could not retrieve email for '{path}'. Treating as unique."
)
if provider not in final_oauth_credentials:
final_oauth_credentials[provider] = []
final_oauth_credentials[provider].append(path)
continue
# Deduplication check
if email not in processed_emails:
processed_emails[email] = {}
if (
provider in processed_emails[email]
and processed_emails[email][provider] != path
):
original_path = processed_emails[email][provider]
logging.warning(
f"Duplicate for '{email}' on '{provider}' found post-init: '{Path(path).name}'. Original: '{Path(original_path).name}'. Skipping."
)
continue
else:
processed_emails[email][provider] = path
if provider not in final_oauth_credentials:
final_oauth_credentials[provider] = []
final_oauth_credentials[provider].append(path)
# Update metadata (skip for env-based credentials - they don't have files)
if not path.startswith("env://"):
try:
with open(path, "r+") as f:
data = json.load(f)
metadata = data.get("_proxy_metadata", {})
metadata["email"] = email
metadata["last_check_timestamp"] = time.time()
data["_proxy_metadata"] = metadata
f.seek(0)
json.dump(data, f, indent=2)
f.truncate()
except Exception as e:
logging.error(f"Failed to update metadata for '{path}': {e}")
logging.info("OAuth credential processing complete.")
oauth_credentials = final_oauth_credentials
# [NEW] Load provider-specific params
litellm_provider_params = {
"gemini_cli": {"project_id": os.getenv("GEMINI_CLI_PROJECT_ID")}
}
# Load global timeout from environment (default 30 seconds)
global_timeout = int(os.getenv("GLOBAL_TIMEOUT", "30"))
# The client now uses the root logger configuration
client = RotatingClient(
api_keys=api_keys,
oauth_credentials=oauth_credentials, # Pass OAuth config
configure_logging=True,
global_timeout=global_timeout,
litellm_provider_params=litellm_provider_params,
ignore_models=ignore_models,
whitelist_models=whitelist_models,
enable_request_logging=ENABLE_REQUEST_LOGGING,
max_concurrent_requests_per_key=max_concurrent_requests_per_key,
)
# Log loaded credentials summary (compact, always visible for deployment verification)
# _api_summary = ', '.join([f"{p}:{len(c)}" for p, c in api_keys.items()]) if api_keys else "none"
# _oauth_summary = ', '.join([f"{p}:{len(c)}" for p, c in oauth_credentials.items()]) if oauth_credentials else "none"
# _total_summary = ', '.join([f"{p}:{len(c)}" for p, c in client.all_credentials.items()])
# print(f"🔑 Credentials loaded: {_total_summary} (API: {_api_summary} | OAuth: {_oauth_summary})")
client.background_refresher.start() # Start the background task
app.state.rotating_client = client
# Warn if no provider credentials are configured
if not client.all_credentials:
logging.warning("=" * 70)
logging.warning("⚠️ NO PROVIDER CREDENTIALS CONFIGURED")
logging.warning("The proxy is running but cannot serve any LLM requests.")
logging.warning(
"Launch the credential tool to add API keys or OAuth credentials."
)
logging.warning(" • Executable: Run with --add-credential flag")
logging.warning(" • Source: python src/proxy_app/main.py --add-credential")
logging.warning("=" * 70)
os.environ["LITELLM_LOG"] = "ERROR"
litellm.set_verbose = False
litellm.drop_params = True
if USE_EMBEDDING_BATCHER:
batcher = EmbeddingBatcher(client=client)
app.state.embedding_batcher = batcher
logging.info("RotatingClient and EmbeddingBatcher initialized.")
else:
app.state.embedding_batcher = None
logging.info("RotatingClient initialized (EmbeddingBatcher disabled).")
# Start model info service in background (fetches pricing/capabilities data)
# This runs asynchronously and doesn't block proxy startup
model_info_service = await init_model_info_service()
app.state.model_info_service = model_info_service
logging.info("Model info service started (fetching pricing data in background).")
yield
await client.background_refresher.stop() # Stop the background task on shutdown
if app.state.embedding_batcher:
await app.state.embedding_batcher.stop()
await client.close()
# Stop model info service
if hasattr(app.state, "model_info_service") and app.state.model_info_service:
await app.state.model_info_service.stop()
if app.state.embedding_batcher:
logging.info("RotatingClient and EmbeddingBatcher closed.")
else:
logging.info("RotatingClient closed.")
# --- FastAPI App Setup ---
app = FastAPI(lifespan=lifespan)
# Add CORS middleware to allow all origins, methods, and headers
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins
allow_credentials=True,
allow_methods=["*"], # Allows all methods
allow_headers=["*"], # Allows all headers
)
api_key_header = APIKeyHeader(name="Authorization", auto_error=False)
def get_rotating_client(request: Request) -> RotatingClient:
"""Dependency to get the rotating client instance from the app state."""
return request.app.state.rotating_client
def get_embedding_batcher(request: Request) -> EmbeddingBatcher:
"""Dependency to get the embedding batcher instance from the app state."""
return request.app.state.embedding_batcher
async def verify_api_key(auth: str = Depends(api_key_header)):
"""Dependency to verify the proxy API key."""
# If PROXY_API_KEY is not set or empty, skip verification (open access)
if not PROXY_API_KEY:
return auth
if not auth or auth != f"Bearer {PROXY_API_KEY}":
raise HTTPException(status_code=401, detail="Invalid or missing API Key")
return auth
# --- Anthropic API Key Header ---
anthropic_api_key_header = APIKeyHeader(name="x-api-key", auto_error=False)
async def verify_anthropic_api_key(
x_api_key: str = Depends(anthropic_api_key_header),
auth: str = Depends(api_key_header),
):
"""
Dependency to verify API key for Anthropic endpoints.
Accepts either x-api-key header (Anthropic style) or Authorization Bearer (OpenAI style).
"""
# Check x-api-key first (Anthropic style)
if x_api_key and x_api_key == PROXY_API_KEY:
return x_api_key
# Fall back to Bearer token (OpenAI style)
if auth and auth == f"Bearer {PROXY_API_KEY}":
return auth
raise HTTPException(status_code=401, detail="Invalid or missing API Key")
async def streaming_response_wrapper(
request: Request,
request_data: dict,
response_stream: AsyncGenerator[str, None],
logger: Optional[RawIOLogger] = None,
) -> AsyncGenerator[str, None]:
"""
Wraps a streaming response to log the full response after completion
and ensures any errors during the stream are sent to the client.
"""
response_chunks = []
full_response = {}
try:
async for chunk_str in response_stream:
if await request.is_disconnected():
logging.warning("Client disconnected, stopping stream.")
break
yield chunk_str
if chunk_str.strip() and chunk_str.startswith("data:"):
content = chunk_str[len("data:") :].strip()
if content != "[DONE]":
try:
chunk_data = json.loads(content)
response_chunks.append(chunk_data)
if logger:
logger.log_stream_chunk(chunk_data)
except json.JSONDecodeError:
pass
except Exception as e:
logging.error(f"An error occurred during the response stream: {e}")
# Yield a final error message to the client to ensure they are not left hanging.
error_payload = {
"error": {
"message": f"An unexpected error occurred during the stream: {str(e)}",
"type": "proxy_internal_error",
"code": 500,
}
}
yield f"data: {json.dumps(error_payload)}\n\n"
yield "data: [DONE]\n\n"
# Also log this as a failed request
if logger:
logger.log_final_response(
status_code=500, headers=None, body={"error": str(e)}
)
return # Stop further processing
finally:
if response_chunks:
# --- Aggregation Logic ---
final_message = {"role": "assistant"}
aggregated_tool_calls = {}
usage_data = None
finish_reason = None
for chunk in response_chunks:
if "choices" in chunk and chunk["choices"]:
choice = chunk["choices"][0]
delta = choice.get("delta", {})
# Dynamically aggregate all fields from the delta
for key, value in delta.items():
if value is None:
continue
if key == "content":
if "content" not in final_message:
final_message["content"] = ""
if value:
final_message["content"] += value
elif key == "tool_calls":
for tc_chunk in value:
index = tc_chunk["index"]
if index not in aggregated_tool_calls:
aggregated_tool_calls[index] = {
"type": "function",
"function": {"name": "", "arguments": ""},
}
# Ensure 'function' key exists for this index before accessing its sub-keys
if "function" not in aggregated_tool_calls[index]:
aggregated_tool_calls[index]["function"] = {
"name": "",
"arguments": "",
}
if tc_chunk.get("id"):
aggregated_tool_calls[index]["id"] = tc_chunk["id"]
if "function" in tc_chunk:
if "name" in tc_chunk["function"]:
if tc_chunk["function"]["name"] is not None:
aggregated_tool_calls[index]["function"][
"name"
] += tc_chunk["function"]["name"]
if "arguments" in tc_chunk["function"]:
if (
tc_chunk["function"]["arguments"]
is not None
):
aggregated_tool_calls[index]["function"][
"arguments"
] += tc_chunk["function"]["arguments"]
elif key == "function_call":
if "function_call" not in final_message:
final_message["function_call"] = {
"name": "",
"arguments": "",
}
if "name" in value:
if value["name"] is not None:
final_message["function_call"]["name"] += value[
"name"
]
if "arguments" in value:
if value["arguments"] is not None:
final_message["function_call"]["arguments"] += (
value["arguments"]
)
else: # Generic key handling for other data like 'reasoning'
# FIX: Role should always replace, never concatenate
if key == "role":
final_message[key] = value
elif key not in final_message:
final_message[key] = value
elif isinstance(final_message.get(key), str):
final_message[key] += value
else:
final_message[key] = value
if "finish_reason" in choice and choice["finish_reason"]:
finish_reason = choice["finish_reason"]
if "usage" in chunk and chunk["usage"]:
usage_data = chunk["usage"]
# --- Final Response Construction ---
if aggregated_tool_calls:
final_message["tool_calls"] = list(aggregated_tool_calls.values())
# CRITICAL FIX: Override finish_reason when tool_calls exist
# This ensures OpenCode and other agentic systems continue the conversation loop
finish_reason = "tool_calls"
# Ensure standard fields are present for consistent logging
for field in ["content", "tool_calls", "function_call"]:
if field not in final_message:
final_message[field] = None
first_chunk = response_chunks[0]
final_choice = {
"index": 0,
"message": final_message,
"finish_reason": finish_reason,
}
full_response = {
"id": first_chunk.get("id"),
"object": "chat.completion",
"created": first_chunk.get("created"),
"model": first_chunk.get("model"),
"choices": [final_choice],
"usage": usage_data,
}
if logger:
logger.log_final_response(
status_code=200,
headers=None, # Headers are not available at this stage
body=full_response,
)
@app.post("/v1/chat/completions")
async def chat_completions(
request: Request,
client: RotatingClient = Depends(get_rotating_client),
_=Depends(verify_api_key),
):
"""
OpenAI-compatible endpoint powered by the RotatingClient.
Handles both streaming and non-streaming responses and logs them.
"""
# Raw I/O logger captures unmodified HTTP data at proxy boundary (disabled by default)
raw_logger = RawIOLogger() if ENABLE_RAW_LOGGING else None
try:
# Read and parse the request body only once at the beginning.
try:
request_data = await request.json()
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid JSON in request body.")
# Global temperature=0 override (controlled by .env variable, default: OFF)
# Low temperature makes models deterministic and prone to following training data
# instead of actual schemas, which can cause tool hallucination
# Modes: "remove" = delete temperature key, "set" = change to 1.0, "false" = disabled
override_temp_zero = os.getenv("OVERRIDE_TEMPERATURE_ZERO", "false").lower()
if (
override_temp_zero in ("remove", "set", "true", "1", "yes")
and "temperature" in request_data
and request_data["temperature"] == 0
):
if override_temp_zero == "remove":
# Remove temperature key entirely
del request_data["temperature"]
logging.debug(
"OVERRIDE_TEMPERATURE_ZERO=remove: Removed temperature=0 from request"
)
else:
# Set to 1.0 (for "set", "true", "1", "yes")
request_data["temperature"] = 1.0
logging.debug(
"OVERRIDE_TEMPERATURE_ZERO=set: Converting temperature=0 to temperature=1.0"
)
# If raw logging is enabled, capture the unmodified request data.
if raw_logger:
raw_logger.log_request(headers=request.headers, body=request_data)
# Extract and log specific reasoning parameters for monitoring.
model = request_data.get("model")
generation_cfg = (
request_data.get("generationConfig", {})
or request_data.get("generation_config", {})
or {}
)
reasoning_effort = request_data.get("reasoning_effort") or generation_cfg.get(
"reasoning_effort"
)
logging.getLogger("rotator_library").debug(
f"Handling reasoning parameters: model={model}, reasoning_effort={reasoning_effort}"
)
# Log basic request info to console (this is a separate, simpler logger).
log_request_to_console(
url=str(request.url),
headers=dict(request.headers),
client_info=(request.client.host, request.client.port),
request_data=request_data,
)
is_streaming = request_data.get("stream", False)
if is_streaming:
response_generator = client.acompletion(request=request, **request_data)
return StreamingResponse(
streaming_response_wrapper(
request, request_data, response_generator, raw_logger
),
media_type="text/event-stream",
)
else:
response = await client.acompletion(request=request, **request_data)
if raw_logger:
# Assuming response has status_code and headers attributes
# This might need adjustment based on the actual response object
response_headers = (
response.headers if hasattr(response, "headers") else None
)
status_code = (
response.status_code if hasattr(response, "status_code") else 200
)
raw_logger.log_final_response(
status_code=status_code,
headers=response_headers,
body=response.model_dump(),
)
return response
except (
litellm.InvalidRequestError,
ValueError,
litellm.ContextWindowExceededError,
) as e:
raise HTTPException(status_code=400, detail=f"Invalid Request: {str(e)}")
except litellm.AuthenticationError as e:
raise HTTPException(status_code=401, detail=f"Authentication Error: {str(e)}")
except litellm.RateLimitError as e:
raise HTTPException(status_code=429, detail=f"Rate Limit Exceeded: {str(e)}")
except (litellm.ServiceUnavailableError, litellm.APIConnectionError) as e:
raise HTTPException(status_code=503, detail=f"Service Unavailable: {str(e)}")
except litellm.Timeout as e:
raise HTTPException(status_code=504, detail=f"Gateway Timeout: {str(e)}")
except (litellm.InternalServerError, litellm.OpenAIError) as e:
raise HTTPException(status_code=502, detail=f"Bad Gateway: {str(e)}")
except Exception as e:
logging.error(f"Request failed after all retries: {e}")
# Optionally log the failed request
if ENABLE_REQUEST_LOGGING:
try:
request_data = await request.json()
except json.JSONDecodeError:
request_data = {"error": "Could not parse request body"}
if raw_logger:
raw_logger.log_final_response(
status_code=500, headers=None, body={"error": str(e)}
)
raise HTTPException(status_code=500, detail=str(e))
# --- Anthropic Messages API Endpoint ---
@app.post("/v1/messages")
async def anthropic_messages(
request: Request,
body: AnthropicMessagesRequest,
client: RotatingClient = Depends(get_rotating_client),
_=Depends(verify_anthropic_api_key),
):
"""
Anthropic-compatible Messages API endpoint.
Accepts requests in Anthropic's format and returns responses in Anthropic's format.
Internally translates to OpenAI format for processing via LiteLLM.
This endpoint is compatible with Claude Code and other Anthropic API clients.
"""
# Initialize raw I/O logger if enabled (for debugging proxy boundary)
logger = RawIOLogger() if ENABLE_RAW_LOGGING else None
# Log raw Anthropic request if raw logging is enabled
if logger:
logger.log_request(
headers=dict(request.headers),
body=body.model_dump(exclude_none=True),
)
try:
# Log the request to console
log_request_to_console(
url=str(request.url),
headers=dict(request.headers),
client_info=(
request.client.host if request.client else "unknown",
request.client.port if request.client else 0,
),
request_data=body.model_dump(exclude_none=True),
)
# Use the library method to handle the request
result = await client.anthropic_messages(body, raw_request=request)
if body.stream:
# Streaming response
return StreamingResponse(
result,
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"X-Accel-Buffering": "no",
},
)
else:
# Non-streaming response
if logger:
logger.log_final_response(
status_code=200,
headers=None,
body=result,
)
return JSONResponse(content=result)
except (
litellm.InvalidRequestError,
ValueError,
litellm.ContextWindowExceededError,
) as e:
error_response = {
"type": "error",
"error": {"type": "invalid_request_error", "message": str(e)},
}
raise HTTPException(status_code=400, detail=error_response)
except litellm.AuthenticationError as e:
error_response = {
"type": "error",
"error": {"type": "authentication_error", "message": str(e)},
}
raise HTTPException(status_code=401, detail=error_response)
except litellm.RateLimitError as e:
error_response = {
"type": "error",
"error": {"type": "rate_limit_error", "message": str(e)},
}
raise HTTPException(status_code=429, detail=error_response)
except (litellm.ServiceUnavailableError, litellm.APIConnectionError) as e:
error_response = {
"type": "error",
"error": {"type": "api_error", "message": str(e)},
}
raise HTTPException(status_code=503, detail=error_response)
except litellm.Timeout as e:
error_response = {
"type": "error",
"error": {"type": "api_error", "message": f"Request timed out: {str(e)}"},
}
raise HTTPException(status_code=504, detail=error_response)
except Exception as e:
logging.error(f"Anthropic messages endpoint error: {e}")
if logger:
logger.log_final_response(
status_code=500,
headers=None,
body={"error": str(e)},
)
error_response = {
"type": "error",
"error": {"type": "api_error", "message": str(e)},
}
raise HTTPException(status_code=500, detail=error_response)
# --- Anthropic Count Tokens Endpoint ---
@app.post("/v1/messages/count_tokens")
async def anthropic_count_tokens(
request: Request,
body: AnthropicCountTokensRequest,
client: RotatingClient = Depends(get_rotating_client),
_=Depends(verify_anthropic_api_key),
):
"""
Anthropic-compatible count_tokens endpoint.
Counts the number of tokens that would be used by a Messages API request.
This is useful for estimating costs and managing context windows.
Accepts requests in Anthropic's format and returns token count in Anthropic's format.
"""
try:
# Use the library method to handle the request
result = await client.anthropic_count_tokens(body)
return JSONResponse(content=result)
except (
litellm.InvalidRequestError,
ValueError,
litellm.ContextWindowExceededError,
) as e:
error_response = {
"type": "error",
"error": {"type": "invalid_request_error", "message": str(e)},
}
raise HTTPException(status_code=400, detail=error_response)
except litellm.AuthenticationError as e:
error_response = {
"type": "error",
"error": {"type": "authentication_error", "message": str(e)},
}
raise HTTPException(status_code=401, detail=error_response)
except Exception as e:
logging.error(f"Anthropic count_tokens endpoint error: {e}")
error_response = {
"type": "error",
"error": {"type": "api_error", "message": str(e)},
}
raise HTTPException(status_code=500, detail=error_response)
@app.post("/v1/embeddings")
async def embeddings(
request: Request,
body: EmbeddingRequest,
client: RotatingClient = Depends(get_rotating_client),
batcher: Optional[EmbeddingBatcher] = Depends(get_embedding_batcher),
_=Depends(verify_api_key),
):
"""
OpenAI-compatible endpoint for creating embeddings.
Supports two modes based on the USE_EMBEDDING_BATCHER flag:
- True: Uses a server-side batcher for high throughput.
- False: Passes requests directly to the provider.
"""
try:
request_data = body.model_dump(exclude_none=True)
log_request_to_console(
url=str(request.url),
headers=dict(request.headers),
client_info=(request.client.host, request.client.port),
request_data=request_data,
)
if USE_EMBEDDING_BATCHER and batcher:
# --- Server-Side Batching Logic ---
request_data = body.model_dump(exclude_none=True)
inputs = request_data.get("input", [])
if isinstance(inputs, str):
inputs = [inputs]
tasks = []
for single_input in inputs:
individual_request = request_data.copy()
individual_request["input"] = single_input
tasks.append(batcher.add_request(individual_request))
results = await asyncio.gather(*tasks)
all_data = []
total_prompt_tokens = 0
total_tokens = 0
for i, result in enumerate(results):
result["data"][0]["index"] = i
all_data.extend(result["data"])
total_prompt_tokens += result["usage"]["prompt_tokens"]
total_tokens += result["usage"]["total_tokens"]
final_response_data = {
"object": "list",
"model": results[0]["model"],
"data": all_data,
"usage": {
"prompt_tokens": total_prompt_tokens,
"total_tokens": total_tokens,
},
}
response = litellm.EmbeddingResponse(**final_response_data)
else:
# --- Direct Pass-Through Logic ---
request_data = body.model_dump(exclude_none=True)
if isinstance(request_data.get("input"), str):
request_data["input"] = [request_data["input"]]
response = await client.aembedding(request=request, **request_data)
return response
except HTTPException as e:
# Re-raise HTTPException to ensure it's not caught by the generic Exception handler
raise e
except (
litellm.InvalidRequestError,
ValueError,
litellm.ContextWindowExceededError,
) as e:
raise HTTPException(status_code=400, detail=f"Invalid Request: {str(e)}")
except litellm.AuthenticationError as e:
raise HTTPException(status_code=401, detail=f"Authentication Error: {str(e)}")
except litellm.RateLimitError as e:
raise HTTPException(status_code=429, detail=f"Rate Limit Exceeded: {str(e)}")
except (litellm.ServiceUnavailableError, litellm.APIConnectionError) as e:
raise HTTPException(status_code=503, detail=f"Service Unavailable: {str(e)}")
except litellm.Timeout as e:
raise HTTPException(status_code=504, detail=f"Gateway Timeout: {str(e)}")
except (litellm.InternalServerError, litellm.OpenAIError) as e:
raise HTTPException(status_code=502, detail=f"Bad Gateway: {str(e)}")
except Exception as e:
logging.error(f"Embedding request failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.get("/dashboard")
async def dashboard():
"""Serve the usage dashboard HTML page."""
from fastapi.responses import FileResponse
import os
dashboard_path = os.path.join(os.path.dirname(__file__), "static", "dashboard.html")
return FileResponse(dashboard_path, media_type="text/html")
@app.get("/")
def read_root():
return {"Status": "API Key Proxy is running"}
@app.get("/v1/models")
async def list_models(
request: Request,
client: RotatingClient = Depends(get_rotating_client),
_=Depends(verify_api_key),
enriched: bool = True,
):
"""
Returns a list of available models in the OpenAI-compatible format.
Query Parameters:
enriched: If True (default), returns detailed model info with pricing and capabilities.
If False, returns minimal OpenAI-compatible response.
"""
model_ids = await client.get_all_available_models(grouped=False)
if enriched and hasattr(request.app.state, "model_info_service"):
model_info_service = request.app.state.model_info_service
if model_info_service.is_ready:
# Return enriched model data
enriched_data = model_info_service.enrich_model_list(model_ids)
return {"object": "list", "data": enriched_data}
# Fallback to basic model cards
model_cards = [
{
"id": model_id,
"object": "model",
"created": int(time.time()),
"owned_by": "Mirro-Proxy",
}
for model_id in model_ids
]
return {"object": "list", "data": model_cards}
@app.get("/v1/models/{model_id:path}")
async def get_model(
model_id: str,
request: Request,
_=Depends(verify_api_key),
):
"""
Returns detailed information about a specific model.
Path Parameters:
model_id: The model ID (e.g., "anthropic/claude-3-opus", "openrouter/openai/gpt-4")
"""
if hasattr(request.app.state, "model_info_service"):
model_info_service = request.app.state.model_info_service
if model_info_service.is_ready:
info = model_info_service.get_model_info(model_id)
if info:
return info.to_dict()
# Return basic info if service not ready or model not found
return {
"id": model_id,
"object": "model",
"created": int(time.time()),
"owned_by": model_id.split("/")[0] if "/" in model_id else "unknown",
}
@app.get("/v1/model-info/stats")
async def model_info_stats(
request: Request,
_=Depends(verify_api_key),
):
"""
Returns statistics about the model info service (for monitoring/debugging).
"""
if hasattr(request.app.state, "model_info_service"):
return request.app.state.model_info_service.get_stats()
return {"error": "Model info service not initialized"}
@app.get("/v1/providers")
async def list_providers(_=Depends(verify_api_key)):
"""
Returns a list of all available providers.
"""
return list(PROVIDER_PLUGINS.keys())
@app.get("/v1/quota-stats")
async def get_quota_stats(
request: Request,
client: RotatingClient = Depends(get_rotating_client),
_=Depends(verify_api_key),
provider: str = None,
):
"""
Returns quota and usage statistics for all credentials.
This returns cached data from the proxy without making external API calls.
Use POST to reload from disk or force refresh from external APIs.
Query Parameters:
provider: Optional filter to return stats for a specific provider only
Returns:
{
"providers": {
"provider_name": {
"credential_count": int,
"active_count": int,
"on_cooldown_count": int,
"exhausted_count": int,
"total_requests": int,
"tokens": {...},
"approx_cost": float | null,
"quota_groups": {...}, // For Antigravity
"credentials": [...]
}
},
"summary": {...},
"data_source": "cache",
"timestamp": float
}
"""
try:
stats = await client.get_quota_stats(provider_filter=provider)
return stats
except Exception as e:
logging.error(f"Failed to get quota stats: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/v1/quota-stats")
async def refresh_quota_stats(
request: Request,
client: RotatingClient = Depends(get_rotating_client),
_=Depends(verify_api_key),
):
"""
Refresh quota and usage statistics.
Request body:
{
"action": "reload" | "force_refresh",
"scope": "all" | "provider" | "credential",
"provider": "antigravity", // required if scope != "all"
"credential": "antigravity_oauth_1.json" // required if scope == "credential"
}
Actions:
- reload: Re-read data from disk (no external API calls)
- force_refresh: For Antigravity, fetch live quota from API.
For other providers, same as reload.
Returns:
Same as GET, plus a "refresh_result" field with operation details.
"""
try:
data = await request.json()
action = data.get("action", "reload")
scope = data.get("scope", "all")
provider = data.get("provider")
credential = data.get("credential")
# Validate parameters
if action not in ("reload", "force_refresh"):
raise HTTPException(
status_code=400,
detail="action must be 'reload' or 'force_refresh'",
)
if scope not in ("all", "provider", "credential"):
raise HTTPException(
status_code=400,
detail="scope must be 'all', 'provider', or 'credential'",
)
if scope in ("provider", "credential") and not provider:
raise HTTPException(
status_code=400,
detail="'provider' is required when scope is 'provider' or 'credential'",
)
if scope == "credential" and not credential:
raise HTTPException(
status_code=400,
detail="'credential' is required when scope is 'credential'",
)
refresh_result = {
"action": action,
"scope": scope,
"provider": provider,
"credential": credential,
}
if action == "reload":
# Just reload from disk
start_time = time.time()
await client.reload_usage_from_disk()
refresh_result["duration_ms"] = int((time.time() - start_time) * 1000)
refresh_result["success"] = True
refresh_result["message"] = "Reloaded usage data from disk"
elif action == "force_refresh":
# Force refresh from external API (for supported providers like Antigravity)
result = await client.force_refresh_quota(
provider=provider if scope in ("provider", "credential") else None,
credential=credential if scope == "credential" else None,
)
refresh_result.update(result)
refresh_result["success"] = result["failed_count"] == 0
# Get updated stats
stats = await client.get_quota_stats(provider_filter=provider)
stats["refresh_result"] = refresh_result
stats["data_source"] = "refreshed"
return stats
except HTTPException:
raise
except Exception as e:
logging.error(f"Failed to refresh quota stats: {e}")
raise HTTPException(status_code=500, detail=str(e))
# --- Log Viewing Endpoint ---
@app.get("/logs/{log_type}")
async def view_logs(
log_type: str,
lines: int = 50,
_: str = Depends(verify_api_key),
):
"""
View the last N lines of a log file.
Authenticated with PROXY_API_KEY.
Path Params:
- log_type: 'proxy', 'debug', or 'failures'
Query Params:
- lines: number of lines to return (default: 50)
Example:
curl -H "Authorization: Bearer YOUR_KEY" "https://your-space.hf.space/logs/failures?lines=100"
"""
allowed_logs = {
"failures": "failures.log",
"proxy": "proxy.log",
"debug": "proxy_debug.log",
}
if log_type not in allowed_logs:
raise HTTPException(
status_code=400,
detail=f"Invalid log type. Choose from: {list(allowed_logs.keys())}"
)
log_file = LOG_DIR / allowed_logs[log_type]
if not log_file.exists():
return JSONResponse(
status_code=404,
content={"error": "Log file not found", "path": str(log_file), "available_logs": list(allowed_logs.keys())}
)
try:
# Simple/naive implementation - fine for small log files
with open(log_file, "r", encoding="utf-8", errors="replace") as f:
all_lines = f.readlines()
# Return last N lines as a single string
result = "".join(all_lines[-lines:])
return JSONResponse(content={"log": allowed_logs[log_type], "lines": lines, "content": result})
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to read log file: {str(e)}")
@app.post("/v1/token-count")
async def token_count(
request: Request,
client: RotatingClient = Depends(get_rotating_client),
_=Depends(verify_api_key),
):
"""
Calculates the token count for a given list of messages and a model.
"""
try:
data = await request.json()
model = data.get("model")
messages = data.get("messages")
if not model or not messages:
raise HTTPException(
status_code=400, detail="'model' and 'messages' are required."
)
count = client.token_count(**data)
return {"token_count": count}
except Exception as e:
logging.error(f"Token count failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/v1/cost-estimate")
async def cost_estimate(request: Request, _=Depends(verify_api_key)):
"""
Estimates the cost for a request based on token counts and model pricing.
Request body:
{
"model": "anthropic/claude-3-opus",
"prompt_tokens": 1000,
"completion_tokens": 500,
"cache_read_tokens": 0, # optional
"cache_creation_tokens": 0 # optional
}
Returns:
{
"model": "anthropic/claude-3-opus",
"cost": 0.0375,
"currency": "USD",
"pricing": {
"input_cost_per_token": 0.000015,
"output_cost_per_token": 0.000075
},
"source": "model_info_service" # or "litellm_fallback"
}
"""
try:
data = await request.json()
model = data.get("model")
prompt_tokens = data.get("prompt_tokens", 0)
completion_tokens = data.get("completion_tokens", 0)
cache_read_tokens = data.get("cache_read_tokens", 0)
cache_creation_tokens = data.get("cache_creation_tokens", 0)
if not model:
raise HTTPException(status_code=400, detail="'model' is required.")
result = {
"model": model,
"cost": None,
"currency": "USD",
"pricing": {},
"source": None,
}
# Try model info service first
if hasattr(request.app.state, "model_info_service"):
model_info_service = request.app.state.model_info_service
if model_info_service.is_ready:
cost = model_info_service.calculate_cost(
model,
prompt_tokens,
completion_tokens,
cache_read_tokens,
cache_creation_tokens,
)
if cost is not None:
cost_info = model_info_service.get_cost_info(model)
result["cost"] = cost
result["pricing"] = cost_info or {}
result["source"] = "model_info_service"
return result
# Fallback to litellm
try:
import litellm
# Create a mock response for cost calculation
model_info = litellm.get_model_info(model)
input_cost = model_info.get("input_cost_per_token", 0)
output_cost = model_info.get("output_cost_per_token", 0)
if input_cost or output_cost:
cost = (prompt_tokens * input_cost) + (completion_tokens * output_cost)
result["cost"] = cost
result["pricing"] = {
"input_cost_per_token": input_cost,
"output_cost_per_token": output_cost,
}
result["source"] = "litellm_fallback"
return result
except Exception:
pass
result["source"] = "unknown"
result["error"] = "Pricing data not available for this model"
return result
except HTTPException:
raise
except Exception as e:
logging.error(f"Cost estimate failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
# Define ENV_FILE for onboarding checks using centralized path
ENV_FILE = get_data_file(".env")
# Check if launcher TUI should be shown (no arguments provided)
if len(sys.argv) == 1:
# No arguments - show launcher TUI (lazy import)
from proxy_app.launcher_tui import run_launcher_tui
run_launcher_tui()
# Launcher modifies sys.argv and returns, or exits if user chose Exit
# If we get here, user chose "Run Proxy" and sys.argv is modified
# Re-parse arguments with modified sys.argv
args = parser.parse_args()
def needs_onboarding() -> bool:
"""
Check if the proxy needs onboarding (first-time setup).
Returns True if onboarding is needed, False otherwise.
"""
# Skip onboarding if CONFIG_ENV secret exists (Hugging Face Spaces deployment)
if os.getenv("CONFIG_ENV"):
return False
# Only check if .env file exists
# PROXY_API_KEY is optional (will show warning if not set)
if not ENV_FILE.is_file():
return True
return False
def show_onboarding_message():
"""Display clear explanatory message for why onboarding is needed."""
os.system(
"cls" if os.name == "nt" else "clear"
) # Clear terminal for clean presentation
console.print(
Panel.fit(
"[bold cyan]🚀 LLM API Key Proxy - First Time Setup[/bold cyan]",
border_style="cyan",
)
)
console.print("[bold yellow]⚠️ Configuration Required[/bold yellow]\n")
console.print("The proxy needs initial configuration:")
console.print(" [red]❌ No .env file found[/red]")
console.print("\n[bold]Why this matters:[/bold]")
console.print(" • The .env file stores your credentials and settings")
console.print(" • PROXY_API_KEY protects your proxy from unauthorized access")
console.print(" • Provider API keys enable LLM access")
console.print("\n[bold]What happens next:[/bold]")
console.print(" 1. We'll create a .env file with PROXY_API_KEY")
console.print(" 2. You can add LLM provider credentials (API keys or OAuth)")
console.print(" 3. The proxy will then start normally")
console.print(
"\n[bold yellow]⚠️ Note:[/bold yellow] The credential tool adds PROXY_API_KEY by default."
)
console.print(" You can remove it later if you want an unsecured proxy.\n")
console.input(
"[bold green]Press Enter to launch the credential setup tool...[/bold green]"
)
# Check if user explicitly wants to add credentials
if args.add_credential:
# Import and call ensure_env_defaults to create .env and PROXY_API_KEY if needed
from rotator_library.credential_tool import ensure_env_defaults
ensure_env_defaults()
# Reload environment variables after ensure_env_defaults creates/updates .env
load_dotenv(ENV_FILE, override=True)
run_credential_tool()
else:
# Check if onboarding is needed
if needs_onboarding():
# Import console from rich for better messaging
from rich.console import Console
from rich.panel import Panel
console = Console()
# Show clear explanatory message
show_onboarding_message()
# Launch credential tool automatically
from rotator_library.credential_tool import ensure_env_defaults
ensure_env_defaults()
load_dotenv(ENV_FILE, override=True)
run_credential_tool()
# After credential tool exits, reload and re-check
load_dotenv(ENV_FILE, override=True)
# Re-read PROXY_API_KEY from environment
PROXY_API_KEY = os.getenv("PROXY_API_KEY")
# Verify onboarding is complete
if needs_onboarding():
console.print("\n[bold red]❌ Configuration incomplete.[/bold red]")
console.print(
"The proxy still cannot start. Please ensure PROXY_API_KEY is set in .env\n"
)
sys.exit(1)
else:
console.print("\n[bold green]✅ Configuration complete![/bold green]")
console.print("\nStarting proxy server...\n")
import uvicorn
# [CONCURRENCY FIX #2] - Launch Uvicorn with multiple workers + concurrency limits
workers = max(1, args.workers)
if workers > 1:
logging.info(f"Starting with {workers} worker processes for concurrent request handling.")
# When workers > 1, Uvicorn requires an import string (not app object)
# so it can re-import the app in each spawned worker process
app_target = "proxy_app.main:app" if workers > 1 else app
uvicorn.run(
app_target,
host=args.host,
port=args.port,
workers=workers,
limit_concurrency=100, # Max simultaneous connections per worker
timeout_keep_alive=30, # Keep-alive for connection reuse
)
|