Spaces:
Sleeping
Sleeping
File size: 5,163 Bytes
6a12693 89860e6 917117f |
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 |
import uvicorn
import requests
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Dict
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# API Configuration
TOKEN_URL = "https://spuckhogycrxcbomznwo.supabase.co/auth/v1/token?grant_type=refresh_token"
GPT_URL = "https://not-diamond-workers.t7-cc4.workers.dev/stream-message"
# Global token storage
ACCESS_TOKEN = "eyJhbGciOiJIUzI1NiIsImtpZCI6Im1ZMmorY1dRdWFNTEp3d1AiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL3NwdWNraG9neWNyeGNib216bndvLnN1cGFiYXNlLmNvL2F1dGgvdjEiLCJzdWIiOiI1NzRjZDQ1OS1jNDFiLTQ3MTgtODRlNi0xZWRhNGZiZDI2MWUiLCJhdWQiOiJhdXRoZW50aWNhdGVkIiwiZXhwIjoxNzMyMzY4NDQxLCJpYXQiOjE3MzIzNjQ4NDEsImVtYWlsIjoiYWxob29yc2hvcHBAZ21haWwuY29tIiwicGhvbmUiOiIiLCJhcHBfbWV0YWRhdGEiOnsicHJvdmlkZXIiOiJnb29nbGUiLCJwcm92aWRlcnMiOlsiZ29vZ2xlIl19LCJ1c2VyX21ldGFkYXRhIjp7ImF2YXRhcl91cmwiOiJodHRwczovL2xoMy5nb29nbGV1c2VyY29udGVudC5jb20vYS9BQ2c4b2NMeVN2MUtwakxHMnNTMm44bGtwNzBqSWRid1ZDRTFqWjNEOWQ4c3RSNm5Xb1JVb3c9czk2LWMiLCJlbWFpbCI6ImFsaG9vcnNob3BwQGdtYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJmdWxsX25hbWUiOiJBbGhvb3IgU2hvcHAiLCJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJuYW1lIjoiQWxob29yIFNob3BwIiwicGhvbmVfdmVyaWZpZWQiOmZhbHNlLCJwaWN0dXJlIjoiaHR0cHM6Ly9saDMuZ29vZ2xldXNlcmNvbnRlbnQuY29tL2EvQUNnOG9jTHlTdjFLcGpMRzJzUzJuOGxrcDcwaklkYndWQ0UxalozRDlkOHN0UjZuV29SVW93PXM5Ni1jIiwicHJvdmlkZXJfaWQiOiIxMDE3NjY0MjA3Nzk0MjU0OTgwNDYiLCJzdWIiOiIxMDE3NjY0MjA3Nzk0MjU0OTgwNDYifSwicm9sZSI6ImF1dGhlbnRpY2F0ZWQiLCJhYWwiOiJhYWwxIiwiYW1yIjpbeyJtZXRob2QiOiJvYXV0aCIsInRpbWVzdGFtcCI6MTczMjM2MTAxNn1dLCJzZXNzaW9uX2lkIjoiZWZlNTRmMzgtYjFhYS00NjNmLThhODgtM2JiOWVjMTVmYTlkIiwiaXNfYW5vbnltb3VzIjpmYWxzZX0.fCdK8WF4ipmSucvRTtcs0-wgpzkeY6dIlKD62IjYS7M"
REFRESH_TOKEN = "VW2ol3sRN7S_-LqLtBE_fQ"
app = FastAPI(title="AI Response Server")
# Pydantic model for request validation
class MessageRequest(BaseModel):
messages: List[Dict[str, str]]
model: str = "chatgpt-4o-latest"
temperature: float = 0.9
# Token Refresh Function
def refresh_access_token(refresh_token: str):
global ACCESS_TOKEN
headers = {
"Authorization": f"Bearer {refresh_token}",
"Content-Type": "application/json"
}
payload = {"refresh_token": refresh_token}
try:
response = requests.post(TOKEN_URL, headers=headers, json=payload)
response.raise_for_status()
tokens = response.json()
ACCESS_TOKEN = tokens.get("access_token")
new_refresh_token = tokens.get("refresh_token")
logger.info("Access token refreshed successfully")
return ACCESS_TOKEN, new_refresh_token
except requests.exceptions.RequestException as e:
logger.error(f"Token refresh failed: {e}")
return None, None
# GPT Message Sending Function
def send_message_to_gpt(messages: List[Dict[str, str]], model: str = "chatgpt-4o-latest", temperature: float = 0.9):
global ACCESS_TOKEN
headers = {
"Authorization": f"Bearer {ACCESS_TOKEN}",
"Content-Type": "application/json"
}
payload = {
"messages": messages,
"model": model,
"temperature": temperature
}
try:
response = requests.post(GPT_URL, headers=headers, json=payload)
response.raise_for_status()
return response.text
except requests.exceptions.HTTPError as http_err:
if response.status_code == 401: # Unauthorized, token might be expired
logger.warning("Access token expired. Attempting to refresh...")
new_access_token, _ = refresh_access_token(REFRESH_TOKEN)
if new_access_token:
# Retry the request with the new token
return send_message_to_gpt(messages, model, temperature)
logger.error(f"HTTP error occurred: {http_err}")
raise HTTPException(status_code=500, detail=f"GPT API request failed: {http_err}")
except requests.exceptions.RequestException as req_err:
logger.error(f"Request error: {req_err}")
raise HTTPException(status_code=500, detail=f"Request to GPT failed: {req_err}")
# Endpoint for GPT interaction
@app.post("/get-response")
async def get_gpt_response(request: MessageRequest):
try:
response = send_message_to_gpt(
messages=request.messages,
model=request.model,
temperature=request.temperature
)
return {"response": response}
except HTTPException as e:
raise e
# Health check endpoint
@app.get("/health")
async def health_check():
return {"status": "healthy"}
# DNS Resolution Test Endpoint
@app.get("/test-dns")
async def test_dns():
try:
import socket
socket.gethostbyname('not-diamond-workers.t7-cc4.workers.dev')
return {"status": "success", "message": "DNS resolution successful"}
except Exception as e:
return {"status": "failure", "error": str(e)}
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host='not-diamond-workers.t7-cc4.workers.dev', port=8000) |