Spaces:
Sleeping
Sleeping
Create backend/routes_ai.py
Browse files- backend/routes_ai.py +80 -0
backend/routes_ai.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import re
|
| 4 |
+
import httpx
|
| 5 |
+
import subprocess
|
| 6 |
+
from fastapi import APIRouter
|
| 7 |
+
|
| 8 |
+
router = APIRouter()
|
| 9 |
+
|
| 10 |
+
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "")
|
| 11 |
+
API_URL = "https://" + "openrouter.ai/api/v1/chat/completions"
|
| 12 |
+
REFERER_URL = "https://" + "huggingface.co/"
|
| 13 |
+
|
| 14 |
+
@router.post("/api/ai_edit")
|
| 15 |
+
async def ai_edit(data: dict):
|
| 16 |
+
prompt, content = data.get("prompt"), data.get("content")
|
| 17 |
+
messages = [
|
| 18 |
+
{"role": "system", "content": "You are an expert coder. Rewrite the provided code based on the user's request. Output ONLY the raw updated code. Do not use markdown blocks like ```python. No conversational text."},
|
| 19 |
+
{"role": "user", "content": f"Current Code:\n{content}\n\nRequest: {prompt}"}
|
| 20 |
+
]
|
| 21 |
+
payload = {"model": "openrouter/auto", "messages": messages}
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}", "HTTP-Referer": REFERER_URL}
|
| 25 |
+
async with httpx.AsyncClient(trust_env=False) as client:
|
| 26 |
+
res = await client.post(API_URL, headers=headers, json=payload, timeout=60.0)
|
| 27 |
+
if res.status_code != 200:
|
| 28 |
+
return {"code": f"# API_ERROR: {res.text}"}
|
| 29 |
+
new_code = res.json()['choices'][0]['message']['content']
|
| 30 |
+
except Exception as httpx_err:
|
| 31 |
+
try:
|
| 32 |
+
cmd = [
|
| 33 |
+
"curl", "--noproxy", "*", "-s", "-X", "POST", API_URL,
|
| 34 |
+
"-H", f"Authorization: Bearer {OPENROUTER_API_KEY}",
|
| 35 |
+
"-H", "Content-Type: application/json",
|
| 36 |
+
"-H", f"HTTP-Referer: {REFERER_URL}",
|
| 37 |
+
"-d", json.dumps(payload)
|
| 38 |
+
]
|
| 39 |
+
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
|
| 40 |
+
if result.returncode != 0:
|
| 41 |
+
return {"code": f"# CURL_NETWORK_ERROR: {result.stderr}\n# HTTPX_ERROR: {str(httpx_err)}"}
|
| 42 |
+
res_json = json.loads(result.stdout)
|
| 43 |
+
new_code = res_json['choices'][0]['message']['content']
|
| 44 |
+
except Exception as curl_err:
|
| 45 |
+
return {"code": f"# FATAL_NETWORK_ERROR. HTTPX: {str(httpx_err)} | CURL: {str(curl_err)}"}
|
| 46 |
+
|
| 47 |
+
new_code = re.sub(r"^```[a-z]*\n", "", new_code)
|
| 48 |
+
new_code = re.sub(r"\n```$", "", new_code)
|
| 49 |
+
return {"code": new_code.strip()}
|
| 50 |
+
|
| 51 |
+
async def ask_openrouter(messages) -> str:
|
| 52 |
+
if not OPENROUTER_API_KEY:
|
| 53 |
+
return "API_ERROR: OPENROUTER_API_KEY is not set in Spaces Secrets."
|
| 54 |
+
data = {"model": "openrouter/auto", "messages": messages}
|
| 55 |
+
try:
|
| 56 |
+
headers = {"Authorization": f"Bearer {OPENROUTER_API_KEY}", "HTTP-Referer": REFERER_URL}
|
| 57 |
+
async with httpx.AsyncClient(trust_env=False) as client:
|
| 58 |
+
response = await client.post(API_URL, headers=headers, json=data, timeout=45.0)
|
| 59 |
+
if response.status_code != 200: return f"API_ERROR: {response.text}"
|
| 60 |
+
return response.json()['choices'][0]['message']['content']
|
| 61 |
+
except Exception as e:
|
| 62 |
+
httpx_error = str(e)
|
| 63 |
+
try:
|
| 64 |
+
cmd = [
|
| 65 |
+
"curl", "--noproxy", "*", "-s", "-X", "POST", API_URL,
|
| 66 |
+
"-H", f"Authorization: Bearer {OPENROUTER_API_KEY}",
|
| 67 |
+
"-H", "Content-Type: application/json",
|
| 68 |
+
"-H", f"HTTP-Referer: {REFERER_URL}",
|
| 69 |
+
"-d", json.dumps(data)
|
| 70 |
+
]
|
| 71 |
+
result = subprocess.run(cmd, capture_output=True, text=True, timeout=45)
|
| 72 |
+
if result.returncode != 0:
|
| 73 |
+
return f"CURL_NETWORK_ERROR: {result.stderr}\nHTTPX_ERROR: {httpx_error}"
|
| 74 |
+
res_json = json.loads(result.stdout)
|
| 75 |
+
if "error" in res_json:
|
| 76 |
+
return f"API_ERROR: {json.dumps(res_json['error'])}"
|
| 77 |
+
return res_json['choices'][0]['message']['content']
|
| 78 |
+
except Exception as curl_e:
|
| 79 |
+
return f"FATAL_NETWORK_ERROR\nHTTPX Error: {httpx_error}\nCURL Error: {str(curl_e)}"
|
| 80 |
+
|