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 line2345678187 unmodified lines19619719819819920020120218 unmodified lines2212222232232242252262262272282292301 unmodified lineimport jsonimport base64import timeimport loggingfrom datetime import datetimefrom fastapi import Request, HTTPException, Dependsfrom fastapi.security import HTTPBasic187 unmodified lines prompt="consent", include_granted_scopes='true' ) print(f"\nPlease open this URL in your browser to log in:\n{auth_url}\n") logging.info(f"Please open this URL in your browser to log in: {auth_url}") server = HTTPServer(("", 8080), _OAuthCallbackHandler) server.handle_request()18 unmodified lines credentials = flow.credentials credentials_from_env = False # Mark as file-based credentials save_credentials(credentials) print("Authentication successful! Credentials saved.") logging.info("Authentication successful! Credentials saved.") return credentials except Exception as e: print(f"Authentication failed: {e}") logging.error(f"Authentication failed: {e}") return None finally: oauthlib.oauth2.rfc6749.parameters.validate_token_parameters = original_validate114 unmodified lines115116117118119120121122123114 unmodified lines response_line = f"data: {response_json}\n\n" yield response_line await asyncio.sleep(0) else: obj_json = json.dumps(obj, separators=(',', ':')) yield f"data: {obj_json}\n\n" except json.JSONDecodeError: continue 123456789101112131415168 unmodified lines25262728293031323334272835363738303139404133424335364445464748import 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) print("Gemini proxy server started") print("Authentication required - Password: see .env file") 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: print(f"Setup failed: {str(e)}") print("Server started but may not function properly until setup issues are resolved.") logging.error(f"Setup failed: {str(e)}") logging.warning("Server started but may not function properly until setup issues are resolved.") else: print("Could not obtain credentials. Please authenticate and restart the server.") logging.error("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.") 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 lines678910111217 unmodified lines3031323233343536373839363738394040414243444546474849505152535455565758596061454647486263645051526566676869707172545556575859606162636465666768697071727374757677737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117801181191201217 unmodified lines1291301319495969798991321011021031331341351361371051381391401411421431441451461471071481491501511521531541551561571581591601611621631641111651661671689 unmodified lines1781791801811821831271281291301311321331341351361371381391401411421431441451461471481491501511521841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282291541551561571581591601611622302312322332342355 unmodified linesimport jsonimport uuidimport asyncioimport loggingfrom fastapi import APIRouter, Request, Response, Dependsfrom fastapi.responses import StreamingResponse
17 unmodified lines): """ OpenAI-compatible chat completions endpoint. Transforms OpenAI requests to Gemini format, sends to Google API, 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 format gemini_request_data = openai_request_to_gemini(request) # Build the payload for Google API gemini_payload = build_gemini_payload_from_openai(gemini_request_data) # Transform OpenAI request to Gemini format gemini_request_data = openai_request_to_gemini(request) # Build the payload for Google API gemini_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 response async def openai_stream_generator(): response = send_gemini_request(gemini_payload, is_streaming=True) if isinstance(response, StreamingResponse): response_id = "chatcmpl-" + str(uuid.uuid4()) try: response = send_gemini_request(gemini_payload, is_streaming=True) async for chunk in response.body_iterator: if isinstance(chunk, bytes): chunk = chunk.decode('utf-8') 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 chunk chunk_data = chunk[6:] # Remove 'data: ' prefix gemini_chunk = json.loads(chunk_data) # Transform to OpenAI format openai_chunk = gemini_stream_chunk_to_openai( gemini_chunk, request.model, response_id ) # Send as OpenAI streaming format yield f"data: {json.dumps(openai_chunk)}\n\n" await asyncio.sleep(0) except (json.JSONDecodeError, KeyError, UnicodeDecodeError) as e: continue # Send the final [DONE] marker yield "data: [DONE]\n\n" else: # Error case - forward the error response if chunk.startswith('data: '): try: # Parse the Gemini streaming chunk chunk_data = chunk[6:] # Remove 'data: ' prefix gemini_chunk = json.loads(chunk_data) # Transform to OpenAI format openai_chunk = gemini_stream_chunk_to_openai( gemini_chunk, request.model, response_id ) # Send as OpenAI streaming format yield 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] marker yield "data: [DONE]\n\n" logging.info(f"Completed streaming response: {response_id}") else: # Error case - log and forward the error response error_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": "Streaming request failed", "message": f"Streaming failed: {str(e)}", "type": "api_error" } }7 unmodified lines else: # Handle non-streaming response response = send_gemini_request(gemini_payload, is_streaming=False) if isinstance(response, Response) and response.status_code != 200: # Forward error responses as-is return response try: # Parse Gemini response and transform to OpenAI format gemini_response = json.loads(response.body) openai_response = gemini_response_to_openai(gemini_response, request.model) response = send_gemini_request(gemini_payload, is_streaming=False) if isinstance(response, Response) and response.status_code != 200: # Log and forward error responses logging.error(f"Gemini API error: status={response.status_code}, body={response.body}") return openai_response return response try: # Parse Gemini response and transform to OpenAI format gemini_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_response except (json.JSONDecodeError, AttributeError) as e: except (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": "Failed to process response", "message": f"Request failed: {str(e)}", "type": "api_error" } }),9 unmodified lines Returns available models in OpenAI format. """ try: logging.info("OpenAI models list requested") # Convert our Gemini models to OpenAI format from .config import SUPPORTED_MODELS openai_models = [] for model in SUPPORTED_MODELS: # Remove "models/" prefix for OpenAI compatibility model_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 # Convert our Gemini models to OpenAI format from .config import SUPPORTED_MODELS openai_models = [] for model in SUPPORTED_MODELS: # Remove "models/" prefix for OpenAI compatibility model_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" } ], "root": model_id, "parent": None }) return { "object": "list", "data": openai_models } }), 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