Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
93 lines (71 loc) · 3.8 KB
/
Copy pathmain.py
File metadata and controls
93 lines (71 loc) · 3.8 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
"""
LLMProxyfier — сервер прокси для LLM API.
Запускает прокси-сервер с эндпоинтами из endpoints.py.
Каждый эндпоинт маппит локальный путь на целевой API.
Примеры использования:
http://localhost:8080/v1/chat/completions → NVIDIA
http://localhost:8080/v2/chat/completions → Groq
http://localhost:8080/v3/chat/completions → OpenRouter
В программах указывайте:
Base URL: http://localhost:8080/v1
API Key: ваш-ключ (через заголовок X-Forwarded-Token)
"""
import logging
import sys
from pathlib import Path
# Добавляем корень проекта в sys.path для импорта endpoints
sys.path.insert(0, str(Path(__file__).parent))
from endpoints import create_router
from library import run_server, check_proxy_connection
# ---------------------------------------------------------------------------
# Логирование
# ---------------------------------------------------------------------------
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(levelname)-8s %(message)s",
)
log = logging.getLogger("llmproxyfier.main")
# Уменьшаем уровень логирования для aiohttp, чтобы уменьшить шум
logging.getLogger("aiohttp").setLevel(logging.WARNING)
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
def handle_asyncio_exception(loop, context):
"""Глобальный обработчик исключений для asyncio."""
if "exception" in context and isinstance(context["exception"], ConnectionResetError):
log.warning("ConnectionResetError caught in asyncio loop: %s", context["exception"])
else:
log.error("Unexpected error in asyncio loop: %s", context.get("message", "Unknown error"))
def main():
import argparse
parser = argparse.ArgumentParser(description='LLMProxyfier - Proxy server for LLM APIs')
parser.add_argument('--port', '-p', type=int, default=8080,
help='Port to run the server on (default: 8080)')
parser.add_argument('--host', type=str, default="0.0.0.0",
help='Host to bind the server to (default: 0.0.0.0)')
parser.add_argument('--proxy', type=str, default=None,
help='HTTP proxy to use for API connections (e.g., http://proxy.example.com:8080)')
parser.add_argument('--no-custom-handlers',
action='store_true',
help='Disable all custom handlers globally (use raw API responses)')
args = parser.parse_args()
# Устанавливаем глобальный обработчик исключений для asyncio.
# Создаём новый цикл явным образом (asyncio.get_event_loop()
# deprecated и в Python 3.12+ не создаёт цикл автоматически).
import asyncio
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.set_exception_handler(handle_asyncio_exception)
router = create_router(proxy_override=args.proxy)
# Включаем кастомные обработчики (если не отключены через CLI)
if not args.no_custom_handlers:
from endpoints import enable_custom_handlers
enable_custom_handlers(router)
else:
for route in router._endpoints:
route.use_custom_handler_override = False
log.warning("Global custom handlers DISABLED (--no-custom-handlers)")
return run_server(router, port=args.port, host=args.host, proxy=args.proxy)
if __name__ == "__main__":
import sys as _sys
_sys.exit(main())