Zydit1 / app.py
Norsec93's picture
Update app.py
44d902f verified
Raw History Blame Contribute Delete
4.61 kB
from fastapi import FastAPI, Request, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from curl_cffi import requests
import os
app = FastAPI()
# Enable cross-origin resource sharing for Janitor AI requests
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Target endpoint for Zydit V1 Catalog Models
ZYDIT_V1_URL = 'https://api.zydit.in/v1/chat/completions'
# Map Janitor incoming models straight to GLM 5.1
MODEL_MAPPING = {
'gpt-4': 'z-ai/glm5.1',
'gpt-4o': 'z-ai/glm5.1',
'gpt-3.5-turbo': 'z-ai/glm5.1'
}
@app.get("/{path:path}")
async def health_check(path: str):
return {"status": "alive", "message": "Clean Browser-Masked Shield Active."}
@app.post("/{path:path}")
async def proxy_post(path: str, request: Request):
try:
body = await request.json()
except Exception:
return {"status": "alive", "message": "Ping received."}
if "messages" not in body:
return {"status": "alive", "message": "Connection baseline stable."}
api_key = os.environ.get("ZYDIT_LIVE_KEY", "").strip()
if not api_key:
raise HTTPException(status_code=500, detail="Secret Configuration Error: ZYDIT_LIVE_KEY is missing.")
inbound_model = body.get("model", "gpt-4")
target_model = MODEL_MAPPING.get(inbound_model, "z-ai/glm5.1")
# --- Janitor Payload Sanitization ---
sanitized_messages = []
combined_system_content = ""
for msg in body.get("messages", []):
role = msg.get("role")
if role in ['example_user', 'user']:
role = 'user'
elif role in ['example_assistant', 'assistant']:
role = 'assistant'
content = msg.get("content", "")
if isinstance(content, str):
content = content.strip()
else:
content = ""
if not content:
continue
if role == 'system':
combined_system_content += ("\n" + content if combined_system_content else content)
elif role in ['user', 'assistant']:
# Squash consecutive identical roles to prevent parsing rejections
if sanitized_messages and sanitized_messages[-1]['role'] == role:
sanitized_messages[-1]['content'] += "\n" + content
else:
sanitized_messages.append({"role": role, "content": content})
if combined_system_content:
sanitized_messages.insert(0, {"role": "system", "content": combined_system_content})
# Reassemble standardized OpenAI format body
pristine_body = {
"model": target_model,
"messages": sanitized_messages,
"stream": body.get("stream", True)
}
if "temperature" in body and isinstance(body["temperature"], (int, float)):
pristine_body["temperature"] = body["temperature"]
if "top_p" in body and isinstance(body["top_p"], (int, float)):
pristine_body["top_p"] = body["top_p"]
if "max_tokens" in body and isinstance(body["max_tokens"], int):
pristine_body["max_tokens"] = body["max_tokens"]
print(f"[Python Proxy] Attempting handshake with V1 Route...")
try:
# TLS fingerprint emulation via curl_cffi
response = requests.post(
ZYDIT_V1_URL,
json=pristine_body,
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
},
impersonate="chrome110",
stream=True,
timeout=60.0
)
# Catch rejections and output the response stream details to logs
if response.status_code != 200:
print(f"[Upstream Rejection] Status Code Caught: {response.status_code}")
print(f"[Upstream Body Sniffer]: {response.text[:1200]}")
raise HTTPException(
status_code=response.status_code,
detail=f"Zydit rejected request with status {response.status_code}. Check Space logs."
)
def generate_stream():
for chunk in response.iter_content(chunk_size=1024):
if chunk:
yield chunk
return StreamingResponse(generate_stream(), media_type=response.headers.get("content-type", "text/event-stream"))
except HTTPException:
raise
except Exception as e:
print(f"[Proxy Exception]: {str(e)}")
raise HTTPException(status_code=500, detail=f"Internal proxy network drop: {str(e)}")