@@ -323,6 +323,28 @@ def epoch_clock():
323323 yield
324324 stop_event .set ()
325325
326+ def _prepare_proxy_and_headers (request : Request , authorization : Optional [str ]) -> tuple [DeepSeekProxy , str ]:
327+ """Helper to extract API key, filter headers, and instantiate the proxy."""
328+ request_id = request .headers .get ("x-request-id" , str (uuid .uuid4 ()))
329+ api_key = "dummy-key"
330+
331+ if SERVER_STATE .is_mock_mode :
332+ api_key = _MOCK_ENV_API_KEY or "mock-key"
333+ elif authorization :
334+ if not authorization .startswith ("Bearer " ):
335+ logger .warning (f"Rejected request { request_id } : Invalid Authorization Format" )
336+ raise HTTPException (status_code = 401 , detail = "Invalid Authorization header format. Expected 'Bearer <token>'" )
337+ api_key = authorization .replace ("Bearer " , "" )
338+
339+ logger .debug (f"using API Key: { api_key [:8 ]} ... for request { request_id } " )
340+
341+ unsafe_headers = {"host" , "content-length" , "content-type" , "authorization" , "connection" , "upgrade" , "accept-encoding" , "transfer-encoding" }
342+ forward_headers = {k : v for k , v in request .headers .items () if k .lower () not in unsafe_headers }
343+
344+ proxy = DeepSeekProxy (api_key = api_key , extra_headers = forward_headers )
345+ return proxy , request_id
346+
347+
326348def create_app () -> FastAPI :
327349 app = FastAPI (title = "DeepSeek-DashScope Proxy" , lifespan = lifespan )
328350 app .add_middleware (
@@ -360,30 +382,7 @@ async def generation(
360382 body : GenerationRequest = None ,
361383 authorization : Optional [str ] = Header (None )
362384 ):
363- request_id = request .headers .get ("x-request-id" , str (uuid .uuid4 ()))
364-
365- # --- [Logic Switch: Mock vs Production] ---
366-
367- api_key = "dummy-key"
368- if SERVER_STATE .is_mock_mode :
369- # In MOCK mode, we can optionally use the shadow/env key
370- api_key = _MOCK_ENV_API_KEY or "mock-key"
371- elif authorization :
372- if not authorization .startswith ("Bearer " ):
373- logger .warning (f"Rejected request { request_id } : Invalid Authorization Format" )
374- raise HTTPException (status_code = 401 , detail = "Invalid Authorization header format. Expected 'Bearer <token>'" )
375-
376- # Transparently forward the user's key
377- api_key = authorization .replace ("Bearer " , "" )
378-
379- logger .debug (f"using API Key: { api_key [:8 ]} ... for request { request_id } " )
380-
381- # 过滤掉不安全的或由 httpx 库自动管理的 Headers
382- unsafe_headers = {"host" , "content-length" , "content-type" , "authorization" , "connection" , "upgrade" , "accept-encoding" , "transfer-encoding" }
383- forward_headers = {k : v for k , v in request .headers .items () if k .lower () not in unsafe_headers }
384-
385- # Instantiate Proxy with the specific key AND headers
386- proxy = DeepSeekProxy (api_key = api_key , extra_headers = forward_headers )
385+ proxy , request_id = _prepare_proxy_and_headers (request , authorization )
387386
388387 # Parse Body if not injected
389388 if not body :
@@ -433,19 +432,7 @@ async def dynamic_path_generation(
433432 request : Request ,
434433 authorization : Optional [str ] = Header (None )
435434 ):
436- api_key = "dummy-key"
437- if authorization :
438- if not authorization .startswith ("Bearer " ):
439- logger .warning ("Rejected request: Invalid Authorization Format" )
440- raise HTTPException (status_code = 401 , detail = "Invalid Authorization header format. Expected 'Bearer <token>'" )
441- api_key = authorization .replace ("Bearer " , "" )
442-
443- request_id = request .headers .get ("x-request-id" , str (uuid .uuid4 ()))
444-
445- unsafe_headers = {"host" , "content-length" , "content-type" , "authorization" , "connection" , "upgrade" , "accept-encoding" , "transfer-encoding" }
446- forward_headers = {k : v for k , v in request .headers .items () if k .lower () not in unsafe_headers }
447-
448- proxy = DeepSeekProxy (api_key = api_key , extra_headers = forward_headers )
435+ proxy , request_id = _prepare_proxy_and_headers (request , authorization )
449436
450437 # 2. Parse, Inject Model, and Validate
451438 try :
0 commit comments