Update app.py
Browse files
app.py
CHANGED
|
@@ -12,20 +12,19 @@ from pydantic import BaseModel
|
|
| 12 |
# Configuration
|
| 13 |
API_CHALLENGE_URL = 'https://api.eqing.tech/api/altcaptcha/challenge'
|
| 14 |
NEXTWAY_CHAT_URL = 'https://origin.eqing.tech/api/openai/v1/chat/completions'
|
| 15 |
-
CREDENTIAL_EXPIRY_MARGIN = 60 * 1000
|
| 16 |
PORT = 7860
|
| 17 |
API_ENDPOINT = '/v1/chat/completions'
|
| 18 |
MODEL_NAME = "gpt-4o-free"
|
| 19 |
-
REQUEST_TIMEOUT = 480
|
| 20 |
MAX_RETRIES = 3
|
| 21 |
-
RETRY_DELAY = 1
|
| 22 |
|
| 23 |
# Global variables
|
| 24 |
current_credential = None
|
| 25 |
credential_expiry = None
|
| 26 |
is_refreshing_credential = False
|
| 27 |
|
| 28 |
-
# Model mappings
|
| 29 |
MODEL_MAPPING = {
|
| 30 |
'gpt-4o-all-lite': 'gpt-4o-mini',
|
| 31 |
'gpt-4o-image': 'gpt-4o-mini-image-free',
|
|
@@ -45,32 +44,47 @@ class ChatRequest(BaseModel):
|
|
| 45 |
top_p: Optional[float] = 1
|
| 46 |
max_tokens: Optional[int] = 4000
|
| 47 |
|
| 48 |
-
def
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
if
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
async def solve_challenge(challenge: str, salt: str, algorithm: str = "SHA-512", max_number: int = 1000000):
|
| 76 |
start_time = time.time()
|
|
@@ -155,36 +169,7 @@ async def get_credential():
|
|
| 155 |
|
| 156 |
return current_credential
|
| 157 |
|
| 158 |
-
|
| 159 |
-
async def chat_endpoint(request: ChatRequest):
|
| 160 |
-
try:
|
| 161 |
-
model = MODEL_MAPPING.get(request.model, request.model or MODEL_NAME)
|
| 162 |
-
response_content = await handle_chat_request(model, request.messages)
|
| 163 |
-
|
| 164 |
-
if response_content is None:
|
| 165 |
-
return Response(
|
| 166 |
-
content="Failed to get response from API",
|
| 167 |
-
status_code=500
|
| 168 |
-
)
|
| 169 |
-
|
| 170 |
-
return {
|
| 171 |
-
"choices": [{
|
| 172 |
-
"message": {
|
| 173 |
-
"role": "assistant",
|
| 174 |
-
"content": response_content.strip()
|
| 175 |
-
},
|
| 176 |
-
"finish_reason": "stop",
|
| 177 |
-
"index": 0
|
| 178 |
-
}],
|
| 179 |
-
"model": model,
|
| 180 |
-
"object": "chat.completion"
|
| 181 |
-
}
|
| 182 |
-
|
| 183 |
-
except Exception as e:
|
| 184 |
-
print(f"Error handling chat request: {e}")
|
| 185 |
-
return Response(content="Internal server error", status_code=500)
|
| 186 |
-
|
| 187 |
-
async def handle_chat_request(model: str, messages: List[Dict[str, str]]):
|
| 188 |
captcha_token = await get_credential()
|
| 189 |
if not captcha_token:
|
| 190 |
return None
|
|
@@ -206,24 +191,51 @@ async def handle_chat_request(model: str, messages: List[Dict[str, str]]):
|
|
| 206 |
async with session.post(
|
| 207 |
NEXTWAY_CHAT_URL,
|
| 208 |
json=body,
|
| 209 |
-
timeout=REQUEST_TIMEOUT
|
| 210 |
) as response:
|
| 211 |
if response.status != 200:
|
|
|
|
|
|
|
|
|
|
| 212 |
return None
|
| 213 |
|
| 214 |
-
|
| 215 |
-
async for chunk in response.content:
|
| 216 |
-
chunk_text = chunk.decode()
|
| 217 |
-
content = extract_content(chunk_text)
|
| 218 |
-
if content:
|
| 219 |
-
complete_response += content
|
| 220 |
-
|
| 221 |
-
return complete_response
|
| 222 |
|
| 223 |
-
except
|
| 224 |
print(f"Error in chat request: {e}")
|
| 225 |
-
|
|
|
|
|
|
|
| 226 |
return None
|
| 227 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 228 |
if __name__ == "__main__":
|
| 229 |
uvicorn.run(app, host="0.0.0.0", port=PORT)
|
|
|
|
| 12 |
# Configuration
|
| 13 |
API_CHALLENGE_URL = 'https://api.eqing.tech/api/altcaptcha/challenge'
|
| 14 |
NEXTWAY_CHAT_URL = 'https://origin.eqing.tech/api/openai/v1/chat/completions'
|
| 15 |
+
CREDENTIAL_EXPIRY_MARGIN = 60 * 1000
|
| 16 |
PORT = 7860
|
| 17 |
API_ENDPOINT = '/v1/chat/completions'
|
| 18 |
MODEL_NAME = "gpt-4o-free"
|
| 19 |
+
REQUEST_TIMEOUT = 480
|
| 20 |
MAX_RETRIES = 3
|
| 21 |
+
RETRY_DELAY = 1
|
| 22 |
|
| 23 |
# Global variables
|
| 24 |
current_credential = None
|
| 25 |
credential_expiry = None
|
| 26 |
is_refreshing_credential = False
|
| 27 |
|
|
|
|
| 28 |
MODEL_MAPPING = {
|
| 29 |
'gpt-4o-all-lite': 'gpt-4o-mini',
|
| 30 |
'gpt-4o-image': 'gpt-4o-mini-image-free',
|
|
|
|
| 44 |
top_p: Optional[float] = 1
|
| 45 |
max_tokens: Optional[int] = 4000
|
| 46 |
|
| 47 |
+
async def extract_streaming_content(response):
|
| 48 |
+
buffer = ""
|
| 49 |
+
complete_response = ""
|
| 50 |
+
async for chunk in response.content:
|
| 51 |
+
buffer += chunk.decode()
|
| 52 |
+
lines = buffer.split('\n')
|
| 53 |
+
|
| 54 |
+
# Process complete lines
|
| 55 |
+
for line in lines[:-1]:
|
| 56 |
+
line = line.strip()
|
| 57 |
+
if line.startswith('data: '):
|
| 58 |
+
content = process_data_line(line[5:].strip())
|
| 59 |
+
if content:
|
| 60 |
+
complete_response += content
|
| 61 |
+
|
| 62 |
+
# Keep the last incomplete line in buffer
|
| 63 |
+
buffer = lines[-1] if lines else ""
|
| 64 |
+
|
| 65 |
+
# Process any remaining data
|
| 66 |
+
if buffer:
|
| 67 |
+
line = buffer.strip()
|
| 68 |
+
if line.startswith('data: '):
|
| 69 |
+
content = process_data_line(line[5:].strip())
|
| 70 |
+
if content:
|
| 71 |
+
complete_response += content
|
| 72 |
+
|
| 73 |
+
return complete_response
|
| 74 |
|
| 75 |
+
def process_data_line(data_str: str) -> str:
|
| 76 |
+
if not data_str or data_str in ['[ORIGIN]', '[DONE]']:
|
| 77 |
+
return ''
|
| 78 |
+
|
| 79 |
+
try:
|
| 80 |
+
json_data = json.loads(data_str)
|
| 81 |
+
if (json_data.get('choices') and
|
| 82 |
+
json_data['choices'][0].get('delta') and
|
| 83 |
+
'content' in json_data['choices'][0]['delta']):
|
| 84 |
+
return json_data['choices'][0]['delta']['content']
|
| 85 |
+
except json.JSONDecodeError:
|
| 86 |
+
print(f'Invalid JSON data: {data_str}')
|
| 87 |
+
return ''
|
| 88 |
|
| 89 |
async def solve_challenge(challenge: str, salt: str, algorithm: str = "SHA-512", max_number: int = 1000000):
|
| 90 |
start_time = time.time()
|
|
|
|
| 169 |
|
| 170 |
return current_credential
|
| 171 |
|
| 172 |
+
async def handle_chat_request(model: str, messages: List[Dict[str, str]], retries=0):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
captcha_token = await get_credential()
|
| 174 |
if not captcha_token:
|
| 175 |
return None
|
|
|
|
| 191 |
async with session.post(
|
| 192 |
NEXTWAY_CHAT_URL,
|
| 193 |
json=body,
|
| 194 |
+
timeout=aiohttp.ClientTimeout(total=REQUEST_TIMEOUT)
|
| 195 |
) as response:
|
| 196 |
if response.status != 200:
|
| 197 |
+
if retries < MAX_RETRIES:
|
| 198 |
+
await asyncio.sleep(RETRY_DELAY)
|
| 199 |
+
return await handle_chat_request(model, messages, retries + 1)
|
| 200 |
return None
|
| 201 |
|
| 202 |
+
return await extract_streaming_content(response)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
+
except (aiohttp.ClientError, asyncio.TimeoutError) as e:
|
| 205 |
print(f"Error in chat request: {e}")
|
| 206 |
+
if retries < MAX_RETRIES:
|
| 207 |
+
await asyncio.sleep(RETRY_DELAY)
|
| 208 |
+
return await handle_chat_request(model, messages, retries + 1)
|
| 209 |
return None
|
| 210 |
|
| 211 |
+
@app.post(API_ENDPOINT)
|
| 212 |
+
async def chat_endpoint(request: ChatRequest):
|
| 213 |
+
try:
|
| 214 |
+
model = MODEL_MAPPING.get(request.model, request.model or MODEL_NAME)
|
| 215 |
+
response_content = await handle_chat_request(model, request.messages)
|
| 216 |
+
|
| 217 |
+
if response_content is None:
|
| 218 |
+
return Response(
|
| 219 |
+
content="Failed to get response from API",
|
| 220 |
+
status_code=500
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
return {
|
| 224 |
+
"choices": [{
|
| 225 |
+
"message": {
|
| 226 |
+
"role": "assistant",
|
| 227 |
+
"content": response_content.strip()
|
| 228 |
+
},
|
| 229 |
+
"finish_reason": "stop",
|
| 230 |
+
"index": 0
|
| 231 |
+
}],
|
| 232 |
+
"model": model,
|
| 233 |
+
"object": "chat.completion"
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
except Exception as e:
|
| 237 |
+
print(f"Error handling chat request: {e}")
|
| 238 |
+
return Response(content="Internal server error", status_code=500)
|
| 239 |
+
|
| 240 |
if __name__ == "__main__":
|
| 241 |
uvicorn.run(app, host="0.0.0.0", port=PORT)
|