Niansuh commited on
Commit
32a532b
·
verified ·
1 Parent(s): 6c37ac6

Upload 13 files

Browse files
Files changed (9) hide show
  1. .github/workflows/docker-deploy.yml +1 -1
  2. Dockerfile +1 -1
  3. api/app.py +41 -43
  4. api/auth.py +10 -12
  5. api/config.py +249 -89
  6. api/logger.py +54 -54
  7. api/models.py +14 -19
  8. api/routes.py +59 -61
  9. api/utils.py +227 -258
.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:v1 # 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
 
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:v4 # 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
@@ -23,4 +23,4 @@ COPY . /app
23
  EXPOSE 8001
24
 
25
  # Command to run the app with Gunicorn and Uvicorn workers
26
- CMD ["gunicorn", "-k", "uvicorn.workers.UvicornWorker", "--workers", "4", "--bind", "0.0.0.0:8001", "main:app"]
 
23
  EXPOSE 8001
24
 
25
  # Command to run the app with Gunicorn and Uvicorn workers
26
+ CMD ["gunicorn", "-k", "uvicorn.workers.UvicornWorker", "--workers", "8", "--bind", "0.0.0.0:8001", "main:app"]
api/app.py CHANGED
@@ -1,43 +1,41 @@
1
- # api/app.py
2
-
3
- from fastapi import FastAPI, Request
4
- from starlette.middleware.cors import CORSMiddleware
5
- from fastapi.responses import JSONResponse
6
- from api.logger import setup_logger
7
- from api.routes import router
8
-
9
-
10
- logger = setup_logger(__name__)
11
-
12
- def create_app():
13
- app = FastAPI(
14
- title="GizAI API Gateway",
15
- docs_url=None, # Disable Swagger UI
16
- redoc_url=None, # Disable ReDoc
17
- openapi_url=None, # Disable OpenAPI schema
18
- )
19
-
20
- # CORS settings
21
- app.add_middleware(
22
- CORSMiddleware,
23
- allow_origins=["*"], # Adjust as needed for security
24
- allow_credentials=True,
25
- allow_methods=["*"],
26
- allow_headers=["*"],
27
- )
28
-
29
- # Include routes
30
- app.include_router(router)
31
-
32
- # Global exception handler for better error reporting
33
- @app.exception_handler(Exception)
34
- async def global_exception_handler(request: Request, exc: Exception):
35
- logger.error(f"An error occurred: {str(exc)}")
36
- return JSONResponse(
37
- status_code=500,
38
- content={"message": "An internal server error occurred."},
39
- )
40
-
41
- return app
42
-
43
- app = create_app()
 
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 CHANGED
@@ -1,12 +1,10 @@
1
- # api/auth.py
2
-
3
- from fastapi import Depends, HTTPException
4
- from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
5
- from api.config import APP_SECRET
6
-
7
- security = HTTPBearer()
8
-
9
- def verify_app_secret(credentials: HTTPAuthorizationCredentials = Depends(security)):
10
- if credentials.credentials != APP_SECRET:
11
- raise HTTPException(status_code=403, detail="Invalid APP_SECRET")
12
- return credentials.credentials
 
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 CHANGED
@@ -1,89 +1,249 @@
1
- # api/config.py
2
-
3
- import os
4
- from dotenv import load_dotenv
5
-
6
- load_dotenv()
7
-
8
- # Base URL and API Endpoint for GizAI
9
- BASE_URL = "https://app.giz.ai"
10
- API_ENDPOINT = "https://app.giz.ai/api/data/users/inferenceServer.infer"
11
-
12
- common_headers = {
13
- 'Accept': 'application/json, text/plain, */*',
14
- 'Accept-Language': 'en-US,en;q=0.9',
15
- 'Cache-Control': 'no-cache',
16
- 'Origin': BASE_URL,
17
- 'Pragma': 'no-cache',
18
- 'Sec-Fetch-Dest': 'empty',
19
- 'Sec-Fetch-Mode': 'cors',
20
- 'Sec-Fetch-Site': 'same-origin',
21
- 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36',
22
- 'sec-ch-ua': '"Not?A_Brand";v="99", "Chromium";v="130"',
23
- 'sec-ch-ua-mobile': '?0',
24
- 'sec-ch-ua-platform': '"Linux"',
25
- 'Content-Type': 'application/json'
26
- }
27
-
28
- # Header Configurations for Specific API Calls
29
- def get_headers_api_chat(referer_url=None):
30
- headers = common_headers.copy()
31
- if referer_url:
32
- headers['Referer'] = referer_url
33
- return headers
34
-
35
- # Define GizAI Models
36
- CHAT_MODELS = [
37
- 'chat-gemini-flash',
38
- 'chat-gemini-pro',
39
- 'chat-gpt4m',
40
- 'chat-gpt4',
41
- 'claude-sonnet',
42
- 'claude-haiku',
43
- 'llama-3-70b',
44
- 'llama-3-8b',
45
- 'mistral-large',
46
- 'chat-o1-mini'
47
- ]
48
-
49
- IMAGE_MODELS = [
50
- 'flux1',
51
- 'sdxl',
52
- 'sd',
53
- 'sd35',
54
- ]
55
-
56
- MODELS = CHAT_MODELS + IMAGE_MODELS
57
-
58
- MODEL_ALIASES = {
59
- # Chat model aliases
60
- "gemini-flash": "chat-gemini-flash",
61
- "gemini-pro": "chat-gemini-pro",
62
- "gpt-4o-mini": "chat-gpt4m",
63
- "gpt-4o": "chat-gpt4",
64
- "claude-3.5-sonnet": "claude-sonnet",
65
- "claude-3-haiku": "claude-haiku",
66
- "llama-3.1-70b": "llama-3-70b",
67
- "llama-3.1-8b": "llama-3-8b",
68
- "o1-mini": "chat-o1-mini",
69
- # Image model aliases
70
- "sd-1.5": "sd",
71
- "sd-3.5": "sd35",
72
- "flux-schnell": "flux1",
73
- }
74
-
75
- DEFAULT_MODEL = 'chat-gemini-flash'
76
-
77
- MODEL_MAPPING = {model: model for model in MODELS}
78
- MODEL_MAPPING.update(MODEL_ALIASES)
79
-
80
- ALLOWED_MODELS = MODELS # You can adjust this if you want to restrict further
81
-
82
- # Agent modes
83
- AGENT_MODE = {}
84
- TRENDING_AGENT_MODE = {}
85
- MODEL_PREFIXES = {}
86
- MODEL_REFERERS = {}
87
-
88
- # **Authentication Secret**
89
- APP_SECRET = os.getenv("APP_SECRET")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
80
+ # Added New Agents
81
+ {"id": "FlaskAgent", "name": "FlaskAgent"},
82
+ {"id": "FirebaseAgent", "name": "FirebaseAgent"},
83
+ {"id": "FastAPIAgent", "name": "FastAPIAgent"},
84
+ {"id": "ErlangAgent", "name": "ErlangAgent"},
85
+ {"id": "ElectronAgent", "name": "ElectronAgent"},
86
+ {"id": "DockerAgent", "name": "DockerAgent"},
87
+ {"id": "DigitalOceanAgent", "name": "DigitalOceanAgent"},
88
+ {"id": "BitbucketAgent", "name": "BitbucketAgent"},
89
+ {"id": "AzureAgent", "name": "AzureAgent"},
90
+ {"id": "FlutterAgent", "name": "FlutterAgent"},
91
+ {"id": "YoutubeAgent", "name": "YoutubeAgent"},
92
+ {"id": "builderAgent", "name": "builderAgent"},
93
+ ]
94
+
95
+ MODEL_MAPPING = {
96
+ "blackboxai": "blackboxai",
97
+ "blackboxai-pro": "blackboxai-pro",
98
+ "flux": "flux",
99
+ "ImageGeneration": "flux",
100
+ "llama-3.1-8b": "llama-3.1-8b",
101
+ "llama-3.1-70b": "llama-3.1-70b",
102
+ "llama-3.1-405b": "llama-3.1-405",
103
+ "gpt-4o": "gpt-4o",
104
+ "gemini-pro": "gemini-pro",
105
+ "gemini-1.5-flash": "gemini-1.5-flash",
106
+ "claude-sonnet-3.5": "claude-sonnet-3.5",
107
+ "PythonAgent": "PythonAgent",
108
+ "JavaAgent": "JavaAgent",
109
+ "JavaScriptAgent": "JavaScriptAgent",
110
+ "HTMLAgent": "HTMLAgent",
111
+ "GoogleCloudAgent": "GoogleCloudAgent",
112
+ "AndroidDeveloper": "AndroidDeveloper",
113
+ "SwiftDeveloper": "SwiftDeveloper",
114
+ "Next.jsAgent": "Next.jsAgent",
115
+ "MongoDBAgent": "MongoDBAgent",
116
+ "PyTorchAgent": "PyTorchAgent",
117
+ "ReactAgent": "ReactAgent",
118
+ "XcodeAgent": "XcodeAgent",
119
+ "AngularJSAgent": "AngularJSAgent",
120
+ "HerokuAgent": "HerokuAgent",
121
+ "GodotAgent": "GodotAgent",
122
+ "GoAgent": "GoAgent",
123
+ "GitlabAgent": "GitlabAgent",
124
+ "GitAgent": "GitAgent",
125
+ "RepoMap": "RepoMap",
126
+ # Additional mappings
127
+ "gemini-flash": "gemini-1.5-flash",
128
+ "claude-3.5-sonnet": "claude-sonnet-3.5",
129
+ "flux": "flux",
130
+ "gemini-1.5-pro-latest": "gemini-pro",
131
+ "gemini-1.5-pro": "gemini-1.5-pro",
132
+ "claude-3-5-sonnet-20240620": "claude-sonnet-3.5",
133
+ "claude-3-5-sonnet": "claude-sonnet-3.5",
134
+ "Niansuh": "Niansuh",
135
+ "o1-preview": "o1-preview",
136
+
137
+ # Added New Agents
138
+ "FlaskAgent": "FlaskAgent",
139
+ "FirebaseAgent": "FirebaseAgent",
140
+ "FastAPIAgent": "FastAPIAgent",
141
+ "ErlangAgent": "ErlangAgent",
142
+ "ElectronAgent": "ElectronAgent",
143
+ "DockerAgent": "DockerAgent",
144
+ "DigitalOceanAgent": "DigitalOceanAgent",
145
+ "BitbucketAgent": "BitbucketAgent",
146
+ "AzureAgent": "AzureAgent",
147
+ "FlutterAgent": "FlutterAgent",
148
+ "YoutubeAgent": "YoutubeAgent",
149
+ "builderAgent": "builderAgent",
150
+ }
151
+
152
+ # Agent modes
153
+ AGENT_MODE = {
154
+ 'flux': {'mode': True, 'id': "ImageGenerationLV45LJp", 'name': "flux"},
155
+ 'Niansuh': {'mode': True, 'id': "NiansuhAIk1HgESy", 'name': "Niansuh"},
156
+ 'o1-preview': {'mode': True, 'id': "o1Dst8La8", 'name': "o1-preview"},
157
+ }
158
+
159
+ TRENDING_AGENT_MODE = {
160
+ "blackboxai": {},
161
+ "gemini-1.5-flash": {'mode': True, 'id': 'Gemini'},
162
+ "llama-3.1-8b": {'mode': True, 'id': "llama-3.1-8b"},
163
+ 'llama-3.1-70b': {'mode': True, 'id': "llama-3.1-70b"},
164
+ 'llama-3.1-405b': {'mode': True, 'id': "llama-3.1-405"},
165
+ 'blackboxai-pro': {'mode': True, 'id': "BLACKBOXAI-PRO"},
166
+ 'PythonAgent': {'mode': True, 'id': "Python Agent"},
167
+ 'JavaAgent': {'mode': True, 'id': "Java Agent"},
168
+ 'JavaScriptAgent': {'mode': True, 'id': "JavaScript Agent"},
169
+ 'HTMLAgent': {'mode': True, 'id': "HTML Agent"},
170
+ 'GoogleCloudAgent': {'mode': True, 'id': "Google Cloud Agent"},
171
+ 'AndroidDeveloper': {'mode': True, 'id': "Android Developer"},
172
+ 'SwiftDeveloper': {'mode': True, 'id': "Swift Developer"},
173
+ 'Next.jsAgent': {'mode': True, 'id': "Next.js Agent"},
174
+ 'MongoDBAgent': {'mode': True, 'id': "MongoDB Agent"},
175
+ 'PyTorchAgent': {'mode': True, 'id': "PyTorch Agent"},
176
+ 'ReactAgent': {'mode': True, 'id': "React Agent"},
177
+ 'XcodeAgent': {'mode': True, 'id': "Xcode Agent"},
178
+ 'AngularJSAgent': {'mode': True, 'id': "AngularJS Agent"},
179
+ 'HerokuAgent': {'mode': True, 'id': "HerokuAgent"},
180
+ 'GodotAgent': {'mode': True, 'id': "GodotAgent"},
181
+ 'GoAgent': {'mode': True, 'id': "GoAgent"},
182
+ 'GitlabAgent': {'mode': True, 'id': "GitlabAgent"},
183
+ 'GitAgent': {'mode': True, 'id': "GitAgent"},
184
+ 'RepoMap': {'mode': True, 'id': "repomap"},
185
+
186
+ # Added New Agents
187
+ 'FlaskAgent': {'mode': True, 'id': "FlaskAgent"},
188
+ 'FirebaseAgent': {'mode': True, 'id': "FirebaseAgent"},
189
+ 'FastAPIAgent': {'mode': True, 'id': "FastAPIAgent"},
190
+ 'ErlangAgent': {'mode': True, 'id': "ErlangAgent"},
191
+ 'ElectronAgent': {'mode': True, 'id': "ElectronAgent"},
192
+ 'DockerAgent': {'mode': True, 'id': "DockerAgent"},
193
+ 'DigitalOceanAgent': {'mode': True, 'id': "DigitalOceanAgent"},
194
+ 'BitbucketAgent': {'mode': True, 'id': "BitbucketAgent"},
195
+ 'AzureAgent': {'mode': True, 'id': "AzureAgent"},
196
+ 'FlutterAgent': {'mode': True, 'id': "FlutterAgent"},
197
+ 'YoutubeAgent': {'mode': True, 'id': "YoutubeAgent"},
198
+ 'builderAgent': {'mode': True, 'id': "builderAgent"},
199
+ }
200
+
201
+ # Model prefixes
202
+ MODEL_PREFIXES = {
203
+ 'gpt-4o': '@GPT-4o',
204
+ 'gemini-pro': '@Gemini-PRO',
205
+ 'PythonAgent': '@Python Agent',
206
+ 'JavaAgent': '@Java Agent',
207
+ 'JavaScriptAgent': '@JavaScript Agent',
208
+ 'HTMLAgent': '@HTML Agent',
209
+ 'GoogleCloudAgent': '@Google Cloud Agent',
210
+ 'AndroidDeveloper': '@Android Developer',
211
+ 'SwiftDeveloper': '@Swift Developer',
212
+ 'Next.jsAgent': '@Next.js Agent',
213
+ 'MongoDBAgent': '@MongoDB Agent',
214
+ 'PyTorchAgent': '@PyTorch Agent',
215
+ 'ReactAgent': '@React Agent',
216
+ 'XcodeAgent': '@Xcode Agent',
217
+ 'AngularJSAgent': '@AngularJS Agent',
218
+ 'HerokuAgent': '@Heroku Agent',
219
+ 'GodotAgent': '@Godot Agent',
220
+ 'GoAgent': '@Go Agent',
221
+ 'GitlabAgent': '@Gitlab Agent',
222
+ 'GitAgent': '@Gitlab Agent',
223
+ 'blackboxai-pro': '@BLACKBOXAI-PRO',
224
+ 'flux': '@Image Generation',
225
+ # Add any additional prefixes if necessary
226
+
227
+ # Added New Agents
228
+ 'FlaskAgent': '@Flask Agent',
229
+ 'FirebaseAgent': '@Firebase Agent',
230
+ 'FastAPIAgent': '@FastAPI Agent',
231
+ 'ErlangAgent': '@Erlang Agent',
232
+ 'ElectronAgent': '@Electron Agent',
233
+ 'DockerAgent': '@Docker Agent',
234
+ 'DigitalOceanAgent': '@DigitalOcean Agent',
235
+ 'BitbucketAgent': '@Bitbucket Agent',
236
+ 'AzureAgent': '@Azure Agent',
237
+ 'FlutterAgent': '@Flutter Agent',
238
+ 'YoutubeAgent': '@Youtube Agent',
239
+ 'builderAgent': '@builder Agent',
240
+ }
241
+
242
+ # Model referers
243
+ MODEL_REFERERS = {
244
+ "blackboxai": "/?model=blackboxai",
245
+ "gpt-4o": "/?model=gpt-4o",
246
+ "gemini-pro": "/?model=gemini-pro",
247
+ "claude-sonnet-3.5": "/?model=claude-sonnet-3.5",
248
+ # Add any additional referers if necessary
249
+ }
api/logger.py CHANGED
@@ -1,54 +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 (optional)
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.")
 
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,19 +1,14 @@
1
- # api/models.py
2
-
3
- from typing import List, Optional, Union, Dict, Any # Ensure 'Any' is imported
4
- from pydantic import BaseModel
5
-
6
- class ImageContent(BaseModel):
7
- image_url: Dict[str, str]
8
-
9
- class Message(BaseModel):
10
- role: str
11
- content: Union[str, List[Dict[str, Any]]] # 'Any' is now defined
12
-
13
- class ChatRequest(BaseModel):
14
- model: str
15
- messages: List[Message]
16
- stream: Optional[bool] = False
17
- temperature: Optional[float] = 0.5
18
- top_p: Optional[float] = 0.9
19
- max_tokens: Optional[int] = 1024
 
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] = 1024
 
 
 
 
 
api/routes.py CHANGED
@@ -1,61 +1,59 @@
1
- # api/routes.py
2
-
3
- import json
4
- from fastapi import APIRouter, Depends, HTTPException, Request, Response
5
- from fastapi.responses import StreamingResponse
6
- from api.auth import verify_app_secret
7
- from api.config import MODELS
8
- from api.models import ChatRequest
9
- from api.utils import process_non_streaming_response, process_streaming_response
10
- from api.logger import setup_logger
11
-
12
- logger = setup_logger(__name__)
13
-
14
- router = APIRouter()
15
-
16
- @router.options("/v1/chat/completions")
17
- @router.options("/api/v1/chat/completions")
18
- async def chat_completions_options():
19
- return Response(
20
- status_code=200,
21
- headers={
22
- "Access-Control-Allow-Origin": "*",
23
- "Access-Control-Allow-Methods": "POST, OPTIONS",
24
- "Access-Control-Allow-Headers": "Content-Type, Authorization",
25
- },
26
- )
27
-
28
- @router.get("/v1/models")
29
- @router.get("/api/v1/models")
30
- async def list_models():
31
- return {"object": "list", "data": MODELS}
32
-
33
- @router.post("/v1/chat/completions")
34
- @router.post("/api/v1/chat/completions")
35
- async def chat_completions(
36
- request: ChatRequest, app_secret: str = Depends(verify_app_secret)
37
- ):
38
- logger.info("Entering chat_completions route")
39
- logger.info(f"Processing chat completion request for model: {request.model}")
40
-
41
- if request.model not in MODELS:
42
- raise HTTPException(
43
- status_code=400,
44
- detail=f"Model {request.model} is not allowed. Allowed models are: {', '.join(MODELS)}",
45
- )
46
-
47
- if request.stream:
48
- logger.info("Streaming response")
49
- return StreamingResponse(process_streaming_response(request), media_type="text/event-stream")
50
- else:
51
- logger.info("Non-streaming response")
52
- return await process_non_streaming_response(request)
53
-
54
- @router.route('/')
55
- @router.route('/healthz')
56
- @router.route('/ready')
57
- @router.route('/alive')
58
- @router.route('/status')
59
- @router.get("/health")
60
- def health_check(request: Request):
61
- return Response(content=json.dumps({"status": "ok"}), media_type="application/json")
 
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 CHANGED
@@ -1,258 +1,227 @@
1
- # api/utils.py
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, AsyncGenerator
10
-
11
- import httpx
12
- from fastapi import HTTPException
13
- from api.config import (
14
- MODELS,
15
- MODEL_ALIASES,
16
- DEFAULT_MODEL,
17
- API_ENDPOINT,
18
- get_headers_api_chat,
19
- BASE_URL,
20
- MODEL_PREFIXES,
21
- MODEL_REFERERS
22
- )
23
- from api.models import ChatRequest, Message
24
- from api.logger import setup_logger
25
-
26
- logger = setup_logger(__name__)
27
-
28
- # Helper function to create a random alphanumeric chat ID
29
- def generate_chat_id(length: int = 7) -> str:
30
- characters = string.ascii_letters + string.digits
31
- return ''.join(random.choices(characters, k=length))
32
-
33
- # Helper function to create a chat completion data chunk
34
- def create_chat_completion_data(
35
- content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
36
- ) -> Dict[str, Any]:
37
- return {
38
- "id": f"chatcmpl-{uuid.uuid4()}",
39
- "object": "chat.completion.chunk",
40
- "created": timestamp,
41
- "model": model,
42
- "choices": [
43
- {
44
- "index": 0,
45
- "delta": {"content": content, "role": "assistant"},
46
- "finish_reason": finish_reason,
47
- }
48
- ],
49
- "usage": None,
50
- }
51
-
52
- # Function to convert message to dictionary format, ensuring base64 data and optional model prefix
53
- def message_to_dict(message: Message, model_prefix: Optional[str] = None):
54
- content = message.content if isinstance(message.content, str) else message.content[0]["text"]
55
- if model_prefix:
56
- content = f"{model_prefix} {content}"
57
- if isinstance(message.content, list) and len(message.content) == 2 and "image_url" in message.content[1]:
58
- # Ensure base64 images are always included for all models
59
- return {
60
- "role": message.role,
61
- "content": content,
62
- "data": {
63
- "imageBase64": message.content[1]["image_url"]["url"],
64
- "fileText": "",
65
- "title": "snapshot",
66
- },
67
- }
68
- return {"role": message.role, "content": content}
69
-
70
- # Function to strip model prefix from content if present
71
- def strip_model_prefix(content: str, model_prefix: Optional[str] = None) -> str:
72
- """Remove the model prefix from the response content if present."""
73
- if model_prefix and content.startswith(model_prefix):
74
- logger.debug(f"Stripping prefix '{model_prefix}' from content.")
75
- return content[len(model_prefix):].strip()
76
- return content
77
-
78
- # Function to get the correct referer URL for logging
79
- def get_referer_url(chat_id: str, model: str) -> str:
80
- """Generate the referer URL based on specific models listed in MODEL_REFERERS."""
81
- if model in MODEL_REFERERS:
82
- return f"{BASE_URL}/chat/{chat_id}?model={model}"
83
- return BASE_URL
84
-
85
- # Helper function to format messages
86
- def format_messages(messages: list[Message]) -> str:
87
- # Assuming messages need to be concatenated in some way
88
- return "\n".join([msg.content if isinstance(msg.content, str) else msg.content[0]["text"] for msg in messages])
89
-
90
- # Process streaming response
91
- async def process_streaming_response(request: ChatRequest) -> AsyncGenerator[str, None]:
92
- chat_id = generate_chat_id()
93
- referer_url = get_referer_url(chat_id, request.model)
94
- logger.info(f"Generated Chat ID: {chat_id} - Model: {request.model} - URL: {referer_url}")
95
-
96
- model = request.model if request.model in MODELS else MODEL_ALIASES.get(request.model, DEFAULT_MODEL)
97
- model_prefix = MODEL_PREFIXES.get(model, "")
98
-
99
- headers_api_chat = get_headers_api_chat(referer_url)
100
-
101
- # Prepare data based on model type
102
- if model in ['flux1', 'sdxl', 'sd', 'sd35']: # Image models
103
- prompt = request.messages[-1].content if isinstance(request.messages[-1].content, str) else request.messages[-1].content[0]["text"]
104
- data = {
105
- "model": model,
106
- "input": {
107
- "width": "1024",
108
- "height": "1024",
109
- "steps": 4,
110
- "output_format": "webp",
111
- "batch_size": 1,
112
- "mode": "plan",
113
- "prompt": prompt
114
- }
115
- }
116
- else: # Chat models
117
- data = {
118
- "model": model,
119
- "input": {
120
- "messages": [
121
- {
122
- "type": "human",
123
- "content": f"{model_prefix} {format_messages(request.messages)}" if model_prefix else format_messages(request.messages)
124
- }
125
- ],
126
- "mode": "plan"
127
- },
128
- "noStream": False # Assuming streaming
129
- }
130
-
131
- async with httpx.AsyncClient() as client:
132
- try:
133
- async with client.post(
134
- API_ENDPOINT,
135
- headers=headers_api_chat,
136
- json=data,
137
- timeout=100
138
- ) as response:
139
- response.raise_for_status()
140
- # Assuming the API returns a streaming response
141
- async for line in response.aiter_lines():
142
- timestamp = int(datetime.now().timestamp())
143
- if line:
144
- content = line
145
- # Depending on GizAI's response format, adjust parsing
146
- # Placeholder for content processing
147
- # Assuming content contains the message
148
- cleaned_content = strip_model_prefix(content, model_prefix)
149
- yield f"data: {json.dumps(create_chat_completion_data(cleaned_content, model, timestamp))}\n\n"
150
-
151
- # Indicate end of stream
152
- yield f"data: {json.dumps(create_chat_completion_data('', model, int(datetime.now().timestamp()), 'stop'))}\n\n"
153
- yield "data: [DONE]\n\n"
154
- except httpx.HTTPStatusError as e:
155
- logger.error(f"HTTP error occurred for Chat ID {chat_id}: {e}")
156
- raise HTTPException(status_code=e.response.status_code, detail=str(e))
157
- except httpx.RequestError as e:
158
- logger.error(f"Error occurred during request for Chat ID {chat_id}: {e}")
159
- raise HTTPException(status_code=500, detail=str(e))
160
-
161
- # Process non-streaming response
162
- async def process_non_streaming_response(request: ChatRequest) -> Dict[str, Any]:
163
- chat_id = generate_chat_id()
164
- referer_url = get_referer_url(chat_id, request.model)
165
- logger.info(f"Generated Chat ID: {chat_id} - Model: {request.model} - URL: {referer_url}")
166
-
167
- model = request.model if request.model in MODELS else MODEL_ALIASES.get(request.model, DEFAULT_MODEL)
168
- model_prefix = MODEL_PREFIXES.get(model, "")
169
-
170
- headers_api_chat = get_headers_api_chat(referer_url)
171
-
172
- # Prepare data based on model type
173
- if model in ['flux1', 'sdxl', 'sd', 'sd35']: # Image models
174
- prompt = request.messages[-1].content if isinstance(request.messages[-1].content, str) else request.messages[-1].content[0]["text"]
175
- data = {
176
- "model": model,
177
- "input": {
178
- "width": "1024",
179
- "height": "1024",
180
- "steps": 4,
181
- "output_format": "webp",
182
- "batch_size": 1,
183
- "mode": "plan",
184
- "prompt": prompt
185
- }
186
- }
187
- else: # Chat models
188
- data = {
189
- "model": model,
190
- "input": {
191
- "messages": [
192
- {
193
- "type": "human",
194
- "content": f"{model_prefix} {format_messages(request.messages)}" if model_prefix else format_messages(request.messages)
195
- }
196
- ],
197
- "mode": "plan"
198
- },
199
- "noStream": True # Non-streaming
200
- }
201
-
202
- async with httpx.AsyncClient() as client:
203
- try:
204
- response = await client.post(
205
- API_ENDPOINT,
206
- headers=headers_api_chat,
207
- json=data,
208
- timeout=100
209
- )
210
- response.raise_for_status()
211
- response_data = response.json()
212
-
213
- # Process response based on GizAI's API response structure
214
- # Placeholder: assuming 'output' contains the generated content
215
- if model in ['flux1', 'sdxl', 'sd', 'sd35']: # Image models
216
- if response_data.get('status') == 'completed' and response_data.get('output'):
217
- images = response_data['output']
218
- # Assuming images is a list of URLs
219
- # For non-streaming, return all images at once
220
- # Adjust according to actual response
221
- return {
222
- "id": f"chatcmpl-{uuid.uuid4()}",
223
- "object": "chat.completion",
224
- "created": int(datetime.now().timestamp()),
225
- "model": model,
226
- "choices": [
227
- {
228
- "index": 0,
229
- "message": {"role": "assistant", "content": "", "images": images},
230
- "finish_reason": "stop",
231
- }
232
- ],
233
- "usage": None,
234
- }
235
- else: # Chat models
236
- # Assuming response_data contains the full response
237
- content = response_data.get('output', '')
238
- cleaned_content = strip_model_prefix(content, model_prefix)
239
- return {
240
- "id": f"chatcmpl-{uuid.uuid4()}",
241
- "object": "chat.completion",
242
- "created": int(datetime.now().timestamp()),
243
- "model": model,
244
- "choices": [
245
- {
246
- "index": 0,
247
- "message": {"role": "assistant", "content": cleaned_content},
248
- "finish_reason": "stop",
249
- }
250
- ],
251
- "usage": None,
252
- }
253
- except httpx.HTTPStatusError as e:
254
- logger.error(f"HTTP error occurred for Chat ID {chat_id}: {e}")
255
- raise HTTPException(status_code=e.response.status_code, detail=str(e))
256
- except httpx.RequestError as e:
257
- logger.error(f"Error occurred during request for Chat ID {chat_id}: {e}")
258
- raise HTTPException(status_code=500, detail=str(e))
 
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": "69783381-2ce4-4dbd-ac78-35e9063feabc",
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": "69783381-2ce4-4dbd-ac78-35e9063feabc",
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
+ }