Upload 15 files
Browse files- .dockerignore +4 -3
- .github/workflows/docker-deploy.yml +1 -1
- Dockerfile +20 -8
- api/__init__.py +0 -0
- api/__pycache__/dummy.txt +1 -0
- api/app.py +41 -0
- api/auth.py +10 -0
- api/config.py +256 -0
- api/logger.py +54 -0
- api/models.py +14 -0
- api/routes.py +59 -0
- api/utils.py +233 -0
- api/validate.py +70 -0
- requirements.txt +5 -8
.dockerignore
CHANGED
@@ -2,8 +2,9 @@ __pycache__
|
|
2 |
*.pyc
|
3 |
*.pyo
|
4 |
*.pyd
|
5 |
-
*.
|
6 |
-
*.
|
7 |
-
*.log
|
8 |
.env
|
9 |
.git
|
|
|
|
|
|
2 |
*.pyc
|
3 |
*.pyo
|
4 |
*.pyd
|
5 |
+
*.db
|
6 |
+
*.sqlite3
|
|
|
7 |
.env
|
8 |
.git
|
9 |
+
.gitignore
|
10 |
+
Dockerfile
|
.github/workflows/docker-deploy.yml
CHANGED
@@ -36,7 +36,7 @@ jobs:
|
|
36 |
with:
|
37 |
context: . # The context is the root of your repository
|
38 |
push: true # Automatically push the image after building
|
39 |
-
tags: ${{ secrets.DOCKER_USERNAME }}/blackboxv2:
|
40 |
|
41 |
# Step 5: Log out of Docker Hub
|
42 |
- name: Log out of Docker Hub
|
|
|
36 |
with:
|
37 |
context: . # The context is the root of your repository
|
38 |
push: true # Automatically push the image after building
|
39 |
+
tags: ${{ secrets.DOCKER_USERNAME }}/blackboxv2:v7 # Replace 'your-app-name' with your desired Docker image name
|
40 |
|
41 |
# Step 5: Log out of Docker Hub
|
42 |
- name: Log out of Docker Hub
|
Dockerfile
CHANGED
@@ -1,17 +1,29 @@
|
|
1 |
-
# Use official Python image
|
2 |
FROM python:3.10-slim
|
3 |
|
4 |
-
# Set
|
|
|
|
|
|
|
|
|
5 |
WORKDIR /app
|
6 |
|
7 |
-
#
|
8 |
-
|
|
|
|
|
|
|
|
|
9 |
|
10 |
-
# Install dependencies
|
|
|
11 |
RUN pip install --no-cache-dir -r requirements.txt
|
12 |
|
13 |
-
#
|
|
|
|
|
|
|
14 |
EXPOSE 8001
|
15 |
|
16 |
-
# Command to run the FastAPI app with
|
17 |
-
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8001"]
|
|
|
1 |
+
# Use the official Python 3.10 slim image
|
2 |
FROM python:3.10-slim
|
3 |
|
4 |
+
# Set environment variables to prevent Python from writing pyc files and to buffer stdout/stderr
|
5 |
+
ENV PYTHONDONTWRITEBYTECODE=1
|
6 |
+
ENV PYTHONUNBUFFERED=1
|
7 |
+
|
8 |
+
# Set the working directory to /app
|
9 |
WORKDIR /app
|
10 |
|
11 |
+
# Install system dependencies (if any)
|
12 |
+
# For example, if you need gcc for some packages, uncomment the following line
|
13 |
+
# RUN apt-get update && apt-get install -y gcc
|
14 |
+
|
15 |
+
# Copy only the requirements.txt first to leverage Docker cache
|
16 |
+
COPY requirements.txt .
|
17 |
|
18 |
+
# Install Python dependencies
|
19 |
+
RUN pip install --no-cache-dir --upgrade pip
|
20 |
RUN pip install --no-cache-dir -r requirements.txt
|
21 |
|
22 |
+
# Copy the rest of the application code
|
23 |
+
COPY . .
|
24 |
+
|
25 |
+
# Expose port 8001 to the outside world
|
26 |
EXPOSE 8001
|
27 |
|
28 |
+
# Command to run the FastAPI app with Uvicorn
|
29 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8001"]
|
api/__init__.py
ADDED
File without changes
|
api/__pycache__/dummy.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
|
api/app.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, Request
|
2 |
+
from starlette.middleware.cors import CORSMiddleware
|
3 |
+
from fastapi.responses import JSONResponse
|
4 |
+
from api.logger import setup_logger
|
5 |
+
from api.routes import router
|
6 |
+
|
7 |
+
|
8 |
+
logger = setup_logger(__name__)
|
9 |
+
|
10 |
+
def create_app():
|
11 |
+
app = FastAPI(
|
12 |
+
title="NiansuhAI API Gateway",
|
13 |
+
docs_url=None, # Disable Swagger UI
|
14 |
+
redoc_url=None, # Disable ReDoc
|
15 |
+
openapi_url=None, # Disable OpenAPI schema
|
16 |
+
)
|
17 |
+
|
18 |
+
# CORS settings
|
19 |
+
app.add_middleware(
|
20 |
+
CORSMiddleware,
|
21 |
+
allow_origins=["*"], # Adjust as needed for security
|
22 |
+
allow_credentials=True,
|
23 |
+
allow_methods=["*"],
|
24 |
+
allow_headers=["*"],
|
25 |
+
)
|
26 |
+
|
27 |
+
# Include routes
|
28 |
+
app.include_router(router)
|
29 |
+
|
30 |
+
# Global exception handler for better error reporting
|
31 |
+
@app.exception_handler(Exception)
|
32 |
+
async def global_exception_handler(request: Request, exc: Exception):
|
33 |
+
logger.error(f"An error occurred: {str(exc)}")
|
34 |
+
return JSONResponse(
|
35 |
+
status_code=500,
|
36 |
+
content={"message": "An internal server error occurred."},
|
37 |
+
)
|
38 |
+
|
39 |
+
return app
|
40 |
+
|
41 |
+
app = create_app()
|
api/auth.py
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import Depends, HTTPException
|
2 |
+
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
3 |
+
from api.config import APP_SECRET
|
4 |
+
|
5 |
+
security = HTTPBearer()
|
6 |
+
|
7 |
+
def verify_app_secret(credentials: HTTPAuthorizationCredentials = Depends(security)):
|
8 |
+
if credentials.credentials != APP_SECRET:
|
9 |
+
raise HTTPException(status_code=403, detail="Invalid APP_SECRET")
|
10 |
+
return credentials.credentials
|
api/config.py
ADDED
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from dotenv import load_dotenv
|
3 |
+
|
4 |
+
load_dotenv()
|
5 |
+
|
6 |
+
# Base URL and Common Headers
|
7 |
+
BASE_URL = "https://www.blackbox.ai"
|
8 |
+
common_headers = {
|
9 |
+
'accept': '*/*',
|
10 |
+
'accept-language': 'en-US,en;q=0.9',
|
11 |
+
'cache-control': 'no-cache',
|
12 |
+
'origin': BASE_URL,
|
13 |
+
'pragma': 'no-cache',
|
14 |
+
'priority': 'u=1, i',
|
15 |
+
'sec-ch-ua': '"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"',
|
16 |
+
'sec-ch-ua-mobile': '?0',
|
17 |
+
'sec-ch-ua-platform': '"Windows"',
|
18 |
+
'sec-fetch-dest': 'empty',
|
19 |
+
'sec-fetch-mode': 'cors',
|
20 |
+
'sec-fetch-site': 'same-origin',
|
21 |
+
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
|
22 |
+
'AppleWebKit/537.36 (KHTML, like Gecko) '
|
23 |
+
'Chrome/130.0.0.0 Safari/537.36',
|
24 |
+
}
|
25 |
+
|
26 |
+
# Header Configurations for Specific API Calls
|
27 |
+
def get_headers_api_chat(referer_url):
|
28 |
+
return {**common_headers, 'Content-Type': 'application/json', 'Referer': referer_url}
|
29 |
+
|
30 |
+
def get_headers_chat(chat_url, next_action, next_router_state_tree):
|
31 |
+
return {
|
32 |
+
**common_headers,
|
33 |
+
'Accept': 'text/x-component',
|
34 |
+
'Content-Type': 'text/plain;charset=UTF-8',
|
35 |
+
'Referer': chat_url,
|
36 |
+
'next-action': next_action,
|
37 |
+
'next-router-state-tree': next_router_state_tree,
|
38 |
+
'next-url': '/',
|
39 |
+
}
|
40 |
+
|
41 |
+
APP_SECRET = os.getenv("APP_SECRET")
|
42 |
+
|
43 |
+
ALLOWED_MODELS = [
|
44 |
+
{"id": "blackboxai", "name": "blackboxai"},
|
45 |
+
{"id": "blackboxai-pro", "name": "blackboxai-pro"},
|
46 |
+
{"id": "flux", "name": "flux"},
|
47 |
+
{"id": "llama-3.1-8b", "name": "llama-3.1-8b"},
|
48 |
+
{"id": "llama-3.1-70b", "name": "llama-3.1-70b"},
|
49 |
+
{"id": "llama-3.1-405b", "name": "llama-3.1-405"},
|
50 |
+
{"id": "gpt-4o", "name": "gpt-4o"},
|
51 |
+
{"id": "gemini-pro", "name": "gemini-pro"},
|
52 |
+
{"id": "gemini-1.5-flash", "name": "gemini-1.5-flash"},
|
53 |
+
{"id": "claude-sonnet-3.5", "name": "claude-sonnet-3.5"},
|
54 |
+
{"id": "PythonAgent", "name": "PythonAgent"},
|
55 |
+
{"id": "JavaAgent", "name": "JavaAgent"},
|
56 |
+
{"id": "JavaScriptAgent", "name": "JavaScriptAgent"},
|
57 |
+
{"id": "HTMLAgent", "name": "HTMLAgent"},
|
58 |
+
{"id": "GoogleCloudAgent", "name": "GoogleCloudAgent"},
|
59 |
+
{"id": "AndroidDeveloper", "name": "AndroidDeveloper"},
|
60 |
+
{"id": "SwiftDeveloper", "name": "SwiftDeveloper"},
|
61 |
+
{"id": "Next.jsAgent", "name": "Next.jsAgent"},
|
62 |
+
{"id": "MongoDBAgent", "name": "MongoDBAgent"},
|
63 |
+
{"id": "PyTorchAgent", "name": "PyTorchAgent"},
|
64 |
+
{"id": "ReactAgent", "name": "ReactAgent"},
|
65 |
+
{"id": "XcodeAgent", "name": "XcodeAgent"},
|
66 |
+
{"id": "AngularJSAgent", "name": "AngularJSAgent"},
|
67 |
+
{"id": "HerokuAgent", "name": "HerokuAgent"},
|
68 |
+
{"id": "GodotAgent", "name": "GodotAgent"},
|
69 |
+
{"id": "GoAgent", "name": "GoAgent"},
|
70 |
+
{"id": "GitlabAgent", "name": "GitlabAgent"},
|
71 |
+
{"id": "GitAgent", "name": "GitAgent"},
|
72 |
+
{"id": "RepoMap", "name": "RepoMap"},
|
73 |
+
{"id": "gemini-1.5-pro-latest", "name": "gemini-pro"},
|
74 |
+
{"id": "gemini-1.5-pro", "name": "gemini-1.5-pro"},
|
75 |
+
{"id": "claude-3-5-sonnet-20240620", "name": "claude-sonnet-3.5"},
|
76 |
+
{"id": "claude-3-5-sonnet", "name": "claude-sonnet-3.5"},
|
77 |
+
{"id": "Niansuh", "name": "Niansuh"},
|
78 |
+
{"id": "o1-preview", "name": "o1-preview"},
|
79 |
+
{"id": "claude-3-5-sonnet-20241022", "name": "claude-3-5-sonnet-20241022"},
|
80 |
+
{"id": "claude-3-5-sonnet-x", "name": "claude-3-5-sonnet-x"},
|
81 |
+
|
82 |
+
# Added New Agents
|
83 |
+
{"id": "FlaskAgent", "name": "FlaskAgent"},
|
84 |
+
{"id": "FirebaseAgent", "name": "FirebaseAgent"},
|
85 |
+
{"id": "FastAPIAgent", "name": "FastAPIAgent"},
|
86 |
+
{"id": "ErlangAgent", "name": "ErlangAgent"},
|
87 |
+
{"id": "ElectronAgent", "name": "ElectronAgent"},
|
88 |
+
{"id": "DockerAgent", "name": "DockerAgent"},
|
89 |
+
{"id": "DigitalOceanAgent", "name": "DigitalOceanAgent"},
|
90 |
+
{"id": "BitbucketAgent", "name": "BitbucketAgent"},
|
91 |
+
{"id": "AzureAgent", "name": "AzureAgent"},
|
92 |
+
{"id": "FlutterAgent", "name": "FlutterAgent"},
|
93 |
+
{"id": "YoutubeAgent", "name": "YoutubeAgent"},
|
94 |
+
{"id": "builderAgent", "name": "builderAgent"},
|
95 |
+
]
|
96 |
+
|
97 |
+
MODEL_MAPPING = {
|
98 |
+
"blackboxai": "blackboxai",
|
99 |
+
"blackboxai-pro": "blackboxai-pro",
|
100 |
+
"flux": "flux",
|
101 |
+
"ImageGeneration": "flux",
|
102 |
+
"llama-3.1-8b": "llama-3.1-8b",
|
103 |
+
"llama-3.1-70b": "llama-3.1-70b",
|
104 |
+
"llama-3.1-405b": "llama-3.1-405",
|
105 |
+
"gpt-4o": "gpt-4o",
|
106 |
+
"gemini-pro": "gemini-pro",
|
107 |
+
"gemini-1.5-flash": "gemini-1.5-flash",
|
108 |
+
"claude-sonnet-3.5": "claude-sonnet-3.5",
|
109 |
+
"PythonAgent": "PythonAgent",
|
110 |
+
"JavaAgent": "JavaAgent",
|
111 |
+
"JavaScriptAgent": "JavaScriptAgent",
|
112 |
+
"HTMLAgent": "HTMLAgent",
|
113 |
+
"GoogleCloudAgent": "GoogleCloudAgent",
|
114 |
+
"AndroidDeveloper": "AndroidDeveloper",
|
115 |
+
"SwiftDeveloper": "SwiftDeveloper",
|
116 |
+
"Next.jsAgent": "Next.jsAgent",
|
117 |
+
"MongoDBAgent": "MongoDBAgent",
|
118 |
+
"PyTorchAgent": "PyTorchAgent",
|
119 |
+
"ReactAgent": "ReactAgent",
|
120 |
+
"XcodeAgent": "XcodeAgent",
|
121 |
+
"AngularJSAgent": "AngularJSAgent",
|
122 |
+
"HerokuAgent": "HerokuAgent",
|
123 |
+
"GodotAgent": "GodotAgent",
|
124 |
+
"GoAgent": "GoAgent",
|
125 |
+
"GitlabAgent": "GitlabAgent",
|
126 |
+
"GitAgent": "GitAgent",
|
127 |
+
"RepoMap": "RepoMap",
|
128 |
+
# Additional mappings
|
129 |
+
"gemini-flash": "gemini-1.5-flash",
|
130 |
+
"claude-3.5-sonnet": "claude-sonnet-3.5",
|
131 |
+
"flux": "flux",
|
132 |
+
"gemini-1.5-pro-latest": "gemini-pro",
|
133 |
+
"gemini-1.5-pro": "gemini-1.5-pro",
|
134 |
+
"claude-3-5-sonnet-20240620": "claude-sonnet-3.5",
|
135 |
+
"claude-3-5-sonnet": "claude-sonnet-3.5",
|
136 |
+
"Niansuh": "Niansuh",
|
137 |
+
"o1-preview": "o1-preview",
|
138 |
+
"claude-3-5-sonnet-20241022": "claude-3-5-sonnet-20241022",
|
139 |
+
"claude-3-5-sonnet-x": "claude-3-5-sonnet-x",
|
140 |
+
|
141 |
+
# Added New Agents
|
142 |
+
"FlaskAgent": "FlaskAgent",
|
143 |
+
"FirebaseAgent": "FirebaseAgent",
|
144 |
+
"FastAPIAgent": "FastAPIAgent",
|
145 |
+
"ErlangAgent": "ErlangAgent",
|
146 |
+
"ElectronAgent": "ElectronAgent",
|
147 |
+
"DockerAgent": "DockerAgent",
|
148 |
+
"DigitalOceanAgent": "DigitalOceanAgent",
|
149 |
+
"BitbucketAgent": "BitbucketAgent",
|
150 |
+
"AzureAgent": "AzureAgent",
|
151 |
+
"FlutterAgent": "FlutterAgent",
|
152 |
+
"YoutubeAgent": "YoutubeAgent",
|
153 |
+
"builderAgent": "builderAgent",
|
154 |
+
}
|
155 |
+
|
156 |
+
# Agent modes
|
157 |
+
AGENT_MODE = {
|
158 |
+
'flux': {'mode': True, 'id': "ImageGenerationLV45LJp", 'name': "flux"},
|
159 |
+
'Niansuh': {'mode': True, 'id': "NiansuhAIk1HgESy", 'name': "Niansuh"},
|
160 |
+
'o1-preview': {'mode': True, 'id': "o1Dst8La8", 'name': "o1-preview"},
|
161 |
+
'claude-3-5-sonnet-20241022': {'mode': True, 'id': "Claude-Sonnet-3.5zO2HZSF", 'name': "claude-3-5-sonnet-20241022"},
|
162 |
+
'claude-3-5-sonnet-x': {'mode': True, 'id': "Claude-Sonnet-3.52022JE0UdQ3", 'name': "claude-3-5-sonnet-x"},
|
163 |
+
}
|
164 |
+
|
165 |
+
TRENDING_AGENT_MODE = {
|
166 |
+
"blackboxai": {},
|
167 |
+
"gemini-1.5-flash": {'mode': True, 'id': 'Gemini'},
|
168 |
+
"llama-3.1-8b": {'mode': True, 'id': "llama-3.1-8b"},
|
169 |
+
'llama-3.1-70b': {'mode': True, 'id': "llama-3.1-70b"},
|
170 |
+
'llama-3.1-405b': {'mode': True, 'id': "llama-3.1-405"},
|
171 |
+
'blackboxai-pro': {'mode': True, 'id': "BLACKBOXAI-PRO"},
|
172 |
+
'PythonAgent': {'mode': True, 'id': "Python Agent"},
|
173 |
+
'JavaAgent': {'mode': True, 'id': "Java Agent"},
|
174 |
+
'JavaScriptAgent': {'mode': True, 'id': "JavaScript Agent"},
|
175 |
+
'HTMLAgent': {'mode': True, 'id': "HTML Agent"},
|
176 |
+
'GoogleCloudAgent': {'mode': True, 'id': "Google Cloud Agent"},
|
177 |
+
'AndroidDeveloper': {'mode': True, 'id': "Android Developer"},
|
178 |
+
'SwiftDeveloper': {'mode': True, 'id': "Swift Developer"},
|
179 |
+
'Next.jsAgent': {'mode': True, 'id': "Next.js Agent"},
|
180 |
+
'MongoDBAgent': {'mode': True, 'id': "MongoDB Agent"},
|
181 |
+
'PyTorchAgent': {'mode': True, 'id': "PyTorch Agent"},
|
182 |
+
'ReactAgent': {'mode': True, 'id': "React Agent"},
|
183 |
+
'XcodeAgent': {'mode': True, 'id': "Xcode Agent"},
|
184 |
+
'AngularJSAgent': {'mode': True, 'id': "AngularJS Agent"},
|
185 |
+
'HerokuAgent': {'mode': True, 'id': "HerokuAgent"},
|
186 |
+
'GodotAgent': {'mode': True, 'id': "GodotAgent"},
|
187 |
+
'GoAgent': {'mode': True, 'id': "GoAgent"},
|
188 |
+
'GitlabAgent': {'mode': True, 'id': "GitlabAgent"},
|
189 |
+
'GitAgent': {'mode': True, 'id': "GitAgent"},
|
190 |
+
'RepoMap': {'mode': True, 'id': "repomap"},
|
191 |
+
|
192 |
+
# Added New Agents
|
193 |
+
'FlaskAgent': {'mode': True, 'id': "FlaskAgent"},
|
194 |
+
'FirebaseAgent': {'mode': True, 'id': "FirebaseAgent"},
|
195 |
+
'FastAPIAgent': {'mode': True, 'id': "FastAPIAgent"},
|
196 |
+
'ErlangAgent': {'mode': True, 'id': "ErlangAgent"},
|
197 |
+
'ElectronAgent': {'mode': True, 'id': "ElectronAgent"},
|
198 |
+
'DockerAgent': {'mode': True, 'id': "DockerAgent"},
|
199 |
+
'DigitalOceanAgent': {'mode': True, 'id': "DigitalOceanAgent"},
|
200 |
+
'BitbucketAgent': {'mode': True, 'id': "BitbucketAgent"},
|
201 |
+
'AzureAgent': {'mode': True, 'id': "AzureAgent"},
|
202 |
+
'FlutterAgent': {'mode': True, 'id': "FlutterAgent"},
|
203 |
+
'YoutubeAgent': {'mode': True, 'id': "YoutubeAgent"},
|
204 |
+
'builderAgent': {'mode': True, 'id': "builderAgent"},
|
205 |
+
}
|
206 |
+
|
207 |
+
# Model prefixes
|
208 |
+
MODEL_PREFIXES = {
|
209 |
+
'gpt-4o': '@GPT-4o',
|
210 |
+
'gemini-pro': '@Gemini-PRO',
|
211 |
+
'claude-sonnet-3.5': '@Claude-Sonnet-3.5',
|
212 |
+
'PythonAgent': '@Python Agent',
|
213 |
+
'JavaAgent': '@Java Agent',
|
214 |
+
'JavaScriptAgent': '@JavaScript Agent',
|
215 |
+
'HTMLAgent': '@HTML Agent',
|
216 |
+
'GoogleCloudAgent': '@Google Cloud Agent',
|
217 |
+
'AndroidDeveloper': '@Android Developer',
|
218 |
+
'SwiftDeveloper': '@Swift Developer',
|
219 |
+
'Next.jsAgent': '@Next.js Agent',
|
220 |
+
'MongoDBAgent': '@MongoDB Agent',
|
221 |
+
'PyTorchAgent': '@PyTorch Agent',
|
222 |
+
'ReactAgent': '@React Agent',
|
223 |
+
'XcodeAgent': '@Xcode Agent',
|
224 |
+
'AngularJSAgent': '@AngularJS Agent',
|
225 |
+
'HerokuAgent': '@Heroku Agent',
|
226 |
+
'GodotAgent': '@Godot Agent',
|
227 |
+
'GoAgent': '@Go Agent',
|
228 |
+
'GitlabAgent': '@Gitlab Agent',
|
229 |
+
'GitAgent': '@Gitlab Agent',
|
230 |
+
'blackboxai-pro': '@BLACKBOXAI-PRO',
|
231 |
+
'flux': '@Image Generation',
|
232 |
+
# Add any additional prefixes if necessary
|
233 |
+
|
234 |
+
# Added New Agents
|
235 |
+
'FlaskAgent': '@Flask Agent',
|
236 |
+
'FirebaseAgent': '@Firebase Agent',
|
237 |
+
'FastAPIAgent': '@FastAPI Agent',
|
238 |
+
'ErlangAgent': '@Erlang Agent',
|
239 |
+
'ElectronAgent': '@Electron Agent',
|
240 |
+
'DockerAgent': '@Docker Agent',
|
241 |
+
'DigitalOceanAgent': '@DigitalOcean Agent',
|
242 |
+
'BitbucketAgent': '@Bitbucket Agent',
|
243 |
+
'AzureAgent': '@Azure Agent',
|
244 |
+
'FlutterAgent': '@Flutter Agent',
|
245 |
+
'YoutubeAgent': '@Youtube Agent',
|
246 |
+
'builderAgent': '@builder Agent',
|
247 |
+
}
|
248 |
+
|
249 |
+
# Model referers
|
250 |
+
MODEL_REFERERS = {
|
251 |
+
"blackboxai": "/?model=blackboxai",
|
252 |
+
"gpt-4o": "/?model=gpt-4o",
|
253 |
+
"gemini-pro": "/?model=gemini-pro",
|
254 |
+
"claude-sonnet-3.5": "/?model=claude-sonnet-3.5",
|
255 |
+
# Add any additional referers if necessary
|
256 |
+
}
|
api/logger.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
|
3 |
+
# Setup logger with a consistent format
|
4 |
+
def setup_logger(name):
|
5 |
+
logger = logging.getLogger(name)
|
6 |
+
if not logger.handlers:
|
7 |
+
logger.setLevel(logging.INFO)
|
8 |
+
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
9 |
+
|
10 |
+
# Console handler
|
11 |
+
console_handler = logging.StreamHandler()
|
12 |
+
console_handler.setFormatter(formatter)
|
13 |
+
logger.addHandler(console_handler)
|
14 |
+
|
15 |
+
# File Handler - Error Level
|
16 |
+
# error_file_handler = logging.FileHandler('error.log')
|
17 |
+
# error_file_handler.setFormatter(formatter)
|
18 |
+
# error_file_handler.setLevel(logging.ERROR)
|
19 |
+
# logger.addHandler(error_file_handler)
|
20 |
+
|
21 |
+
return logger
|
22 |
+
|
23 |
+
logger = setup_logger(__name__)
|
24 |
+
|
25 |
+
# Log functions to structure specific logs in utils.py
|
26 |
+
def log_generated_chat_id_with_referer(chat_id, model, referer_url):
|
27 |
+
"""
|
28 |
+
Log the generated Chat ID with model and referer URL if it exists.
|
29 |
+
"""
|
30 |
+
logger.info(f"Generated Chat ID: {chat_id} - Model: {model} - URL: {referer_url}")
|
31 |
+
|
32 |
+
def log_model_delay(delay_seconds, model, chat_id):
|
33 |
+
"""
|
34 |
+
Log the delay introduced for specific models.
|
35 |
+
"""
|
36 |
+
logger.info(f"Introducing a delay of {delay_seconds} seconds for model '{model}' (Chat ID: {chat_id})")
|
37 |
+
|
38 |
+
def log_http_error(error, chat_id):
|
39 |
+
"""
|
40 |
+
Log HTTP errors encountered during requests.
|
41 |
+
"""
|
42 |
+
logger.error(f"HTTP error occurred for Chat ID {chat_id}: {error}")
|
43 |
+
|
44 |
+
def log_request_error(error, chat_id):
|
45 |
+
"""
|
46 |
+
Log request errors unrelated to HTTP status.
|
47 |
+
"""
|
48 |
+
logger.error(f"Request error occurred for Chat ID {chat_id}: {error}")
|
49 |
+
|
50 |
+
def log_strip_prefix(model_prefix, content):
|
51 |
+
"""
|
52 |
+
Log when a model prefix is stripped from the content.
|
53 |
+
"""
|
54 |
+
logger.debug(f"Stripping prefix '{model_prefix}' from content.")
|
api/models.py
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import List, Optional
|
2 |
+
from pydantic import BaseModel
|
3 |
+
|
4 |
+
class Message(BaseModel):
|
5 |
+
role: str
|
6 |
+
content: str | list
|
7 |
+
|
8 |
+
class ChatRequest(BaseModel):
|
9 |
+
model: str
|
10 |
+
messages: List[Message]
|
11 |
+
stream: Optional[bool] = False
|
12 |
+
temperature: Optional[float] = 0.5
|
13 |
+
top_p: Optional[float] = 0.9
|
14 |
+
max_tokens: Optional[int] = 99999999
|
api/routes.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
3 |
+
from fastapi.responses import StreamingResponse
|
4 |
+
from api.auth import verify_app_secret
|
5 |
+
from api.config import ALLOWED_MODELS
|
6 |
+
from api.models import ChatRequest
|
7 |
+
from api.utils import process_non_streaming_response, process_streaming_response
|
8 |
+
from api.logger import setup_logger
|
9 |
+
|
10 |
+
logger = setup_logger(__name__)
|
11 |
+
|
12 |
+
router = APIRouter()
|
13 |
+
|
14 |
+
@router.options("/v1/chat/completions")
|
15 |
+
@router.options("/api/v1/chat/completions")
|
16 |
+
async def chat_completions_options():
|
17 |
+
return Response(
|
18 |
+
status_code=200,
|
19 |
+
headers={
|
20 |
+
"Access-Control-Allow-Origin": "*",
|
21 |
+
"Access-Control-Allow-Methods": "POST, OPTIONS",
|
22 |
+
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
23 |
+
},
|
24 |
+
)
|
25 |
+
|
26 |
+
@router.get("/v1/models")
|
27 |
+
@router.get("/api/v1/models")
|
28 |
+
async def list_models():
|
29 |
+
return {"object": "list", "data": ALLOWED_MODELS}
|
30 |
+
|
31 |
+
@router.post("/v1/chat/completions")
|
32 |
+
@router.post("/api/v1/chat/completions")
|
33 |
+
async def chat_completions(
|
34 |
+
request: ChatRequest, app_secret: str = Depends(verify_app_secret)
|
35 |
+
):
|
36 |
+
logger.info("Entering chat_completions route")
|
37 |
+
logger.info(f"Processing chat completion request for model: {request.model}")
|
38 |
+
|
39 |
+
if request.model not in [model["id"] for model in ALLOWED_MODELS]:
|
40 |
+
raise HTTPException(
|
41 |
+
status_code=400,
|
42 |
+
detail=f"Model {request.model} is not allowed. Allowed models are: {', '.join(model['id'] for model in ALLOWED_MODELS)}",
|
43 |
+
)
|
44 |
+
|
45 |
+
if request.stream:
|
46 |
+
logger.info("Streaming response")
|
47 |
+
return StreamingResponse(process_streaming_response(request), media_type="text/event-stream")
|
48 |
+
else:
|
49 |
+
logger.info("Non-streaming response")
|
50 |
+
return await process_non_streaming_response(request)
|
51 |
+
|
52 |
+
@router.route('/')
|
53 |
+
@router.route('/healthz')
|
54 |
+
@router.route('/ready')
|
55 |
+
@router.route('/alive')
|
56 |
+
@router.route('/status')
|
57 |
+
@router.get("/health")
|
58 |
+
def health_check(request: Request):
|
59 |
+
return Response(content=json.dumps({"status": "ok"}), media_type="application/json")
|
api/utils.py
ADDED
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# main.py or your main application file
|
2 |
+
|
3 |
+
from datetime import datetime
|
4 |
+
import json
|
5 |
+
import uuid
|
6 |
+
import asyncio
|
7 |
+
import random
|
8 |
+
import string
|
9 |
+
from typing import Any, Dict, Optional
|
10 |
+
|
11 |
+
import httpx
|
12 |
+
from fastapi import HTTPException
|
13 |
+
from api.config import (
|
14 |
+
MODEL_MAPPING,
|
15 |
+
get_headers_api_chat,
|
16 |
+
get_headers_chat,
|
17 |
+
BASE_URL,
|
18 |
+
AGENT_MODE,
|
19 |
+
TRENDING_AGENT_MODE,
|
20 |
+
MODEL_PREFIXES,
|
21 |
+
MODEL_REFERERS
|
22 |
+
)
|
23 |
+
from api.models import ChatRequest
|
24 |
+
from api.logger import setup_logger
|
25 |
+
from api.validate import getHid # Import the asynchronous getHid function
|
26 |
+
|
27 |
+
logger = setup_logger(__name__)
|
28 |
+
|
29 |
+
# Helper function to create chat completion data
|
30 |
+
def create_chat_completion_data(
|
31 |
+
content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
|
32 |
+
) -> Dict[str, Any]:
|
33 |
+
return {
|
34 |
+
"id": f"chatcmpl-{uuid.uuid4()}",
|
35 |
+
"object": "chat.completion.chunk",
|
36 |
+
"created": timestamp,
|
37 |
+
"model": model,
|
38 |
+
"choices": [
|
39 |
+
{
|
40 |
+
"index": 0,
|
41 |
+
"delta": {"content": content, "role": "assistant"},
|
42 |
+
"finish_reason": finish_reason,
|
43 |
+
}
|
44 |
+
],
|
45 |
+
"usage": None,
|
46 |
+
}
|
47 |
+
|
48 |
+
# Function to convert message to dictionary format, ensuring base64 data and optional model prefix
|
49 |
+
def message_to_dict(message, model_prefix: Optional[str] = None):
|
50 |
+
content = message.content if isinstance(message.content, str) else message.content[0]["text"]
|
51 |
+
if model_prefix:
|
52 |
+
content = f"{model_prefix} {content}"
|
53 |
+
if isinstance(message.content, list) and len(message.content) == 2 and "image_url" in message.content[1]:
|
54 |
+
# Ensure base64 images are always included for all models
|
55 |
+
return {
|
56 |
+
"role": message.role,
|
57 |
+
"content": content,
|
58 |
+
"data": {
|
59 |
+
"imageBase64": message.content[1]["image_url"]["url"],
|
60 |
+
"fileText": "",
|
61 |
+
"title": "snapshot",
|
62 |
+
},
|
63 |
+
}
|
64 |
+
return {"role": message.role, "content": content}
|
65 |
+
|
66 |
+
# Function to strip model prefix from content if present
|
67 |
+
def strip_model_prefix(content: str, model_prefix: Optional[str] = None) -> str:
|
68 |
+
"""Remove the model prefix from the response content if present."""
|
69 |
+
if model_prefix and content.startswith(model_prefix):
|
70 |
+
logger.debug(f"Stripping prefix '{model_prefix}' from content.")
|
71 |
+
return content[len(model_prefix):].strip()
|
72 |
+
return content
|
73 |
+
|
74 |
+
# Process streaming response with headers from config.py
|
75 |
+
async def process_streaming_response(request: ChatRequest):
|
76 |
+
# Generate a unique ID for this request
|
77 |
+
request_id = f"chatcmpl-{uuid.uuid4()}"
|
78 |
+
logger.info(f"Processing request with ID: {request_id} - Model: {request.model}")
|
79 |
+
|
80 |
+
agent_mode = AGENT_MODE.get(request.model, {})
|
81 |
+
trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
|
82 |
+
model_prefix = MODEL_PREFIXES.get(request.model, "")
|
83 |
+
|
84 |
+
# Adjust headers_api_chat since referer_url is removed
|
85 |
+
headers_api_chat = get_headers_api_chat(BASE_URL)
|
86 |
+
|
87 |
+
if request.model == 'o1-preview':
|
88 |
+
delay_seconds = random.randint(1, 60)
|
89 |
+
logger.info(f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview' (Request ID: {request_id})")
|
90 |
+
await asyncio.sleep(delay_seconds)
|
91 |
+
|
92 |
+
# Fetch the h-value for the 'validated' field
|
93 |
+
h_value = await getHid()
|
94 |
+
if not h_value:
|
95 |
+
logger.error("Failed to retrieve h-value for validation.")
|
96 |
+
raise HTTPException(status_code=500, detail="Validation failed due to missing h-value.")
|
97 |
+
|
98 |
+
json_data = {
|
99 |
+
"agentMode": agent_mode,
|
100 |
+
"clickedAnswer2": False,
|
101 |
+
"clickedAnswer3": False,
|
102 |
+
"clickedForceWebSearch": False,
|
103 |
+
"codeModelMode": True,
|
104 |
+
"githubToken": None,
|
105 |
+
"id": None, # Using request_id instead of chat_id
|
106 |
+
"isChromeExt": False,
|
107 |
+
"isMicMode": False,
|
108 |
+
"maxTokens": request.max_tokens,
|
109 |
+
"messages": [message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages],
|
110 |
+
"mobileClient": False,
|
111 |
+
"playgroundTemperature": request.temperature,
|
112 |
+
"playgroundTopP": request.top_p,
|
113 |
+
"previewToken": None,
|
114 |
+
"trendingAgentMode": trending_agent_mode,
|
115 |
+
"userId": None,
|
116 |
+
"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
|
117 |
+
"userSystemPrompt": None,
|
118 |
+
"validated": h_value, # Dynamically set the validated field
|
119 |
+
"visitFromDelta": False,
|
120 |
+
}
|
121 |
+
|
122 |
+
async with httpx.AsyncClient() as client:
|
123 |
+
try:
|
124 |
+
async with client.stream(
|
125 |
+
"POST",
|
126 |
+
f"{BASE_URL}/api/chat",
|
127 |
+
headers=headers_api_chat,
|
128 |
+
json=json_data,
|
129 |
+
timeout=100,
|
130 |
+
) as response:
|
131 |
+
response.raise_for_status()
|
132 |
+
async for line in response.aiter_lines():
|
133 |
+
timestamp = int(datetime.now().timestamp())
|
134 |
+
if line:
|
135 |
+
content = line
|
136 |
+
if content.startswith("$@$v=undefined-rv1$@$"):
|
137 |
+
content = content[21:]
|
138 |
+
cleaned_content = strip_model_prefix(content, model_prefix)
|
139 |
+
yield f"data: {json.dumps(create_chat_completion_data(cleaned_content, request.model, timestamp))}\n\n"
|
140 |
+
|
141 |
+
yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
|
142 |
+
yield "data: [DONE]\n\n"
|
143 |
+
except httpx.HTTPStatusError as e:
|
144 |
+
logger.error(f"HTTP error occurred for Request ID {request_id}: {e}")
|
145 |
+
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
146 |
+
except httpx.RequestError as e:
|
147 |
+
logger.error(f"Error occurred during request for Request ID {request_id}: {e}")
|
148 |
+
raise HTTPException(status_code=500, detail=str(e))
|
149 |
+
|
150 |
+
# Process non-streaming response with headers from config.py
|
151 |
+
async def process_non_streaming_response(request: ChatRequest):
|
152 |
+
# Generate a unique ID for this request
|
153 |
+
request_id = f"chatcmpl-{uuid.uuid4()}"
|
154 |
+
logger.info(f"Processing request with ID: {request_id} - Model: {request.model}")
|
155 |
+
|
156 |
+
agent_mode = AGENT_MODE.get(request.model, {})
|
157 |
+
trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
|
158 |
+
model_prefix = MODEL_PREFIXES.get(request.model, "")
|
159 |
+
|
160 |
+
# Adjust headers_api_chat and headers_chat since referer_url is removed
|
161 |
+
headers_api_chat = get_headers_api_chat(BASE_URL)
|
162 |
+
headers_chat = get_headers_chat(BASE_URL, next_action=str(uuid.uuid4()), next_router_state_tree=json.dumps([""]))
|
163 |
+
|
164 |
+
if request.model == 'o1-preview':
|
165 |
+
delay_seconds = random.randint(20, 60)
|
166 |
+
logger.info(f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview' (Request ID: {request_id})")
|
167 |
+
await asyncio.sleep(delay_seconds)
|
168 |
+
|
169 |
+
# Fetch the h-value for the 'validated' field
|
170 |
+
h_value = await getHid()
|
171 |
+
if not h_value:
|
172 |
+
logger.error("Failed to retrieve h-value for validation.")
|
173 |
+
raise HTTPException(status_code=500, detail="Validation failed due to missing h-value.")
|
174 |
+
|
175 |
+
json_data = {
|
176 |
+
"agentMode": agent_mode,
|
177 |
+
"clickedAnswer2": False,
|
178 |
+
"clickedAnswer3": False,
|
179 |
+
"clickedForceWebSearch": False,
|
180 |
+
"codeModelMode": True,
|
181 |
+
"githubToken": None,
|
182 |
+
"id": None, # Using request_id instead of chat_id
|
183 |
+
"isChromeExt": False,
|
184 |
+
"isMicMode": False,
|
185 |
+
"maxTokens": request.max_tokens,
|
186 |
+
"messages": [message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages],
|
187 |
+
"mobileClient": False,
|
188 |
+
"playgroundTemperature": request.temperature,
|
189 |
+
"playgroundTopP": request.top_p,
|
190 |
+
"previewToken": None,
|
191 |
+
"trendingAgentMode": trending_agent_mode,
|
192 |
+
"userId": None,
|
193 |
+
"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
|
194 |
+
"userSystemPrompt": None,
|
195 |
+
"validated": h_value, # Dynamically set the validated field
|
196 |
+
"visitFromDelta": False,
|
197 |
+
}
|
198 |
+
|
199 |
+
full_response = ""
|
200 |
+
async with httpx.AsyncClient() as client:
|
201 |
+
try:
|
202 |
+
async with client.stream(
|
203 |
+
method="POST", url=f"{BASE_URL}/api/chat", headers=headers_api_chat, json=json_data
|
204 |
+
) as response:
|
205 |
+
response.raise_for_status()
|
206 |
+
async for chunk in response.aiter_text():
|
207 |
+
full_response += chunk
|
208 |
+
except httpx.HTTPStatusError as e:
|
209 |
+
logger.error(f"HTTP error occurred for Request ID {request_id}: {e}")
|
210 |
+
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
211 |
+
except httpx.RequestError as e:
|
212 |
+
logger.error(f"Error occurred during request for Request ID {request_id}: {e}")
|
213 |
+
raise HTTPException(status_code=500, detail=str(e))
|
214 |
+
|
215 |
+
if full_response.startswith("$@$v=undefined-rv1$@$"):
|
216 |
+
full_response = full_response[21:]
|
217 |
+
|
218 |
+
cleaned_full_response = strip_model_prefix(full_response, model_prefix)
|
219 |
+
|
220 |
+
return {
|
221 |
+
"id": f"chatcmpl-{uuid.uuid4()}",
|
222 |
+
"object": "chat.completion",
|
223 |
+
"created": int(datetime.now().timestamp()),
|
224 |
+
"model": request.model,
|
225 |
+
"choices": [
|
226 |
+
{
|
227 |
+
"index": 0,
|
228 |
+
"message": {"role": "assistant", "content": cleaned_full_response},
|
229 |
+
"finish_reason": "stop",
|
230 |
+
}
|
231 |
+
],
|
232 |
+
"usage": None,
|
233 |
+
}
|
api/validate.py
ADDED
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# api/validate.py
|
2 |
+
|
3 |
+
import re
|
4 |
+
import time
|
5 |
+
import asyncio
|
6 |
+
import httpx
|
7 |
+
from typing import Optional # Added import for Optional
|
8 |
+
|
9 |
+
base_url = "https://www.blackbox.ai"
|
10 |
+
headers = {
|
11 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
|
12 |
+
}
|
13 |
+
|
14 |
+
# Cache variables
|
15 |
+
cached_hid = None
|
16 |
+
cache_time = 0
|
17 |
+
CACHE_DURATION = 36000 # Cache duration in seconds (10 hours)
|
18 |
+
|
19 |
+
async def getHid(force_refresh: bool = False) -> Optional[str]:
|
20 |
+
global cached_hid, cache_time
|
21 |
+
current_time = time.time()
|
22 |
+
|
23 |
+
# Check if a forced refresh is needed or if the cached values are still valid.
|
24 |
+
if not force_refresh and cached_hid and (current_time - cache_time) < CACHE_DURATION:
|
25 |
+
print("Using cached_hid:", cached_hid)
|
26 |
+
return cached_hid
|
27 |
+
|
28 |
+
try:
|
29 |
+
async with httpx.AsyncClient() as client:
|
30 |
+
# Retrieve the initial HTML content.
|
31 |
+
response = await client.get(base_url, headers=headers)
|
32 |
+
response.raise_for_status()
|
33 |
+
content = response.text
|
34 |
+
|
35 |
+
# Use a regular expression to find specific `static/chunks` paths.
|
36 |
+
pattern = r"static/chunks/app/layout-[a-zA-Z0-9]+\.js"
|
37 |
+
match = re.search(pattern, content)
|
38 |
+
|
39 |
+
if match:
|
40 |
+
# Construct the full URL of the JS file.
|
41 |
+
js_path = match.group()
|
42 |
+
full_url = f"{base_url}/_next/{js_path}"
|
43 |
+
|
44 |
+
# Request the content of the JS file.
|
45 |
+
js_response = await client.get(full_url, headers=headers)
|
46 |
+
js_response.raise_for_status()
|
47 |
+
|
48 |
+
# In JS content, use a regular expression to search for h-value.
|
49 |
+
h_pattern = r'h="([0-9a-f-]+)"'
|
50 |
+
h_match = re.search(h_pattern, js_response.text)
|
51 |
+
|
52 |
+
if h_match:
|
53 |
+
h_value = h_match.group(1)
|
54 |
+
print("Found the h-value:", h_value)
|
55 |
+
# Update the cache.
|
56 |
+
cached_hid = h_value
|
57 |
+
cache_time = current_time
|
58 |
+
return h_value
|
59 |
+
else:
|
60 |
+
print("The h-value was not found in the JS content.")
|
61 |
+
return None
|
62 |
+
else:
|
63 |
+
print("The specified JS file path was not found in the HTML content.")
|
64 |
+
return None
|
65 |
+
except httpx.RequestError as e:
|
66 |
+
print(f"An error occurred during the request: {e}")
|
67 |
+
return None
|
68 |
+
except httpx.HTTPStatusError as e:
|
69 |
+
print(f"HTTP error occurred: {e}")
|
70 |
+
return None
|
requirements.txt
CHANGED
@@ -1,8 +1,5 @@
|
|
1 |
-
fastapi
|
2 |
-
httpx
|
3 |
-
pydantic
|
4 |
-
|
5 |
-
|
6 |
-
Requests
|
7 |
-
starlette
|
8 |
-
uvicorn
|
|
|
1 |
+
fastapi==0.95.2
|
2 |
+
httpx==0.23.3
|
3 |
+
pydantic==1.10.4
|
4 |
+
python-dotenv==0.21.0
|
5 |
+
uvicorn==0.21.1
|
|
|
|
|
|