Spaces:
Running
Running
File size: 12,907 Bytes
d12a6b6 c3b0824 d12a6b6 c3b0824 d12a6b6 c3b0824 8061397 c3b0824 d12a6b6 c3b0824 d12a6b6 c3b0824 d12a6b6 c3b0824 8061397 c3b0824 8061397 c3b0824 8061397 c3b0824 8061397 c3b0824 8061397 c3b0824 8061397 c3b0824 8061397 c3b0824 d12a6b6 c3b0824 8061397 d12a6b6 c3b0824 d12a6b6 c3b0824 8061397 d12a6b6 c3b0824 8061397 c3b0824 d12a6b6 c3b0824 8061397 d12a6b6 c3b0824 8061397 d12a6b6 c3b0824 d12a6b6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 |
"""
OpenAI API Routes - Handles OpenAI-compatible endpoints.
This module provides OpenAI-compatible endpoints that transform requests/responses
and delegate to the Google API client.
"""
import json
import uuid
import asyncio
import logging
from fastapi import APIRouter, Request, Response, Depends
from fastapi.responses import StreamingResponse
from .auth import authenticate_user
from .models import OpenAIChatCompletionRequest
from .openai_transformers import (
openai_request_to_gemini,
gemini_response_to_openai,
gemini_stream_chunk_to_openai
)
from .google_api_client import send_gemini_request, build_gemini_payload_from_openai
router = APIRouter()
@router.post("/v1/chat/completions")
async def openai_chat_completions(
request: OpenAIChatCompletionRequest,
http_request: Request,
username: str = Depends(authenticate_user)
):
"""
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 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",
"code": 400
}
}),
status_code=400,
media_type="application/json"
)
if request.stream:
# Handle streaming response
async 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 chunk
chunk_data = chunk[6:] # Remove 'data: ' prefix
gemini_chunk = json.loads(chunk_data)
# Check if this is an error chunk
if "error" in gemini_chunk:
logging.error(f"Error in streaming response: {gemini_chunk['error']}")
# Transform error to OpenAI format
error_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 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 - handle Response object with error
error_msg = "Streaming request failed"
status_code = 500
if hasattr(response, 'status_code'):
status_code = response.status_code
error_msg += f" (status: {status_code})"
if hasattr(response, 'body'):
try:
# Try to parse error response
error_body = response.body
if 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:
pass
logging.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"
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",
"code": 500
}
}
yield f"data: {json.dumps(error_data)}\n\n"
yield "data: [DONE]\n\n"
return StreamingResponse(
openai_stream_generator(),
media_type="text/event-stream"
)
else:
# Handle non-streaming response
try:
response = send_gemini_request(gemini_payload, is_streaming=False)
if isinstance(response, Response) and response.status_code != 200:
# Handle error responses from Google API
logging.error(f"Gemini API error: status={response.status_code}")
try:
# Try to parse the error response and transform to OpenAI format
error_body = response.body
if 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 format
openai_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 response
return 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 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:
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",
"code": 500
}
}),
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",
"code": 500
}
}),
status_code=500,
media_type="application/json"
)
@router.get("/v1/models")
async def openai_list_models(username: str = Depends(authenticate_user)):
"""
OpenAI-compatible models endpoint.
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
}
],
"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",
"code": 500
}
}),
status_code=500,
media_type="application/json"
)
|