-
-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathmain.py
More file actions
1780 lines (1517 loc) · 66.3 KB
/
main.py
File metadata and controls
1780 lines (1517 loc) · 66.3 KB
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
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.",
)
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()
# 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: