Upload 13 files
Browse files- .github/workflows/docker-deploy.yml +1 -1
- api/app.py +41 -50
- api/config.py +255 -44
- api/logger.py +54 -14
- api/models.py +14 -14
- api/utils.py +227 -136
- requirements.txt +6 -6
.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:v12 # 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
|
api/app.py
CHANGED
@@ -1,50 +1,41 @@
|
|
1 |
-
from fastapi import FastAPI,
|
2 |
-
from
|
3 |
-
from
|
4 |
-
from api.
|
5 |
-
from api.
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
app = FastAPI(
|
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 |
-
# Health check endpoints
|
43 |
-
@app.get("/")
|
44 |
-
@app.get("/healthz")
|
45 |
-
@app.get("/ready")
|
46 |
-
@app.get("/alive")
|
47 |
-
@app.get("/status")
|
48 |
-
@app.get("/health")
|
49 |
-
def health_check(request: Request):
|
50 |
-
return Response(content='{"status": "ok"}', media_type="application/json")
|
|
|
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/config.py
CHANGED
@@ -1,44 +1,255 @@
|
|
1 |
-
import os
|
2 |
-
from dotenv import load_dotenv
|
3 |
-
|
4 |
-
load_dotenv()
|
5 |
-
|
6 |
-
# Base URL and Common Headers
|
7 |
-
BASE_URL = "https://
|
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 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
'PythonAgent': '@Python Agent',
|
212 |
+
'JavaAgent': '@Java Agent',
|
213 |
+
'JavaScriptAgent': '@JavaScript Agent',
|
214 |
+
'HTMLAgent': '@HTML Agent',
|
215 |
+
'GoogleCloudAgent': '@Google Cloud Agent',
|
216 |
+
'AndroidDeveloper': '@Android Developer',
|
217 |
+
'SwiftDeveloper': '@Swift Developer',
|
218 |
+
'Next.jsAgent': '@Next.js Agent',
|
219 |
+
'MongoDBAgent': '@MongoDB Agent',
|
220 |
+
'PyTorchAgent': '@PyTorch Agent',
|
221 |
+
'ReactAgent': '@React Agent',
|
222 |
+
'XcodeAgent': '@Xcode Agent',
|
223 |
+
'AngularJSAgent': '@AngularJS Agent',
|
224 |
+
'HerokuAgent': '@Heroku Agent',
|
225 |
+
'GodotAgent': '@Godot Agent',
|
226 |
+
'GoAgent': '@Go Agent',
|
227 |
+
'GitlabAgent': '@Gitlab Agent',
|
228 |
+
'GitAgent': '@Gitlab Agent',
|
229 |
+
'blackboxai-pro': '@BLACKBOXAI-PRO',
|
230 |
+
'flux': '@Image Generation',
|
231 |
+
# Add any additional prefixes if necessary
|
232 |
+
|
233 |
+
# Added New Agents
|
234 |
+
'FlaskAgent': '@Flask Agent',
|
235 |
+
'FirebaseAgent': '@Firebase Agent',
|
236 |
+
'FastAPIAgent': '@FastAPI Agent',
|
237 |
+
'ErlangAgent': '@Erlang Agent',
|
238 |
+
'ElectronAgent': '@Electron Agent',
|
239 |
+
'DockerAgent': '@Docker Agent',
|
240 |
+
'DigitalOceanAgent': '@DigitalOcean Agent',
|
241 |
+
'BitbucketAgent': '@Bitbucket Agent',
|
242 |
+
'AzureAgent': '@Azure Agent',
|
243 |
+
'FlutterAgent': '@Flutter Agent',
|
244 |
+
'YoutubeAgent': '@Youtube Agent',
|
245 |
+
'builderAgent': '@builder Agent',
|
246 |
+
}
|
247 |
+
|
248 |
+
# Model referers
|
249 |
+
MODEL_REFERERS = {
|
250 |
+
"blackboxai": "/?model=blackboxai",
|
251 |
+
"gpt-4o": "/?model=gpt-4o",
|
252 |
+
"gemini-pro": "/?model=gemini-pro",
|
253 |
+
"claude-sonnet-3.5": "/?model=claude-sonnet-3.5",
|
254 |
+
# Add any additional referers if necessary
|
255 |
+
}
|
api/logger.py
CHANGED
@@ -1,14 +1,54 @@
|
|
1 |
-
import logging
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
CHANGED
@@ -1,14 +1,14 @@
|
|
1 |
-
from typing import List
|
2 |
-
from pydantic import BaseModel
|
3 |
-
|
4 |
-
class Message(BaseModel):
|
5 |
-
role: str
|
6 |
-
content: str
|
7 |
-
|
8 |
-
class ChatRequest(BaseModel):
|
9 |
-
model: str
|
10 |
-
messages: List[Message]
|
11 |
-
stream: bool = False
|
12 |
-
temperature: float = 0.5
|
13 |
-
top_p: float = 0.9
|
14 |
-
max_tokens: int =
|
|
|
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/utils.py
CHANGED
@@ -1,136 +1,227 @@
|
|
1 |
-
import
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
from
|
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 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from datetime import datetime
|
2 |
+
import json
|
3 |
+
import uuid
|
4 |
+
import asyncio
|
5 |
+
import random
|
6 |
+
import string
|
7 |
+
from typing import Any, Dict, Optional
|
8 |
+
|
9 |
+
import httpx
|
10 |
+
from fastapi import HTTPException
|
11 |
+
from api.config import (
|
12 |
+
MODEL_MAPPING,
|
13 |
+
get_headers_api_chat,
|
14 |
+
get_headers_chat,
|
15 |
+
BASE_URL,
|
16 |
+
AGENT_MODE,
|
17 |
+
TRENDING_AGENT_MODE,
|
18 |
+
MODEL_PREFIXES,
|
19 |
+
MODEL_REFERERS
|
20 |
+
)
|
21 |
+
from api.models import ChatRequest
|
22 |
+
from api.logger import setup_logger
|
23 |
+
|
24 |
+
logger = setup_logger(__name__)
|
25 |
+
|
26 |
+
# Helper function to create a random alphanumeric chat ID
|
27 |
+
def generate_chat_id(length: int = 7) -> str:
|
28 |
+
characters = string.ascii_letters + string.digits
|
29 |
+
return ''.join(random.choices(characters, k=length))
|
30 |
+
|
31 |
+
# Helper function to create chat completion data
|
32 |
+
def create_chat_completion_data(
|
33 |
+
content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
|
34 |
+
) -> Dict[str, Any]:
|
35 |
+
return {
|
36 |
+
"id": f"chatcmpl-{uuid.uuid4()}",
|
37 |
+
"object": "chat.completion.chunk",
|
38 |
+
"created": timestamp,
|
39 |
+
"model": model,
|
40 |
+
"choices": [
|
41 |
+
{
|
42 |
+
"index": 0,
|
43 |
+
"delta": {"content": content, "role": "assistant"},
|
44 |
+
"finish_reason": finish_reason,
|
45 |
+
}
|
46 |
+
],
|
47 |
+
"usage": None,
|
48 |
+
}
|
49 |
+
|
50 |
+
# Function to convert message to dictionary format, ensuring base64 data and optional model prefix
|
51 |
+
def message_to_dict(message, model_prefix: Optional[str] = None):
|
52 |
+
content = message.content if isinstance(message.content, str) else message.content[0]["text"]
|
53 |
+
if model_prefix:
|
54 |
+
content = f"{model_prefix} {content}"
|
55 |
+
if isinstance(message.content, list) and len(message.content) == 2 and "image_url" in message.content[1]:
|
56 |
+
# Ensure base64 images are always included for all models
|
57 |
+
return {
|
58 |
+
"role": message.role,
|
59 |
+
"content": content,
|
60 |
+
"data": {
|
61 |
+
"imageBase64": message.content[1]["image_url"]["url"],
|
62 |
+
"fileText": "",
|
63 |
+
"title": "snapshot",
|
64 |
+
},
|
65 |
+
}
|
66 |
+
return {"role": message.role, "content": content}
|
67 |
+
|
68 |
+
# Function to strip model prefix from content if present
|
69 |
+
def strip_model_prefix(content: str, model_prefix: Optional[str] = None) -> str:
|
70 |
+
"""Remove the model prefix from the response content if present."""
|
71 |
+
if model_prefix and content.startswith(model_prefix):
|
72 |
+
logger.debug(f"Stripping prefix '{model_prefix}' from content.")
|
73 |
+
return content[len(model_prefix):].strip()
|
74 |
+
return content
|
75 |
+
|
76 |
+
# Function to get the correct referer URL for logging
|
77 |
+
def get_referer_url(chat_id: str, model: str) -> str:
|
78 |
+
"""Generate the referer URL based on specific models listed in MODEL_REFERERS."""
|
79 |
+
if model in MODEL_REFERERS:
|
80 |
+
return f"{BASE_URL}/chat/{chat_id}?model={model}"
|
81 |
+
return BASE_URL
|
82 |
+
|
83 |
+
# Process streaming response with headers from config.py
|
84 |
+
async def process_streaming_response(request: ChatRequest):
|
85 |
+
chat_id = generate_chat_id()
|
86 |
+
referer_url = get_referer_url(chat_id, request.model)
|
87 |
+
logger.info(f"Generated Chat ID: {chat_id} - Model: {request.model} - URL: {referer_url}")
|
88 |
+
|
89 |
+
agent_mode = AGENT_MODE.get(request.model, {})
|
90 |
+
trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
|
91 |
+
model_prefix = MODEL_PREFIXES.get(request.model, "")
|
92 |
+
|
93 |
+
headers_api_chat = get_headers_api_chat(referer_url)
|
94 |
+
|
95 |
+
if request.model == 'o1-preview':
|
96 |
+
delay_seconds = random.randint(1, 60)
|
97 |
+
logger.info(f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview' (Chat ID: {chat_id})")
|
98 |
+
await asyncio.sleep(delay_seconds)
|
99 |
+
|
100 |
+
json_data = {
|
101 |
+
"agentMode": agent_mode,
|
102 |
+
"clickedAnswer2": False,
|
103 |
+
"clickedAnswer3": False,
|
104 |
+
"clickedForceWebSearch": False,
|
105 |
+
"codeModelMode": True,
|
106 |
+
"githubToken": None,
|
107 |
+
"id": chat_id,
|
108 |
+
"isChromeExt": False,
|
109 |
+
"isMicMode": False,
|
110 |
+
"maxTokens": request.max_tokens,
|
111 |
+
"messages": [message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages],
|
112 |
+
"mobileClient": False,
|
113 |
+
"playgroundTemperature": request.temperature,
|
114 |
+
"playgroundTopP": request.top_p,
|
115 |
+
"previewToken": None,
|
116 |
+
"trendingAgentMode": trending_agent_mode,
|
117 |
+
"userId": None,
|
118 |
+
"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
|
119 |
+
"userSystemPrompt": None,
|
120 |
+
"validated": "00f37b34-a166-4efb-bce5-1312d87f2f94",
|
121 |
+
"visitFromDelta": False,
|
122 |
+
}
|
123 |
+
|
124 |
+
async with httpx.AsyncClient() as client:
|
125 |
+
try:
|
126 |
+
async with client.stream(
|
127 |
+
"POST",
|
128 |
+
f"{BASE_URL}/api/chat",
|
129 |
+
headers=headers_api_chat,
|
130 |
+
json=json_data,
|
131 |
+
timeout=100,
|
132 |
+
) as response:
|
133 |
+
response.raise_for_status()
|
134 |
+
async for line in response.aiter_lines():
|
135 |
+
timestamp = int(datetime.now().timestamp())
|
136 |
+
if line:
|
137 |
+
content = line
|
138 |
+
if content.startswith("$@$v=undefined-rv1$@$"):
|
139 |
+
content = content[21:]
|
140 |
+
cleaned_content = strip_model_prefix(content, model_prefix)
|
141 |
+
yield f"data: {json.dumps(create_chat_completion_data(cleaned_content, request.model, timestamp))}\n\n"
|
142 |
+
|
143 |
+
yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
|
144 |
+
yield "data: [DONE]\n\n"
|
145 |
+
except httpx.HTTPStatusError as e:
|
146 |
+
logger.error(f"HTTP error occurred for Chat ID {chat_id}: {e}")
|
147 |
+
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
148 |
+
except httpx.RequestError as e:
|
149 |
+
logger.error(f"Error occurred during request for Chat ID {chat_id}: {e}")
|
150 |
+
raise HTTPException(status_code=500, detail=str(e))
|
151 |
+
|
152 |
+
# Process non-streaming response with headers from config.py
|
153 |
+
async def process_non_streaming_response(request: ChatRequest):
|
154 |
+
chat_id = generate_chat_id()
|
155 |
+
referer_url = get_referer_url(chat_id, request.model)
|
156 |
+
logger.info(f"Generated Chat ID: {chat_id} - Model: {request.model} - URL: {referer_url}")
|
157 |
+
|
158 |
+
agent_mode = AGENT_MODE.get(request.model, {})
|
159 |
+
trending_agent_mode = TRENDING_AGENT_MODE.get(request.model, {})
|
160 |
+
model_prefix = MODEL_PREFIXES.get(request.model, "")
|
161 |
+
|
162 |
+
headers_api_chat = get_headers_api_chat(referer_url)
|
163 |
+
headers_chat = get_headers_chat(referer_url, next_action=str(uuid.uuid4()), next_router_state_tree=json.dumps([""]))
|
164 |
+
|
165 |
+
if request.model == 'o1-preview':
|
166 |
+
delay_seconds = random.randint(20, 60)
|
167 |
+
logger.info(f"Introducing a delay of {delay_seconds} seconds for model 'o1-preview' (Chat ID: {chat_id})")
|
168 |
+
await asyncio.sleep(delay_seconds)
|
169 |
+
|
170 |
+
json_data = {
|
171 |
+
"agentMode": agent_mode,
|
172 |
+
"clickedAnswer2": False,
|
173 |
+
"clickedAnswer3": False,
|
174 |
+
"clickedForceWebSearch": False,
|
175 |
+
"codeModelMode": True,
|
176 |
+
"githubToken": None,
|
177 |
+
"id": chat_id,
|
178 |
+
"isChromeExt": False,
|
179 |
+
"isMicMode": False,
|
180 |
+
"maxTokens": request.max_tokens,
|
181 |
+
"messages": [message_to_dict(msg, model_prefix=model_prefix) for msg in request.messages],
|
182 |
+
"mobileClient": False,
|
183 |
+
"playgroundTemperature": request.temperature,
|
184 |
+
"playgroundTopP": request.top_p,
|
185 |
+
"previewToken": None,
|
186 |
+
"trendingAgentMode": trending_agent_mode,
|
187 |
+
"userId": None,
|
188 |
+
"userSelectedModel": MODEL_MAPPING.get(request.model, request.model),
|
189 |
+
"userSystemPrompt": None,
|
190 |
+
"validated": "00f37b34-a166-4efb-bce5-1312d87f2f94",
|
191 |
+
"visitFromDelta": False,
|
192 |
+
}
|
193 |
+
|
194 |
+
full_response = ""
|
195 |
+
async with httpx.AsyncClient() as client:
|
196 |
+
try:
|
197 |
+
async with client.stream(
|
198 |
+
method="POST", url=f"{BASE_URL}/api/chat", headers=headers_api_chat, json=json_data
|
199 |
+
) as response:
|
200 |
+
response.raise_for_status()
|
201 |
+
async for chunk in response.aiter_text():
|
202 |
+
full_response += chunk
|
203 |
+
except httpx.HTTPStatusError as e:
|
204 |
+
logger.error(f"HTTP error occurred for Chat ID {chat_id}: {e}")
|
205 |
+
raise HTTPException(status_code=e.response.status_code, detail=str(e))
|
206 |
+
except httpx.RequestError as e:
|
207 |
+
logger.error(f"Error occurred during request for Chat ID {chat_id}: {e}")
|
208 |
+
raise HTTPException(status_code=500, detail=str(e))
|
209 |
+
if full_response.startswith("$@$v=undefined-rv1$@$"):
|
210 |
+
full_response = full_response[21:]
|
211 |
+
|
212 |
+
cleaned_full_response = strip_model_prefix(full_response, model_prefix)
|
213 |
+
|
214 |
+
return {
|
215 |
+
"id": f"chatcmpl-{uuid.uuid4()}",
|
216 |
+
"object": "chat.completion",
|
217 |
+
"created": int(datetime.now().timestamp()),
|
218 |
+
"model": request.model,
|
219 |
+
"choices": [
|
220 |
+
{
|
221 |
+
"index": 0,
|
222 |
+
"message": {"role": "assistant", "content": cleaned_full_response},
|
223 |
+
"finish_reason": "stop",
|
224 |
+
}
|
225 |
+
],
|
226 |
+
"usage": None,
|
227 |
+
}
|
requirements.txt
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
-
fastapi==0.95.2
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
|
|
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
|
6 |
+
gunicorn==20.1.0
|