Niansuh commited on
Commit
4311a71
1 Parent(s): 56867b8

Upload 13 files

Browse files
Files changed (8) hide show
  1. api/app.py +12 -5
  2. api/config.py +225 -12
  3. api/logger.py +37 -3
  4. api/models.py +2 -4
  5. api/routes.py +8 -11
  6. api/utils.py +227 -160
  7. main.py +1 -1
  8. requirements.txt +6 -8
api/app.py CHANGED
@@ -2,25 +2,32 @@ 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 # 导入router而不是单独的函数
 
6
 
7
  logger = setup_logger(__name__)
8
 
9
  def create_app():
10
- app = FastAPI()
 
 
 
 
 
11
 
12
- # 配置CORS
13
  app.add_middleware(
14
  CORSMiddleware,
15
- allow_origins=["*"],
16
  allow_credentials=True,
17
  allow_methods=["*"],
18
  allow_headers=["*"],
19
  )
20
 
21
- # 添加路由
22
  app.include_router(router)
23
 
 
24
  @app.exception_handler(Exception)
25
  async def global_exception_handler(request: Request, exc: Exception):
26
  logger.error(f"An error occurred: {str(exc)}")
 
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)}")
api/config.py CHANGED
@@ -3,34 +3,247 @@ from dotenv import load_dotenv
3
 
4
  load_dotenv()
5
 
 
6
  BASE_URL = "https://www.blackbox.ai"
7
- headers = {
8
  'accept': '*/*',
9
- 'accept-language': 'zh-CN,zh;q=0.9',
10
- 'origin': 'https://www.blackbox.ai',
 
 
11
  'priority': 'u=1, i',
12
- 'sec-ch-ua': '"Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
13
  'sec-ch-ua-mobile': '?0',
14
  'sec-ch-ua-platform': '"Windows"',
15
  'sec-fetch-dest': 'empty',
16
  'sec-fetch-mode': 'cors',
17
  'sec-fetch-site': 'same-origin',
18
- 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',
 
 
19
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  APP_SECRET = os.getenv("APP_SECRET")
 
21
  ALLOWED_MODELS = [
 
 
 
 
 
 
22
  {"id": "gpt-4o", "name": "gpt-4o"},
23
- {"id": "gemini-1.5-pro-latest", "name": "gemini-pro"},
24
- {"id": "gemini-1.5-pro", "name": "gemini-pro"},
25
  {"id": "gemini-pro", "name": "gemini-pro"},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  {"id": "claude-3-5-sonnet-20240620", "name": "claude-sonnet-3.5"},
27
  {"id": "claude-3-5-sonnet", "name": "claude-sonnet-3.5"},
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  ]
 
29
  MODEL_MAPPING = {
30
- "gpt-4o":"gpt-4o",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  "gemini-1.5-pro-latest": "gemini-pro",
32
- "gemini-1.5-pro":"gemini-1.5-pro",
33
- "gemini-pro":"gemini-pro",
34
- "claude-3-5-sonnet-20240620":"claude-sonnet-3.5",
35
- "claude-3-5-sonnet":"claude-sonnet-3.5",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  }
 
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,20 +1,54 @@
1
  import logging
2
 
 
3
  def setup_logger(name):
4
  logger = logging.getLogger(name)
5
  if not logger.handlers:
6
  logger.setLevel(logging.INFO)
7
  formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
8
 
9
- # 控制台处理器
10
  console_handler = logging.StreamHandler()
11
  console_handler.setFormatter(formatter)
12
  logger.addHandler(console_handler)
13
 
14
- # 文件处理器 - 错误级别
15
  # error_file_handler = logging.FileHandler('error.log')
16
  # error_file_handler.setFormatter(formatter)
17
  # error_file_handler.setLevel(logging.ERROR)
18
  # logger.addHandler(error_file_handler)
19
 
20
- return logger
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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,16 +1,14 @@
1
  from typing import List, Optional
2
  from pydantic import BaseModel
3
 
4
-
5
  class Message(BaseModel):
6
  role: str
7
  content: str | list
8
 
9
-
10
  class ChatRequest(BaseModel):
11
  model: str
12
  messages: List[Message]
13
  stream: Optional[bool] = False
14
- temperature: Optional[float] = 0.7
15
  top_p: Optional[float] = 0.9
16
- max_tokens: Optional[int] = 8192
 
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
@@ -34,9 +34,7 @@ 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"Received request: {request}")
38
- logger.info(f"App secret: {app_secret}")
39
- logger.info(f"Received chat completion request for model: {request.model}")
40
 
41
  if request.model not in [model["id"] for model in ALLOWED_MODELS]:
42
  raise HTTPException(
@@ -51,12 +49,11 @@ async def chat_completions(
51
  logger.info("Non-streaming response")
52
  return await process_non_streaming_response(request)
53
 
54
-
55
- @router.route('/')
56
- @router.route('/healthz')
57
- @router.route('/ready')
58
- @router.route('/alive')
59
- @router.route('/status')
60
  @router.get("/health")
61
- def health_check(request: Request):
62
- return Response(content=json.dumps({"status": "ok"}), media_type="application/json")
 
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(
 
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,160 +1,227 @@
1
- from datetime import datetime
2
- from http.client import HTTPException
3
- import json
4
- from typing import Any, Dict, Optional
5
- import uuid
6
-
7
- import httpx
8
- from api.config import MODEL_MAPPING, headers
9
- from fastapi import Depends, security
10
- from fastapi.security import HTTPAuthorizationCredentials
11
-
12
- from api.config import APP_SECRET, BASE_URL
13
- from api.models import ChatRequest
14
-
15
- from api.logger import setup_logger
16
-
17
- logger = setup_logger(__name__)
18
-
19
-
20
- def create_chat_completion_data(
21
- content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
22
- ) -> Dict[str, Any]:
23
- return {
24
- "id": f"chatcmpl-{uuid.uuid4()}",
25
- "object": "chat.completion.chunk",
26
- "created": timestamp,
27
- "model": model,
28
- "choices": [
29
- {
30
- "index": 0,
31
- "delta": {"content": content, "role": "assistant"},
32
- "finish_reason": finish_reason,
33
- }
34
- ],
35
- "usage": None,
36
- }
37
-
38
-
39
- def verify_app_secret(credentials: HTTPAuthorizationCredentials = Depends(security)):
40
- if credentials.credentials != APP_SECRET:
41
- raise HTTPException(status_code=403, detail="Invalid APP_SECRET")
42
- return credentials.credentials
43
-
44
-
45
- def message_to_dict(message):
46
- if isinstance(message.content, str):
47
- return {"role": message.role, "content": message.content}
48
- elif isinstance(message.content, list) and len(message.content) == 2:
49
- return {
50
- "role": message.role,
51
- "content": message.content[0]["text"],
52
- "data": {
53
- "imageBase64": message.content[1]["image_url"]["url"],
54
- "fileText": "",
55
- "title": "snapshoot",
56
- },
57
- }
58
- else:
59
- return {"role": message.role, "content": message.content}
60
-
61
-
62
- async def process_streaming_response(request: ChatRequest):
63
- json_data = {
64
- "messages": [message_to_dict(msg) for msg in request.messages],
65
- "previewToken": None,
66
- "userId": None,
67
- "codeModelMode": True,
68
- "agentMode": {},
69
- "trendingAgentMode": {},
70
- "isMicMode": False,
71
- "userSystemPrompt": None,
72
- "maxTokens": request.max_tokens,
73
- "playgroundTopP": request.top_p,
74
- "playgroundTemperature": request.temperature,
75
- "isChromeExt": False,
76
- "githubToken": None,
77
- "clickedAnswer2": False,
78
- "clickedAnswer3": False,
79
- "clickedForceWebSearch": False,
80
- "visitFromDelta": False,
81
- "mobileClient": False,
82
- "validated": "69783381-2ce4-4dbd-ac78-35e9063feabc",
83
- "userSelectedModel": MODEL_MAPPING.get(request.model),
84
- }
85
-
86
- async with httpx.AsyncClient() as client:
87
- try:
88
- async with client.stream(
89
- "POST",
90
- f"{BASE_URL}/api/chat",
91
- headers=headers,
92
- json=json_data,
93
- timeout=100,
94
- ) as response:
95
- response.raise_for_status()
96
- async for line in response.aiter_lines():
97
- timestamp = int(datetime.now().timestamp())
98
- if line:
99
- content = line + "\n"
100
- if content.startswith("$@$v=undefined-rv1$@$"):
101
- yield f"data: {json.dumps(create_chat_completion_data(content[21:], request.model, timestamp))}\n\n"
102
- else:
103
- yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
104
-
105
- yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
106
- yield "data: [DONE]\n\n"
107
- except httpx.HTTPStatusError as e:
108
- logger.error(f"HTTP error occurred: {e}")
109
- raise HTTPException(status_code=e.response.status_code, detail=str(e))
110
- except httpx.RequestError as e:
111
- logger.error(f"Error occurred during request: {e}")
112
- raise HTTPException(status_code=500, detail=str(e))
113
-
114
-
115
- async def process_non_streaming_response(request: ChatRequest):
116
- json_data = {
117
- "messages": [message_to_dict(msg) for msg in request.messages],
118
- "previewToken": None,
119
- "userId": None,
120
- "codeModelMode": True,
121
- "agentMode": {},
122
- "trendingAgentMode": {},
123
- "isMicMode": False,
124
- "userSystemPrompt": None,
125
- "maxTokens": request.max_tokens,
126
- "playgroundTopP": request.top_p,
127
- "playgroundTemperature": request.temperature,
128
- "isChromeExt": False,
129
- "githubToken": None,
130
- "clickedAnswer2": False,
131
- "clickedAnswer3": False,
132
- "clickedForceWebSearch": False,
133
- "visitFromDelta": False,
134
- "mobileClient": False,
135
- "validated": "69783381-2ce4-4dbd-ac78-35e9063feabc",
136
- "userSelectedModel": MODEL_MAPPING.get(request.model),
137
- }
138
- full_response = ""
139
- async with httpx.AsyncClient() as client:
140
- async with client.stream(
141
- method="POST", url=f"{BASE_URL}/api/chat", headers=headers, json=json_data
142
- ) as response:
143
- async for chunk in response.aiter_text():
144
- full_response += chunk
145
- if full_response.startswith("$@$v=undefined-rv1$@$"):
146
- full_response = full_response[21:]
147
- return {
148
- "id": f"chatcmpl-{uuid.uuid4()}",
149
- "object": "chat.completion",
150
- "created": int(datetime.now().timestamp()),
151
- "model": request.model,
152
- "choices": [
153
- {
154
- "index": 0,
155
- "message": {"role": "assistant", "content": full_response},
156
- "finish_reason": "stop",
157
- }
158
- ],
159
- "usage": None,
160
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ }
main.py CHANGED
@@ -2,4 +2,4 @@ import uvicorn
2
  from api.app import app
3
 
4
  if __name__ == "__main__":
5
- uvicorn.run(app, host="0.0.0.0", port=8001)
 
2
  from api.app import app
3
 
4
  if __name__ == "__main__":
5
+ uvicorn.run(app, host="0.0.0.0", port=8001)
requirements.txt CHANGED
@@ -1,8 +1,6 @@
1
- fastapi
2
- httpx
3
- pydantic
4
- pyinstaller
5
- python-dotenv
6
- starlette
7
- uvicorn
8
- gunicorn
 
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