hins111 commited on
Commit
fd88cfe
·
verified ·
1 Parent(s): e814319

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +42 -42
main.py CHANGED
@@ -1,5 +1,5 @@
1
  # ===================================================================
2
- # main.py (已修改以适配 Hugging Face Secrets)
3
  # ===================================================================
4
 
5
  import json
@@ -15,7 +15,7 @@ from fastapi.responses import StreamingResponse
15
  from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
16
  from pydantic import BaseModel, Field
17
 
18
- # --- 类型定义和全局变量 (与原始文件一致) ---
19
  class CodeGeeXToken(TypedDict):
20
  token: str
21
  is_valid: bool
@@ -30,12 +30,12 @@ MAX_ERROR_COUNT = 3
30
  ERROR_COOLDOWN = 300
31
  DEBUG_MODE = os.environ.get("DEBUG_MODE", "false").lower() == "true"
32
 
33
- # --- Pydantic 模型 (与原始文件一致) ---
34
  class ChatMessage(BaseModel):
35
  role: str
36
  content: Union[str, List[Dict[str, Any]]]
37
  reasoning_content: Optional[str] = None
38
-
39
  class ChatCompletionRequest(BaseModel):
40
  model: str
41
  messages: List[ChatMessage]
@@ -53,11 +53,12 @@ class ModelInfo(BaseModel):
53
  class ModelList(BaseModel):
54
  object: str = "list"
55
  data: List[ModelInfo]
56
- # ... (其他 Pydantic 模型与原始文件一致)
57
  class ChatCompletionChoice(BaseModel):
58
  message: ChatMessage
59
  index: int = 0
60
  finish_reason: str = "stop"
 
61
  class ChatCompletionResponse(BaseModel):
62
  id: str = Field(default_factory=lambda: f"chatcmpl-{uuid.uuid4().hex}")
63
  object: str = "chat.completion"
@@ -65,10 +66,12 @@ class ChatCompletionResponse(BaseModel):
65
  model: str
66
  choices: List[ChatCompletionChoice]
67
  usage: Dict[str, int] = Field(default_factory=lambda: {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0})
 
68
  class StreamChoice(BaseModel):
69
  delta: Dict[str, Any] = Field(default_factory=dict)
70
  index: int = 0
71
  finish_reason: Optional[str] = None
 
72
  class StreamResponse(BaseModel):
73
  id: str = Field(default_factory=lambda: f"chatcmpl-{uuid.uuid4().hex}")
74
  object: str = "chat.completion.chunk"
@@ -84,43 +87,58 @@ def log_debug(message: str):
84
  if DEBUG_MODE:
85
  print(f"[DEBUG] {message}")
86
 
87
- # --- 配置加载函数 (已修改为从 Secrets 读取) ---
88
  def load_client_api_keys_from_secrets():
89
- """从环境变量加载客户端 API Keys"""
90
  global VALID_CLIENT_KEYS
91
  try:
92
  keys_str = os.environ.get("CLIENT_API_KEYS")
93
- if not keys_str:
94
- raise ValueError("Secret 'CLIENT_API_KEYS' not found.")
95
  keys = json.loads(keys_str)
96
  VALID_CLIENT_KEYS = set(keys) if isinstance(keys, list) else set()
97
- print(f"Successfully loaded {len(VALID_CLIENT_KEYS)} client API keys from secrets.")
98
  except Exception as e:
99
- print(f"FATAL: Error loading client API keys from secrets: {e}")
100
  VALID_CLIENT_KEYS = set()
101
 
102
  def load_codegeex_tokens_from_secrets():
103
- """从环境变量加载 CodeGeeX Tokens"""
104
  global CODEGEEX_TOKENS
105
  CODEGEEX_TOKENS = []
106
  try:
107
  tokens_str = os.environ.get("CODEGEEX_TOKENS")
108
- if not tokens_str:
109
- raise ValueError("Secret 'CODEGEEX_TOKENS' not found.")
110
- tokens = json.loads(tokens_str) # 假设Secret是一个JSON数组
111
- if not isinstance(tokens, list):
112
- raise TypeError("Secret 'CODEGEEX_TOKENS' must be a JSON list of strings.")
113
-
114
  for token in tokens:
115
  if isinstance(token, str) and token:
116
- CODEGEEX_TOKENS.append({
117
- "token": token, "is_valid": True, "last_used": 0, "error_count": 0
118
- })
119
- print(f"Successfully loaded {len(CODEGEEX_TOKENS)} CodeGeeX tokens from secrets.")
120
  except Exception as e:
121
- print(f"FATAL: Error loading CodeGeeX tokens from secrets: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- # --- 核心逻辑 (与原始文件保持一致) ---
 
 
 
 
 
 
 
 
 
124
  def get_best_codegeex_token() -> Optional[CodeGeeXToken]:
125
  with token_rotation_lock:
126
  now = time.time()
@@ -155,28 +173,10 @@ async def authenticate_client(auth: Optional[HTTPAuthorizationCredentials] = Dep
155
  if not auth or not auth.credentials: raise HTTPException(status_code=401, detail="API key required.", headers={"WWW-Authenticate": "Bearer"})
156
  if auth.credentials not in VALID_CLIENT_KEYS: raise HTTPException(status_code=403, detail="Invalid client API key.")
157
 
158
- @app.on_event("startup")
159
- async def startup():
160
- print("Starting CodeGeeX OpenAI API Adapter server...")
161
- load_client_api_keys_from_secrets()
162
- load_codegeex_tokens_from_secrets()
163
- print("Server initialization completed.")
164
-
165
- def get_models_list_response() -> ModelList:
166
- return ModelList(data=[ModelInfo(id=model, created=int(time.time()), owned_by="anthropic") for model in CODEGEEX_MODELS])
167
-
168
- @app.get("/v1/models", response_model=ModelList)
169
- async def list_v1_models(_: None = Depends(authenticate_client)):
170
- return get_models_list_response()
171
-
172
  @app.get("/models", response_model=ModelList)
173
  async def list_models_no_auth():
174
  return get_models_list_response()
175
 
176
- # ... (所有路由和核心函数都与原始文件一致, 此处省略以保持简洁, 但它们都在上面的完整代码块中)
177
- # --- The rest of the original code follows ---
178
- # This includes _codegeex_stream_generator, _build_codegeex_non_stream_response, chat_completions, etc.
179
- # They are included in the full code block above.
180
  def _codegeex_stream_generator(response, model: str):
181
  stream_id = f"chatcmpl-{uuid.uuid4().hex}"
182
  created_time = int(time.time())
 
1
  # ===================================================================
2
+ # main.py (已修复 Hugging Face 健康检查问题)
3
  # ===================================================================
4
 
5
  import json
 
15
  from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
16
  from pydantic import BaseModel, Field
17
 
18
+ # --- 类型定义和全局变量 ---
19
  class CodeGeeXToken(TypedDict):
20
  token: str
21
  is_valid: bool
 
30
  ERROR_COOLDOWN = 300
31
  DEBUG_MODE = os.environ.get("DEBUG_MODE", "false").lower() == "true"
32
 
33
+ # --- Pydantic 模型 ---
34
  class ChatMessage(BaseModel):
35
  role: str
36
  content: Union[str, List[Dict[str, Any]]]
37
  reasoning_content: Optional[str] = None
38
+ # ... (其他模型保持不变)
39
  class ChatCompletionRequest(BaseModel):
40
  model: str
41
  messages: List[ChatMessage]
 
53
  class ModelList(BaseModel):
54
  object: str = "list"
55
  data: List[ModelInfo]
56
+
57
  class ChatCompletionChoice(BaseModel):
58
  message: ChatMessage
59
  index: int = 0
60
  finish_reason: str = "stop"
61
+
62
  class ChatCompletionResponse(BaseModel):
63
  id: str = Field(default_factory=lambda: f"chatcmpl-{uuid.uuid4().hex}")
64
  object: str = "chat.completion"
 
66
  model: str
67
  choices: List[ChatCompletionChoice]
68
  usage: Dict[str, int] = Field(default_factory=lambda: {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0})
69
+
70
  class StreamChoice(BaseModel):
71
  delta: Dict[str, Any] = Field(default_factory=dict)
72
  index: int = 0
73
  finish_reason: Optional[str] = None
74
+
75
  class StreamResponse(BaseModel):
76
  id: str = Field(default_factory=lambda: f"chatcmpl-{uuid.uuid4().hex}")
77
  object: str = "chat.completion.chunk"
 
87
  if DEBUG_MODE:
88
  print(f"[DEBUG] {message}")
89
 
90
+ # --- 配置加载函数 ( Secrets 读取) ---
91
  def load_client_api_keys_from_secrets():
 
92
  global VALID_CLIENT_KEYS
93
  try:
94
  keys_str = os.environ.get("CLIENT_API_KEYS")
95
+ if not keys_str: raise ValueError("Secret 'CLIENT_API_KEYS' not found.")
 
96
  keys = json.loads(keys_str)
97
  VALID_CLIENT_KEYS = set(keys) if isinstance(keys, list) else set()
98
+ print(f"Successfully loaded {len(VALID_CLIENT_KEYS)} client API keys.")
99
  except Exception as e:
100
+ print(f"FATAL: Error loading client API keys: {e}")
101
  VALID_CLIENT_KEYS = set()
102
 
103
  def load_codegeex_tokens_from_secrets():
 
104
  global CODEGEEX_TOKENS
105
  CODEGEEX_TOKENS = []
106
  try:
107
  tokens_str = os.environ.get("CODEGEEX_TOKENS")
108
+ if not tokens_str: raise ValueError("Secret 'CODEGEEX_TOKENS' not found.")
109
+ tokens = json.loads(tokens_str)
110
+ if not isinstance(tokens, list): raise TypeError("Secret 'CODEGEEX_TOKENS' must be a JSON list.")
 
 
 
111
  for token in tokens:
112
  if isinstance(token, str) and token:
113
+ CODEGEEX_TOKENS.append({"token": token, "is_valid": True, "last_used": 0, "error_count": 0})
114
+ print(f"Successfully loaded {len(CODEGEEX_TOKENS)} CodeGeeX tokens.")
 
 
115
  except Exception as e:
116
+ print(f"FATAL: Error loading CodeGeeX tokens: {e}")
117
+
118
+ @app.on_event("startup")
119
+ async def startup():
120
+ print("Starting CodeGeeX OpenAI API Adapter server...")
121
+ load_client_api_keys_from_secrets()
122
+ load_codegeex_tokens_from_secrets()
123
+ print("Server initialization completed.")
124
+
125
+ # --- THE FIX: Add a root endpoint for the health check ---
126
+ @app.get("/")
127
+ def health_check():
128
+ """Health check endpoint for Hugging Face."""
129
+ return {"status": "ok", "message": "CodeGeeX API Adapter is running."}
130
+ # ---------------------------------------------------------
131
 
132
+ # --- 原始路由 ---
133
+ def get_models_list_response() -> ModelList:
134
+ return ModelList(data=[ModelInfo(id=model, created=int(time.time()), owned_by="anthropic") for model in CODEGEEX_MODELS])
135
+
136
+ @app.get("/v1/models", response_model=ModelList)
137
+ async def list_v1_models(_: None = Depends(authenticate_client)):
138
+ return get_models_list_response()
139
+
140
+ # ... (所有其他函数和路由都与之前的文件一致,无需改动)
141
+ # The rest of the original code is unchanged.
142
  def get_best_codegeex_token() -> Optional[CodeGeeXToken]:
143
  with token_rotation_lock:
144
  now = time.time()
 
173
  if not auth or not auth.credentials: raise HTTPException(status_code=401, detail="API key required.", headers={"WWW-Authenticate": "Bearer"})
174
  if auth.credentials not in VALID_CLIENT_KEYS: raise HTTPException(status_code=403, detail="Invalid client API key.")
175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  @app.get("/models", response_model=ModelList)
177
  async def list_models_no_auth():
178
  return get_models_list_response()
179
 
 
 
 
 
180
  def _codegeex_stream_generator(response, model: str):
181
  stream_id = f"chatcmpl-{uuid.uuid4().hex}"
182
  created_time = int(time.time())