main.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. from fastapi import FastAPI, Request, Response, HTTPException, Depends
  2. from fastapi.middleware.cors import CORSMiddleware
  3. from fastapi.responses import StreamingResponse, JSONResponse
  4. import requests
  5. import json
  6. from pydantic import BaseModel
  7. from apps.web.models.users import Users
  8. from constants import ERROR_MESSAGES
  9. from utils.utils import decode_token, get_current_user
  10. from config import OPENAI_API_BASE_URL, OPENAI_API_KEY
  11. app = FastAPI()
  12. app.add_middleware(
  13. CORSMiddleware,
  14. allow_origins=["*"],
  15. allow_credentials=True,
  16. allow_methods=["*"],
  17. allow_headers=["*"],
  18. )
  19. app.state.OPENAI_API_BASE_URL = OPENAI_API_BASE_URL
  20. app.state.OPENAI_API_KEY = OPENAI_API_KEY
  21. class UrlUpdateForm(BaseModel):
  22. url: str
  23. class KeyUpdateForm(BaseModel):
  24. key: str
  25. @app.get("/url")
  26. async def get_openai_url(user=Depends(get_current_user)):
  27. if user and user.role == "admin":
  28. return {"OPENAI_API_BASE_URL": app.state.OPENAI_API_BASE_URL}
  29. else:
  30. raise HTTPException(status_code=401,
  31. detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
  32. @app.post("/url/update")
  33. async def update_openai_url(form_data: UrlUpdateForm,
  34. user=Depends(get_current_user)):
  35. if user and user.role == "admin":
  36. app.state.OPENAI_API_BASE_URL = form_data.url
  37. return {"OPENAI_API_BASE_URL": app.state.OPENAI_API_BASE_URL}
  38. else:
  39. raise HTTPException(status_code=401,
  40. detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
  41. @app.get("/key")
  42. async def get_openai_key(user=Depends(get_current_user)):
  43. if user and user.role == "admin":
  44. return {"OPENAI_API_KEY": app.state.OPENAI_API_KEY}
  45. else:
  46. raise HTTPException(status_code=401,
  47. detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
  48. @app.post("/key/update")
  49. async def update_openai_key(form_data: KeyUpdateForm,
  50. user=Depends(get_current_user)):
  51. if user and user.role == "admin":
  52. app.state.OPENAI_API_KEY = form_data.key
  53. return {"OPENAI_API_KEY": app.state.OPENAI_API_KEY}
  54. else:
  55. raise HTTPException(status_code=401,
  56. detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
  57. @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
  58. async def proxy(path: str, request: Request, user=Depends(get_current_user)):
  59. target_url = f"{app.state.OPENAI_API_BASE_URL}/{path}"
  60. print(target_url, app.state.OPENAI_API_KEY)
  61. if user.role not in ["user", "admin"]:
  62. raise HTTPException(status_code=401,
  63. detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
  64. if app.state.OPENAI_API_KEY == "":
  65. raise HTTPException(status_code=401,
  66. detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)
  67. body = await request.body()
  68. # headers = dict(request.headers)
  69. # print(headers)
  70. headers = {}
  71. headers["Authorization"] = f"Bearer {app.state.OPENAI_API_KEY}"
  72. headers["Content-Type"] = "application/json"
  73. try:
  74. r = requests.request(
  75. method=request.method,
  76. url=target_url,
  77. data=body,
  78. headers=headers,
  79. stream=True,
  80. )
  81. r.raise_for_status()
  82. # Check if response is SSE
  83. if "text/event-stream" in r.headers.get("Content-Type", ""):
  84. return StreamingResponse(
  85. r.iter_content(chunk_size=8192),
  86. status_code=r.status_code,
  87. headers=dict(r.headers),
  88. )
  89. else:
  90. # For non-SSE, read the response and return it
  91. # response_data = (
  92. # r.json()
  93. # if r.headers.get("Content-Type", "")
  94. # == "application/json"
  95. # else r.text
  96. # )
  97. response_data = r.json()
  98. print(type(response_data))
  99. if "openai" in app.state.OPENAI_API_BASE_URL and path == "models":
  100. response_data["data"] = list(
  101. filter(lambda model: "gpt" in model["id"],
  102. response_data["data"]))
  103. return response_data
  104. except Exception as e:
  105. print(e)
  106. error_detail = "Ollama WebUI: Server Connection Error"
  107. if r is not None:
  108. try:
  109. res = r.json()
  110. if "error" in res:
  111. error_detail = f"External: {res['error']}"
  112. except:
  113. error_detail = f"External: {e}"
  114. raise HTTPException(status_code=r.status_code, detail=error_detail)