Delete chat2api.py
Browse files- chat2api.py +0 -254
chat2api.py
DELETED
|
@@ -1,254 +0,0 @@
|
|
| 1 |
-
import asyncio
|
| 2 |
-
import time
|
| 3 |
-
import types
|
| 4 |
-
import warnings
|
| 5 |
-
|
| 6 |
-
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
| 7 |
-
from fastapi import FastAPI, Request, Depends, HTTPException, Form
|
| 8 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
-
from fastapi.responses import HTMLResponse
|
| 10 |
-
from fastapi.responses import StreamingResponse, JSONResponse
|
| 11 |
-
from fastapi.security import OAuth2PasswordBearer
|
| 12 |
-
from fastapi.templating import Jinja2Templates
|
| 13 |
-
from starlette.background import BackgroundTask
|
| 14 |
-
from starlette.responses import RedirectResponse, Response
|
| 15 |
-
|
| 16 |
-
from chatgpt.ChatService import ChatService
|
| 17 |
-
from chatgpt.authorization import refresh_all_tokens, verify_token, get_req_token
|
| 18 |
-
import chatgpt.globals as globals
|
| 19 |
-
from chatgpt.reverseProxy import chatgpt_reverse_proxy
|
| 20 |
-
from utils.Logger import logger
|
| 21 |
-
from utils.config import api_prefix, scheduled_refresh, enable_gateway
|
| 22 |
-
from utils.retry import async_retry
|
| 23 |
-
|
| 24 |
-
warnings.filterwarnings("ignore")
|
| 25 |
-
|
| 26 |
-
app = FastAPI()
|
| 27 |
-
scheduler = AsyncIOScheduler()
|
| 28 |
-
templates = Jinja2Templates(directory="templates")
|
| 29 |
-
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token", auto_error=False)
|
| 30 |
-
|
| 31 |
-
app.add_middleware(
|
| 32 |
-
CORSMiddleware,
|
| 33 |
-
allow_origins=["*"],
|
| 34 |
-
allow_credentials=True,
|
| 35 |
-
allow_methods=["*"],
|
| 36 |
-
allow_headers=["*"],
|
| 37 |
-
)
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
@app.on_event("startup")
|
| 41 |
-
async def app_start():
|
| 42 |
-
if scheduled_refresh:
|
| 43 |
-
scheduler.add_job(id='refresh', func=refresh_all_tokens, trigger='cron', hour=3, minute=0, day='*/4',
|
| 44 |
-
kwargs={'force_refresh': True})
|
| 45 |
-
scheduler.start()
|
| 46 |
-
asyncio.get_event_loop().call_later(0, lambda: asyncio.create_task(refresh_all_tokens(force_refresh=False)))
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
async def to_send_conversation(request_data, req_token):
|
| 50 |
-
chat_service = ChatService(req_token)
|
| 51 |
-
try:
|
| 52 |
-
await chat_service.set_dynamic_data(request_data)
|
| 53 |
-
await chat_service.get_chat_requirements()
|
| 54 |
-
return chat_service
|
| 55 |
-
except HTTPException as e:
|
| 56 |
-
await chat_service.close_client()
|
| 57 |
-
raise HTTPException(status_code=e.status_code, detail=e.detail)
|
| 58 |
-
except Exception as e:
|
| 59 |
-
await chat_service.close_client()
|
| 60 |
-
logger.error(f"Server error, {str(e)}")
|
| 61 |
-
raise HTTPException(status_code=500, detail="Server error")
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
async def process(request_data, req_token):
|
| 65 |
-
chat_service = await to_send_conversation(request_data, req_token)
|
| 66 |
-
await chat_service.prepare_send_conversation()
|
| 67 |
-
res = await chat_service.send_conversation()
|
| 68 |
-
return chat_service, res
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
@app.post(f"/{api_prefix}/v1/chat/completions" if api_prefix else "/v1/chat/completions")
|
| 72 |
-
async def send_conversation(request: Request, req_token: str = Depends(oauth2_scheme)):
|
| 73 |
-
try:
|
| 74 |
-
request_data = await request.json()
|
| 75 |
-
except Exception:
|
| 76 |
-
raise HTTPException(status_code=400, detail={"error": "Invalid JSON body"})
|
| 77 |
-
chat_service, res = await async_retry(process, request_data, req_token)
|
| 78 |
-
try:
|
| 79 |
-
if isinstance(res, types.AsyncGeneratorType):
|
| 80 |
-
background = BackgroundTask(chat_service.close_client)
|
| 81 |
-
return StreamingResponse(res, media_type="text/event-stream", background=background)
|
| 82 |
-
else:
|
| 83 |
-
background = BackgroundTask(chat_service.close_client)
|
| 84 |
-
return JSONResponse(res, media_type="application/json", background=background)
|
| 85 |
-
except HTTPException as e:
|
| 86 |
-
await chat_service.close_client()
|
| 87 |
-
if e.status_code == 500:
|
| 88 |
-
logger.error(f"Server error, {str(e)}")
|
| 89 |
-
raise HTTPException(status_code=500, detail="Server error")
|
| 90 |
-
raise HTTPException(status_code=e.status_code, detail=e.detail)
|
| 91 |
-
except Exception as e:
|
| 92 |
-
await chat_service.close_client()
|
| 93 |
-
logger.error(f"Server error, {str(e)}")
|
| 94 |
-
raise HTTPException(status_code=500, detail="Server error")
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
@app.get(f"/{api_prefix}/tokens" if api_prefix else "/tokens", response_class=HTMLResponse)
|
| 98 |
-
async def upload_html(request: Request):
|
| 99 |
-
tokens_count = len(set(globals.token_list) - set(globals.error_token_list))
|
| 100 |
-
return templates.TemplateResponse("tokens.html",
|
| 101 |
-
{"request": request, "api_prefix": api_prefix, "tokens_count": tokens_count})
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
@app.post(f"/{api_prefix}/tokens/upload" if api_prefix else "/tokens/upload")
|
| 105 |
-
async def upload_post(text: str = Form(...)):
|
| 106 |
-
lines = text.split("\n")
|
| 107 |
-
for line in lines:
|
| 108 |
-
if line.strip() and not line.startswith("#"):
|
| 109 |
-
globals.token_list.append(line.strip())
|
| 110 |
-
with open("data/token.txt", "a", encoding="utf-8") as f:
|
| 111 |
-
f.write(line.strip() + "\n")
|
| 112 |
-
logger.info(f"Token count: {len(globals.token_list)}, Error token count: {len(globals.error_token_list)}")
|
| 113 |
-
tokens_count = len(set(globals.token_list) - set(globals.error_token_list))
|
| 114 |
-
return {"status": "success", "tokens_count": tokens_count}
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
@app.post(f"/{api_prefix}/tokens/clear" if api_prefix else "/tokens/clear")
|
| 118 |
-
async def upload_post():
|
| 119 |
-
globals.token_list.clear()
|
| 120 |
-
globals.error_token_list.clear()
|
| 121 |
-
with open("data/token.txt", "w", encoding="utf-8") as f:
|
| 122 |
-
pass
|
| 123 |
-
logger.info(f"Token count: {len(globals.token_list)}, Error token count: {len(globals.error_token_list)}")
|
| 124 |
-
tokens_count = len(set(globals.token_list) - set(globals.error_token_list))
|
| 125 |
-
return {"status": "success", "tokens_count": tokens_count}
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
@app.post(f"/{api_prefix}/tokens/error" if api_prefix else "/tokens/error")
|
| 129 |
-
async def error_tokens():
|
| 130 |
-
error_tokens_list = list(set(globals.error_token_list))
|
| 131 |
-
return {"status": "success", "error_tokens": error_tokens_list}
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
@app.get(f"/{api_prefix}/tokens/add/{{token}}" if api_prefix else "/tokens/add/{token}")
|
| 135 |
-
async def add_token(token: str):
|
| 136 |
-
if token.strip() and not token.startswith("#"):
|
| 137 |
-
globals.token_list.append(token.strip())
|
| 138 |
-
with open("data/token.txt", "a", encoding="utf-8") as f:
|
| 139 |
-
f.write(token.strip() + "\n")
|
| 140 |
-
logger.info(f"Token count: {len(globals.token_list)}, Error token count: {len(globals.error_token_list)}")
|
| 141 |
-
tokens_count = len(set(globals.token_list) - set(globals.error_token_list))
|
| 142 |
-
return {"status": "success", "tokens_count": tokens_count}
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
if enable_gateway:
|
| 146 |
-
@app.get("/", response_class=HTMLResponse)
|
| 147 |
-
async def chatgpt_html(request: Request):
|
| 148 |
-
token = request.query_params.get("token")
|
| 149 |
-
if not token:
|
| 150 |
-
token = request.cookies.get("token")
|
| 151 |
-
if not token:
|
| 152 |
-
return await login_html(request)
|
| 153 |
-
|
| 154 |
-
response = templates.TemplateResponse("chatgpt.html", {"request": request, "token": token})
|
| 155 |
-
response.set_cookie("token", value=token)
|
| 156 |
-
return response
|
| 157 |
-
|
| 158 |
-
@app.get("/login", response_class=HTMLResponse)
|
| 159 |
-
async def login_html(request: Request):
|
| 160 |
-
response = templates.TemplateResponse("login.html", {"request": request})
|
| 161 |
-
return response
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
@app.get("/backend-api/gizmos/bootstrap")
|
| 165 |
-
async def get_gizmos_bootstrap():
|
| 166 |
-
return {"gizmos": []}
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
# @app.get("/backend-api/conversations")
|
| 170 |
-
# async def get_conversations():
|
| 171 |
-
# return {"items": [], "total": 0, "limit": 28, "offset": 0, "has_missing_conversations": False}
|
| 172 |
-
|
| 173 |
-
# @app.patch("/backend-api/conversations")
|
| 174 |
-
# async def get_conversations():
|
| 175 |
-
# return {"success": True, "message": None}
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
@app.get("/backend-api/me")
|
| 179 |
-
async def get_me():
|
| 180 |
-
created = int(time.time())
|
| 181 |
-
return {
|
| 182 |
-
"object": "user",
|
| 183 |
-
"id": "org-chatgpt",
|
| 184 |
-
"email": "chatgpt@openai.com",
|
| 185 |
-
"name": "ChatGPT",
|
| 186 |
-
"picture": "https://cdn.auth0.com/avatars/ai.png",
|
| 187 |
-
"created": created,
|
| 188 |
-
"phone_number": None,
|
| 189 |
-
"mfa_flag_enabled": False,
|
| 190 |
-
"amr": [],
|
| 191 |
-
"groups": [],
|
| 192 |
-
"orgs": {
|
| 193 |
-
"object": "list",
|
| 194 |
-
"data": [
|
| 195 |
-
{
|
| 196 |
-
"object": "organization",
|
| 197 |
-
"id": "org-chatgpt",
|
| 198 |
-
"created": 1715641300,
|
| 199 |
-
"title": "Personal",
|
| 200 |
-
"name": "user-chatgpt",
|
| 201 |
-
"description": "Personal org for chatgpt@openai.com",
|
| 202 |
-
"personal": True,
|
| 203 |
-
"settings": {},
|
| 204 |
-
"parent_org_id": None,
|
| 205 |
-
"is_default": False,
|
| 206 |
-
"role": "owner",
|
| 207 |
-
"is_scale_tier_authorized_purchaser": None,
|
| 208 |
-
"is_scim_managed": False,
|
| 209 |
-
"projects": {
|
| 210 |
-
"object": "list",
|
| 211 |
-
"data": []
|
| 212 |
-
},
|
| 213 |
-
"groups": [],
|
| 214 |
-
"geography": None
|
| 215 |
-
}
|
| 216 |
-
]
|
| 217 |
-
},
|
| 218 |
-
"has_payg_project_spend_limit": None
|
| 219 |
-
}
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
banned_paths = [
|
| 223 |
-
"backend-api/accounts/logout_all",
|
| 224 |
-
"backend-api/accounts/deactivate",
|
| 225 |
-
"backend-api/user_system_messages",
|
| 226 |
-
"backend-api/memories",
|
| 227 |
-
"backend-api/settings/clear_account_user_memory"
|
| 228 |
-
]
|
| 229 |
-
redirect_paths = ["auth/logout"]
|
| 230 |
-
chatgpt_paths = ["c/"]
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH", "TRACE"])
|
| 234 |
-
async def reverse_proxy(request: Request, path: str):
|
| 235 |
-
for chatgpt_path in chatgpt_paths:
|
| 236 |
-
if chatgpt_path in path:
|
| 237 |
-
return await chatgpt_html(request)
|
| 238 |
-
|
| 239 |
-
for banned_path in banned_paths:
|
| 240 |
-
if banned_path in path:
|
| 241 |
-
return Response(status_code=404)
|
| 242 |
-
|
| 243 |
-
for redirect_path in redirect_paths:
|
| 244 |
-
if redirect_path in path:
|
| 245 |
-
redirect_url = str(request.base_url)
|
| 246 |
-
response = RedirectResponse(url=f"{redirect_url}", status_code=302)
|
| 247 |
-
response.delete_cookie("token")
|
| 248 |
-
return response
|
| 249 |
-
|
| 250 |
-
return await chatgpt_reverse_proxy(request, path)
|
| 251 |
-
else:
|
| 252 |
-
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH", "TRACE"])
|
| 253 |
-
async def reverse_proxy():
|
| 254 |
-
raise HTTPException(status_code=404, detail="Gateway is disabled")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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