Commit ·
8061397
1
Parent(s): c3b0824
added error logging and handling
Browse filesFiles changed (3)
- src/gemini_routes.py+90-48
- src/google_api_client.py+112-20
- src/openai_routes.py+83-13
3 unmodified lines45678910 unmodified lines2021222324252627282930313233349 unmodified lines44454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495963 unmodified lineswithout any format transformations."""import jsonfrom fastapi import APIRouter, Request, Response, Dependsfrom .auth import authenticate_user10 unmodified linesReturns available models in Gemini format, matching the official Gemini API."""models_response = {"models": SUPPORTED_MODELS}return Response(content=json.dumps(models_response),status_code=200,media_type="application/json; charset=utf-8")@router.api_route("/{full_path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"])9 unmodified lines- etc."""# Get the request bodypost_data = await request.body()# Determine if this is a streaming requestis_streaming = "stream" in full_path.lower()# Extract model name from the path# Paths typically look like: v1beta/models/gemini-1.5-pro/generateContentmodel_name = _extract_model_from_path(full_path)if not model_name:return Response(content=json.dumps({"error": {"message": f"Could not extract model name from path: {full_path}","code": 400}}),status_code=400,media_type="application/json")# Parse the incoming requesttry:if post_data:incoming_request = json.loads(post_data)else:incoming_request = {}except json.JSONDecodeError:return Response(content=json.dumps({"error": {"message": "Invalid JSON in request body","code": 400}}),status_code=400,media_type="application/json")# Build the payload for Google APIgemini_payload = build_gemini_payload_from_native(incoming_request, model_name)# Send the request to Google APIresponse = send_gemini_request(gemini_payload, is_streaming=is_streaming)return responsedef _extract_model_from_path(path: str) -> str:3 unmodified lines4567891010 unmodified lines212223242526272829303132333435363738394041424344454647484950519 unmodified lines6162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371383 unmodified lineswithout any format transformations."""import jsonimport loggingfrom fastapi import APIRouter, Request, Response, Dependsfrom .auth import authenticate_user10 unmodified linesReturns available models in Gemini format, matching the official Gemini API."""try:logging.info("Gemini models list requested")models_response = {"models": SUPPORTED_MODELS}logging.info(f"Returning {len(SUPPORTED_MODELS)} Gemini models")return Response(content=json.dumps(models_response),status_code=200,media_type="application/json; charset=utf-8")except Exception as e:logging.error(f"Failed to list Gemini models: {str(e)}")return Response(content=json.dumps({"error": {"message": f"Failed to list models: {str(e)}","code": 500}}),status_code=500,media_type="application/json")@router.api_route("/{full_path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"])9 unmodified lines- etc."""try:# Get the request bodypost_data = await request.body()# Determine if this is a streaming requestis_streaming = "stream" in full_path.lower()# Extract model name from the path# Paths typically look like: v1beta/models/gemini-1.5-pro/generateContentmodel_name = _extract_model_from_path(full_path)logging.info(f"Gemini proxy request: path={full_path}, model={model_name}, stream={is_streaming}")if not model_name:logging.error(f"Could not extract model name from path: {full_path}")return Response(content=json.dumps({"error": {"message": f"Could not extract model name from path: {full_path}","code": 400}}),status_code=400,media_type="application/json")# Parse the incoming requesttry:if post_data:incoming_request = json.loads(post_data)else:incoming_request = {}except json.JSONDecodeError as e:logging.error(f"Invalid JSON in request body: {str(e)}")return Response(content=json.dumps({"error": {"message": "Invalid JSON in request body","code": 400}}),status_code=400,media_type="application/json")# Build the payload for Google APIgemini_payload = build_gemini_payload_from_native(incoming_request, model_name)# Send the request to Google APIresponse = send_gemini_request(gemini_payload, is_streaming=is_streaming)# Log the response statusif hasattr(response, 'status_code'):if response.status_code != 200:logging.error(f"Gemini API returned error: status={response.status_code}")else:logging.info(f"Successfully processed Gemini request for model: {model_name}")return responseexcept Exception as e:logging.error(f"Gemini proxy error: {str(e)}")return Response(content=json.dumps({"error": {"message": f"Proxy error: {str(e)}","code": 500}}),status_code=500,media_type="application/json")def _extract_model_from_path(path: str) -> str:
2 unmodified lines34567871 unmodified lines80818283848586878889909192939495969798991001011021031041051061071084 unmodified lines11311411511611711811912012112212312412512612712812913022 unmodified lines1531541551561571581591601611621631641651661671681691701711722 unmodified linesThis module is used by both OpenAI compatibility layer and native Gemini endpoints."""import jsonimport requestsfrom fastapi import Responsefrom fastapi.responses import StreamingResponse71 unmodified linesfinal_post_data = json.dumps(final_payload)# Send the requestif is_streaming:resp = requests.post(target_url, data=final_post_data, headers=request_headers, stream=True)return _handle_streaming_response(resp)else:resp = requests.post(target_url, data=final_post_data, headers=request_headers)return _handle_non_streaming_response(resp)def _handle_streaming_response(resp) -> StreamingResponse:"""Handle streaming response from Google API."""async def stream_generator():try:with resp:resp.raise_for_status()for chunk in resp.iter_lines():if chunk:if not isinstance(chunk, str):chunk = chunk.decode('utf-8')if chunk.startswith('data: '):chunk = chunk[len('data: '):]4 unmodified linesresponse_chunk = obj["response"]response_json = json.dumps(response_chunk, separators=(',', ':'))response_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:continueexcept requests.exceptions.RequestException as e:yield f'data: {{"error": {{"message": "Upstream request failed: {str(e)}"}}}}\n\n'.encode('utf-8')except Exception as e:yield f'data: {{"error": {{"message": "An unexpected error occurred: {str(e)}"}}}}\n\n'.encode('utf-8')response_headers = {"Content-Type": "text/event-stream",22 unmodified linesgoogle_api_response = json.loads(google_api_response)standard_gemini_response = google_api_response.get("response")return Response(content=json.dumps(standard_gemini_response),status_code=200,media_type="application/json; charset=utf-8")except (json.JSONDecodeError, AttributeError) as e:return Response(content=resp.content,status_code=resp.status_code,media_type=resp.headers.get("Content-Type"))else:return Response(content=resp.content,status_code=resp.status_code,media_type=resp.headers.get("Content-Type"))2 unmodified lines345678971 unmodified lines818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581594 unmodified lines16416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619722 unmodified lines2202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642 unmodified linesThis module is used by both OpenAI compatibility layer and native Gemini endpoints."""import jsonimport loggingimport requestsfrom fastapi import Responsefrom fastapi.responses import StreamingResponse71 unmodified linesfinal_post_data = json.dumps(final_payload)# Send the requesttry:if is_streaming:resp = requests.post(target_url, data=final_post_data, headers=request_headers, stream=True)return _handle_streaming_response(resp)else:resp = requests.post(target_url, data=final_post_data, headers=request_headers)return _handle_non_streaming_response(resp)except requests.exceptions.RequestException as e:logging.error(f"Request to Google API failed: {str(e)}")return Response(content=json.dumps({"error": {"message": f"Request failed: {str(e)}"}}),status_code=500,media_type="application/json")except Exception as e:logging.error(f"Unexpected error during Google API request: {str(e)}")return Response(content=json.dumps({"error": {"message": f"Unexpected error: {str(e)}"}}),status_code=500,media_type="application/json")def _handle_streaming_response(resp) -> StreamingResponse:"""Handle streaming response from Google API."""# Check for HTTP errors before starting to streamif resp.status_code != 200:logging.error(f"Google API returned status {resp.status_code}: {resp.text}")error_message = f"Google API error: {resp.status_code}"try:error_data = resp.json()if "error" in error_data:error_message = error_data["error"].get("message", error_message)except:pass# Return error as a streaming responseasync def error_generator():error_response = {"error": {"message": error_message,"type": "invalid_request_error" if resp.status_code == 404 else "api_error","code": resp.status_code}}yield f'data: {json.dumps(error_response)}\n\n'.encode('utf-8')response_headers = {"Content-Type": "text/event-stream","Content-Disposition": "attachment","Vary": "Origin, X-Origin, Referer","X-XSS-Protection": "0","X-Frame-Options": "SAMEORIGIN","X-Content-Type-Options": "nosniff","Server": "ESF"}return StreamingResponse(error_generator(),media_type="text/event-stream",headers=response_headers,status_code=resp.status_code)async def stream_generator():try:with resp:for chunk in resp.iter_lines():if chunk:if not isinstance(chunk, str):chunk = chunk.decode('utf-8')if chunk.startswith('data: '):chunk = chunk[len('data: '):]4 unmodified linesresponse_chunk = obj["response"]response_json = json.dumps(response_chunk, separators=(',', ':'))response_line = f"data: {response_json}\n\n"yield response_line.encode('utf-8')await asyncio.sleep(0)else:obj_json = json.dumps(obj, separators=(',', ':'))yield f"data: {obj_json}\n\n".encode('utf-8')except json.JSONDecodeError:continueexcept requests.exceptions.RequestException as e:logging.error(f"Streaming request failed: {str(e)}")error_response = {"error": {"message": f"Upstream request failed: {str(e)}","type": "api_error","code": 502}}yield f'data: {json.dumps(error_response)}\n\n'.encode('utf-8')except Exception as e:logging.error(f"Unexpected error during streaming: {str(e)}")error_response = {"error": {"message": f"An unexpected error occurred: {str(e)}","type": "api_error","code": 500}}yield f'data: {json.dumps(error_response)}\n\n'.encode('utf-8')response_headers = {"Content-Type": "text/event-stream",22 unmodified linesgoogle_api_response = json.loads(google_api_response)standard_gemini_response = google_api_response.get("response")return Response(content=json.dumps(standard_gemini_response),status_code=200,media_type="application/json; charset=utf-8")except (json.JSONDecodeError, AttributeError) as e:logging.error(f"Failed to parse Google API response: {str(e)}")return Response(content=resp.content,status_code=resp.status_code,media_type=resp.headers.get("Content-Type"))else:# Log the error detailslogging.error(f"Google API returned status {resp.status_code}: {resp.text}")# Try to parse error response and provide meaningful error messagetry:error_data = resp.json()if "error" in error_data:error_message = error_data["error"].get("message", f"API error: {resp.status_code}")error_response = {"error": {"message": error_message,"type": "invalid_request_error" if resp.status_code == 404 else "api_error","code": resp.status_code}}return Response(content=json.dumps(error_response),status_code=resp.status_code,media_type="application/json")except (json.JSONDecodeError, KeyError):pass# Fallback to original response if we can't parse the errorreturn Response(content=resp.content,status_code=resp.status_code,media_type=resp.headers.get("Content-Type"))
48 unmodified lines4950515253545520 unmodified lines76777879808113 unmodified lines95969798991001011021031041051061071081091101111123 unmodified lines11611711811912012112210 unmodified lines1331341351361371381391401419 unmodified lines1511521531541551561575 unmodified lines16316416516616716816955 unmodified lines22522622722822923023148 unmodified linescontent=json.dumps({"error": {"message": f"Request processing failed: {str(e)}","type": "invalid_request_error"}}),status_code=400,20 unmodified lineschunk_data = chunk[6:] # Remove 'data: ' prefixgemini_chunk = json.loads(chunk_data)# Transform to OpenAI formatopenai_chunk = gemini_stream_chunk_to_openai(gemini_chunk,13 unmodified linesyield "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"3 unmodified lineserror_data = {"error": {"message": f"Streaming failed: {str(e)}","type": "api_error"}}yield f"data: {json.dumps(error_data)}\n\n"10 unmodified linesresponse = 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 format9 unmodified linescontent=json.dumps({"error": {"message": f"Failed to process response: {str(e)}","type": "api_error"}}),status_code=500,5 unmodified linescontent=json.dumps({"error": {"message": f"Request failed: {str(e)}","type": "api_error"}}),status_code=500,55 unmodified linescontent=json.dumps({"error": {"message": f"Failed to list models: {str(e)}","type": "api_error"}}),status_code=500,48 unmodified lines495051525354555620 unmodified lines77787980818283848586878889909192939495969713 unmodified lines1111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411423 unmodified lines14614714814915015115215310 unmodified lines1641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072089 unmodified lines2182192202212222232242255 unmodified lines23123223323423523623723855 unmodified lines29429529629729829930030148 unmodified linescontent=json.dumps({"error": {"message": f"Request processing failed: {str(e)}","type": "invalid_request_error","code": 400}}),status_code=400,20 unmodified lineschunk_data = chunk[6:] # Remove 'data: ' prefixgemini_chunk = json.loads(chunk_data)# Check if this is an error chunkif "error" in gemini_chunk:logging.error(f"Error in streaming response: {gemini_chunk['error']}")# Transform error to OpenAI formaterror_data = {"error": {"message": gemini_chunk["error"].get("message", "Unknown error"),"type": gemini_chunk["error"].get("type", "api_error"),"code": gemini_chunk["error"].get("code")}}yield f"data: {json.dumps(error_data)}\n\n"yield "data: [DONE]\n\n"return# Transform to OpenAI formatopenai_chunk = gemini_stream_chunk_to_openai(gemini_chunk,13 unmodified linesyield "data: [DONE]\n\n"logging.info(f"Completed streaming response: {response_id}")else:# Error case - handle Response object with errorerror_msg = "Streaming request failed"status_code = 500if hasattr(response, 'status_code'):status_code = response.status_codeerror_msg += f" (status: {status_code})"if hasattr(response, 'body'):try:# Try to parse error responseerror_body = response.bodyif isinstance(error_body, bytes):error_body = error_body.decode('utf-8')error_data = json.loads(error_body)if "error" in error_data:error_msg = error_data["error"].get("message", error_msg)except:passlogging.error(f"Streaming request failed: {error_msg}")error_data = {"error": {"message": error_msg,"type": "invalid_request_error" if status_code == 404 else "api_error","code": status_code}}yield f"data: {json.dumps(error_data)}\n\n"3 unmodified lineserror_data = {"error": {"message": f"Streaming failed: {str(e)}","type": "api_error","code": 500}}yield f"data: {json.dumps(error_data)}\n\n"10 unmodified linesresponse = send_gemini_request(gemini_payload, is_streaming=False)if isinstance(response, Response) and response.status_code != 200:# Handle error responses from Google APIlogging.error(f"Gemini API error: status={response.status_code}")try:# Try to parse the error response and transform to OpenAI formaterror_body = response.bodyif isinstance(error_body, bytes):error_body = error_body.decode('utf-8')error_data = json.loads(error_body)if "error" in error_data:# Transform Google API error to OpenAI formatopenai_error = {"error": {"message": error_data["error"].get("message", f"API error: {response.status_code}"),"type": error_data["error"].get("type", "invalid_request_error" if response.status_code == 404 else "api_error"),"code": error_data["error"].get("code", response.status_code)}}return Response(content=json.dumps(openai_error),status_code=response.status_code,media_type="application/json")except (json.JSONDecodeError, UnicodeDecodeError):pass# Fallback error responsereturn Response(content=json.dumps({"error": {"message": f"API error: {response.status_code}","type": "invalid_request_error" if response.status_code == 404 else "api_error","code": response.status_code}}),status_code=response.status_code,media_type="application/json")try:# Parse Gemini response and transform to OpenAI format9 unmodified linescontent=json.dumps({"error": {"message": f"Failed to process response: {str(e)}","type": "api_error","code": 500}}),status_code=500,5 unmodified linescontent=json.dumps({"error": {"message": f"Request failed: {str(e)}","type": "api_error","code": 500}}),status_code=500,55 unmodified linescontent=json.dumps({"error": {"message": f"Failed to list models: {str(e)}","type": "api_error","code": 500}}),status_code=500,
src/gemini_routes.py+90-48
src/google_api_client.py+112-20
src/openai_routes.py+83-13