Commit ·
c3b0824
1
Parent(s): 32a0c88
added better logging
Browse filesFiles changed (4)
- src/auth.py+4-3
- src/google_api_client.py+3
- src/main.py+16-7
- src/openai_routes.py+156-85
1 unmodified line234567187 unmodified lines19519619719819920020118 unmodified lines2202212222232242252262272282291 unmodified lineimport jsonimport base64import timefrom datetime import datetimefrom fastapi import Request, HTTPException, Dependsfrom fastapi.security import HTTPBasic187 unmodified linesprompt="consent",include_granted_scopes='true')print(f"\nPlease open this URL in your browser to log in:\n{auth_url}\n")server = HTTPServer(("", 8080), _OAuthCallbackHandler)server.handle_request()18 unmodified linescredentials = flow.credentialscredentials_from_env = False # Mark as file-based credentialssave_credentials(credentials)print("Authentication successful! Credentials saved.")return credentialsexcept Exception as e:print(f"Authentication failed: {e}")return Nonefinally:oauthlib.oauth2.rfc6749.parameters.validate_token_parameters = original_validate1 unmodified line2345678187 unmodified lines19619719819920020120218 unmodified lines2212222232242252262272282292301 unmodified lineimport jsonimport base64import timeimport loggingfrom datetime import datetimefrom fastapi import Request, HTTPException, Dependsfrom fastapi.security import HTTPBasic187 unmodified linesprompt="consent",include_granted_scopes='true')logging.info(f"Please open this URL in your browser to log in: {auth_url}")server = HTTPServer(("", 8080), _OAuthCallbackHandler)server.handle_request()18 unmodified linescredentials = flow.credentialscredentials_from_env = False # Mark as file-based credentialssave_credentials(credentials)logging.info("Authentication successful! Credentials saved.")return credentialsexcept Exception as e:logging.error(f"Authentication failed: {e}")return Nonefinally:oauthlib.oauth2.rfc6749.parameters.validate_token_parameters = original_validate
114 unmodified lines115116117118119120114 unmodified linesresponse_line = f"data: {response_json}\n\n"yield response_lineawait asyncio.sleep(0)except json.JSONDecodeError:continue114 unmodified lines115116117118119120121122123114 unmodified linesresponse_line = f"data: {response_json}\n\n"yield response_lineawait asyncio.sleep(0)else:obj_json = json.dumps(obj, separators=(',', ':'))yield f"data: {obj_json}\n\n"except json.JSONDecodeError:continue
1234567898 unmodified lines18192021222324252627282930313233343536373839from fastapi import FastAPI, Request, Responsefrom fastapi.middleware.cors import CORSMiddlewarefrom .gemini_routes import router as gemini_routerfrom .openai_routes import router as openai_routerfrom .auth import get_credentials, get_user_project_id, onboard_userapp = FastAPI()# Add CORS middleware for preflight requests8 unmodified lines@app.on_event("startup")async def startup_event():try:creds = get_credentials()if creds:try:proj_id = get_user_project_id(creds)if proj_id:onboard_user(creds, proj_id)print("Gemini proxy server started")print("Authentication required - Password: see .env file")except Exception as e:print(f"Setup failed: {str(e)}")print("Server started but may not function properly until setup issues are resolved.")else:print("Could not obtain credentials. Please authenticate and restart the server.")except Exception as e:print(f"Startup error: {str(e)}")print("Server may not function properly.")@app.options("/{full_path:path}")async def handle_preflight(request: Request, full_path: str):123456789101112131415168 unmodified lines252627282930313233343536373839404142434445464748import loggingfrom fastapi import FastAPI, Request, Responsefrom fastapi.middleware.cors import CORSMiddlewarefrom .gemini_routes import router as gemini_routerfrom .openai_routes import router as openai_routerfrom .auth import get_credentials, get_user_project_id, onboard_user# Configure logginglogging.basicConfig(level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')app = FastAPI()# Add CORS middleware for preflight requests8 unmodified lines@app.on_event("startup")async def startup_event():try:logging.info("Starting Gemini proxy server...")creds = get_credentials()if creds:try:proj_id = get_user_project_id(creds)if proj_id:onboard_user(creds, proj_id)logging.info(f"Successfully onboarded with project ID: {proj_id}")logging.info("Gemini proxy server started successfully")logging.info("Authentication required - Password: see .env file")except Exception as e:logging.error(f"Setup failed: {str(e)}")logging.warning("Server started but may not function properly until setup issues are resolved.")else:logging.error("Could not obtain credentials. Please authenticate and restart the server.")except Exception as e:logging.error(f"Startup error: {str(e)}")logging.warning("Server may not function properly.")@app.options("/{full_path:path}")async def handle_preflight(request: Request, full_path: str):
5 unmodified lines6789101117 unmodified lines293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182837 unmodified lines9192939495969798991001011021031041051061071081091101111121131149 unmodified lines1241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631645 unmodified linesimport jsonimport uuidimport asynciofrom fastapi import APIRouter, Request, Response, Dependsfrom fastapi.responses import StreamingResponse17 unmodified lines):"""OpenAI-compatible chat completions endpoint.Transforms OpenAI requests to Gemini format, sends to Google API,and transforms responses back to OpenAI format."""# Transform OpenAI request to Gemini formatgemini_request_data = openai_request_to_gemini(request)# Build the payload for Google APIgemini_payload = build_gemini_payload_from_openai(gemini_request_data)if request.stream:# Handle streaming responseasync def openai_stream_generator():response = send_gemini_request(gemini_payload, is_streaming=True)if isinstance(response, StreamingResponse):response_id = "chatcmpl-" + str(uuid.uuid4())async for chunk in response.body_iterator:if isinstance(chunk, bytes):chunk = chunk.decode('utf-8')if chunk.startswith('data: '):try:# Parse the Gemini streaming chunkchunk_data = chunk[6:] # Remove 'data: ' prefixgemini_chunk = json.loads(chunk_data)# Transform to OpenAI formatopenai_chunk = gemini_stream_chunk_to_openai(gemini_chunk,request.model,response_id)# Send as OpenAI streaming formatyield f"data: {json.dumps(openai_chunk)}\n\n"await asyncio.sleep(0)except (json.JSONDecodeError, KeyError, UnicodeDecodeError) as e:continue# Send the final [DONE] markeryield "data: [DONE]\n\n"else:# Error case - forward the error responseerror_data = {"error": {"message": "Streaming request failed","type": "api_error"}}7 unmodified lineselse:# Handle non-streaming responseresponse = send_gemini_request(gemini_payload, is_streaming=False)if isinstance(response, Response) and response.status_code != 200:# Forward error responses as-isreturn responsetry:# Parse Gemini response and transform to OpenAI formatgemini_response = json.loads(response.body)openai_response = gemini_response_to_openai(gemini_response, request.model)return openai_responseexcept (json.JSONDecodeError, AttributeError) as e:return Response(content=json.dumps({"error": {"message": "Failed to process response","type": "api_error"}}),9 unmodified linesReturns available models in OpenAI format."""# Convert our Gemini models to OpenAI formatfrom .config import SUPPORTED_MODELSopenai_models = []for model in SUPPORTED_MODELS:# Remove "models/" prefix for OpenAI compatibilitymodel_id = model["name"].replace("models/", "")openai_models.append({"id": model_id,"object": "model","created": 1677610602, # Static timestamp"owned_by": "google","permission": [{"id": "modelperm-" + model_id.replace("/", "-"),"object": "model_permission","created": 1677610602,"allow_create_engine": False,"allow_sampling": True,"allow_logprobs": False,"allow_search_indices": False,"allow_view": True,"allow_fine_tuning": False,"organization": "*","group": None,"is_blocking": False}],"root": model_id,"parent": None})return {"object": "list","data": openai_models}5 unmodified lines678910111217 unmodified lines303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201217 unmodified lines1291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671689 unmodified lines1781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342355 unmodified linesimport jsonimport uuidimport asyncioimport loggingfrom fastapi import APIRouter, Request, Response, Dependsfrom fastapi.responses import StreamingResponse17 unmodified lines):"""OpenAI-compatible chat completions endpoint.Transforms OpenAI requests to Gemini format, sends to Google API,and transforms responses back to OpenAI format."""try:logging.info(f"OpenAI chat completion request: model={request.model}, stream={request.stream}")# Transform OpenAI request to Gemini formatgemini_request_data = openai_request_to_gemini(request)# Build the payload for Google APIgemini_payload = build_gemini_payload_from_openai(gemini_request_data)except Exception as e:logging.error(f"Error processing OpenAI request: {str(e)}")return Response(content=json.dumps({"error": {"message": f"Request processing failed: {str(e)}","type": "invalid_request_error"}}),status_code=400,media_type="application/json")if request.stream:# Handle streaming responseasync def openai_stream_generator():try:response = send_gemini_request(gemini_payload, is_streaming=True)if isinstance(response, StreamingResponse):response_id = "chatcmpl-" + str(uuid.uuid4())logging.info(f"Starting streaming response: {response_id}")async for chunk in response.body_iterator:if isinstance(chunk, bytes):chunk = chunk.decode('utf-8')if chunk.startswith('data: '):try:# Parse the Gemini streaming chunkchunk_data = chunk[6:] # Remove 'data: ' prefixgemini_chunk = json.loads(chunk_data)# Transform to OpenAI formatopenai_chunk = gemini_stream_chunk_to_openai(gemini_chunk,request.model,response_id)# Send as OpenAI streaming formatyield f"data: {json.dumps(openai_chunk)}\n\n"await asyncio.sleep(0)except (json.JSONDecodeError, KeyError, UnicodeDecodeError) as e:logging.warning(f"Failed to parse streaming chunk: {str(e)}")continue# Send the final [DONE] markeryield "data: [DONE]\n\n"logging.info(f"Completed streaming response: {response_id}")else:# Error case - log and forward the error responseerror_msg = "Streaming request failed"if hasattr(response, 'status_code'):error_msg += f" (status: {response.status_code})"if hasattr(response, 'body'):error_msg += f" (body: {response.body})"logging.error(error_msg)error_data = {"error": {"message": error_msg,"type": "api_error"}}yield f"data: {json.dumps(error_data)}\n\n"yield "data: [DONE]\n\n"except Exception as e:logging.error(f"Streaming error: {str(e)}")error_data = {"error": {"message": f"Streaming failed: {str(e)}","type": "api_error"}}7 unmodified lineselse:# Handle non-streaming responsetry:response = send_gemini_request(gemini_payload, is_streaming=False)if isinstance(response, Response) and response.status_code != 200:# Log and forward error responseslogging.error(f"Gemini API error: status={response.status_code}, body={response.body}")return responsetry:# Parse Gemini response and transform to OpenAI formatgemini_response = json.loads(response.body)openai_response = gemini_response_to_openai(gemini_response, request.model)logging.info(f"Successfully processed non-streaming response for model: {request.model}")return openai_responseexcept (json.JSONDecodeError, AttributeError) as e:logging.error(f"Failed to parse Gemini response: {str(e)}")return Response(content=json.dumps({"error": {"message": f"Failed to process response: {str(e)}","type": "api_error"}}),status_code=500,media_type="application/json")except Exception as e:logging.error(f"Non-streaming request failed: {str(e)}")return Response(content=json.dumps({"error": {"message": f"Request failed: {str(e)}","type": "api_error"}}),9 unmodified linesReturns available models in OpenAI format."""try:logging.info("OpenAI models list requested")# Convert our Gemini models to OpenAI formatfrom .config import SUPPORTED_MODELSopenai_models = []for model in SUPPORTED_MODELS:# Remove "models/" prefix for OpenAI compatibilitymodel_id = model["name"].replace("models/", "")openai_models.append({"id": model_id,"object": "model","created": 1677610602, # Static timestamp"owned_by": "google","permission": [{"id": "modelperm-" + model_id.replace("/", "-"),"object": "model_permission","created": 1677610602,"allow_create_engine": False,"allow_sampling": True,"allow_logprobs": False,"allow_search_indices": False,"allow_view": True,"allow_fine_tuning": False,"organization": "*","group": None,"is_blocking": False}],"root": model_id,"parent": None})logging.info(f"Returning {len(openai_models)} models")return {"object": "list","data": openai_models}except Exception as e:logging.error(f"Failed to list models: {str(e)}")return Response(content=json.dumps({"error": {"message": f"Failed to list models: {str(e)}","type": "api_error"}}),status_code=500,media_type="application/json")
src/auth.py+4-3
src/google_api_client.py+3
src/main.py+16-7
src/openai_routes.py+156-85