Niansuh commited on
Commit
b8221ca
1 Parent(s): 473a85c

Upload 13 files

Browse files
Files changed (7) hide show
  1. .github/workflows/docker-deploy.yml +1 -1
  2. api/app.py +41 -50
  3. api/config.py +255 -44
  4. api/logger.py +54 -14
  5. api/models.py +14 -14
  6. api/utils.py +227 -136
  7. 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: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
 
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, Depends, HTTPException, Request, Response
2
- from fastapi.responses import JSONResponse, StreamingResponse
3
- from api.auth import verify_app_secret
4
- from api.config import ALLOWED_MODELS
5
- from api.models import ChatRequest
6
- from api.utils import process_response
7
- from api.logger import setup_logger
8
-
9
- logger = setup_logger(__name__)
10
-
11
- app = FastAPI(
12
- title="Your API",
13
- docs_url=None, # Disable Swagger UI
14
- redoc_url=None, # Disable ReDoc
15
- openapi_url=None, # Disable OpenAPI schema
16
- )
17
-
18
- # Include your authentication if needed
19
- # from api.auth import verify_app_secret
20
-
21
- @app.post("/v1/chat/completions")
22
- async def chat_completions(
23
- request: ChatRequest, app_secret: str = Depends(verify_app_secret)
24
- ):
25
- logger.info("Processing chat completion request")
26
- if request.model not in [model["id"] for model in ALLOWED_MODELS]:
27
- raise HTTPException(
28
- status_code=400,
29
- detail=f"Model {request.model} is not allowed."
30
- )
31
-
32
- # Process the response using Editee API
33
- if request.stream:
34
- # If streaming is required
35
- generator = process_response(request, stream=True)
36
- return StreamingResponse(generator, media_type="text/event-stream")
37
- else:
38
- # Non-streaming response
39
- response_data = await process_response(request)
40
- return JSONResponse(content=response_data)
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://editee.com"
8
- EDITEA_API_ENDPOINT = "https://editee.com/submit/chatgptfree"
9
-
10
- # Editee API Headers
11
- EDITEA_HEADERS = {
12
- "Accept": "application/json, text/plain, */*",
13
- "Accept-Language": "en-US,en;q=0.9",
14
- "Cache-Control": "no-cache",
15
- "Content-Type": "application/json",
16
- "Origin": BASE_URL,
17
- "Pragma": "no-cache",
18
- "Priority": "u=1, i",
19
- "Referer": f"{BASE_URL}/chat-gpt",
20
- "Sec-CH-UA": '"Chromium";v="129", "Not=A?Brand";v="8"',
21
- "Sec-CH-UA-Mobile": '?0',
22
- "Sec-CH-UA-Platform": '"Linux"',
23
- "Sec-Fetch-Dest": 'empty',
24
- "Sec-Fetch-Mode": 'cors',
25
- "Sec-Fetch-Site": 'same-origin',
26
- "User-Agent": 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',
27
- "X-Requested-With": 'XMLHttpRequest',
28
- }
29
-
30
- APP_SECRET = os.getenv("APP_SECRET")
31
-
32
- ALLOWED_MODELS = [
33
- {"id": "claude", "name": "Claude"},
34
- {"id": "gpt4", "name": "GPT-4"},
35
- {"id": "gemini", "name": "Gemini"},
36
- {"id": "mistrallarge", "name": "Mistral Large"},
37
- ]
38
-
39
- MODEL_MAPPING = {
40
- "claude-3.5-sonnet": "claude",
41
- "gpt-4o": "gpt4",
42
- "gemini-pro": "gemini",
43
- "mistral-large": "mistrallarge",
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
- 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
- # Console handler
9
- console_handler = logging.StreamHandler()
10
- console_handler.setFormatter(formatter)
11
- logger.addHandler(console_handler)
12
- return logger
13
-
14
- logger = setup_logger(__name__)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = 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] = 99999999
api/utils.py CHANGED
@@ -1,136 +1,227 @@
1
- import uuid
2
- from typing import List, Dict
3
- from aiohttp import ClientSession
4
- from api.models import ChatRequest
5
- from api.helper import format_prompt
6
- from api.logger import logger
7
- from api.config import MODEL_MAPPING, EDITEA_API_ENDPOINT, EDITEA_HEADERS
8
- from fastapi import HTTPException
9
-
10
- class Editee:
11
- label = "Editee"
12
- url = "https://editee.com"
13
- api_endpoint = EDITEA_API_ENDPOINT
14
- working = True
15
- supports_stream = True
16
- supports_system_message = True
17
- supports_message_history = True
18
-
19
- default_model = 'claude'
20
- models = ['claude', 'gpt4', 'gemini', 'mistrallarge']
21
-
22
- model_aliases = {
23
- "claude-3.5-sonnet": "claude",
24
- "gpt-4o": "gpt4",
25
- "gemini-pro": "gemini",
26
- "mistral-large": "mistrallarge",
27
- }
28
-
29
- @classmethod
30
- def get_model(cls, model: str) -> str:
31
- if model in cls.models:
32
- return model
33
- elif model in cls.model_aliases:
34
- return cls.model_aliases[model]
35
- else:
36
- return cls.default_model
37
-
38
- @classmethod
39
- async def create_async_generator(
40
- cls,
41
- model: str,
42
- messages: List[Dict[str, str]],
43
- proxy: str = None,
44
- **kwargs
45
- ):
46
- model = cls.get_model(model)
47
- headers = EDITEA_HEADERS
48
-
49
- async with ClientSession(headers=headers) as session:
50
- prompt = format_prompt(messages)
51
- data = {
52
- "user_input": prompt,
53
- "context": " ",
54
- "template_id": "",
55
- "selected_model": model
56
- }
57
- try:
58
- async with session.post(cls.api_endpoint, json=data, proxy=proxy) as response:
59
- response.raise_for_status()
60
- # Check if the response is in JSON format
61
- if response.headers.get('Content-Type') == 'application/json':
62
- response_data = await response.json()
63
- yield response_data['text']
64
- else:
65
- # Stream the response line by line
66
- async for line in response.content:
67
- yield line.decode('utf-8')
68
- except Exception as e:
69
- logger.error(f"Error in Editee API call: {e}")
70
- raise HTTPException(status_code=500, detail="Error in Editee API call")
71
-
72
- # Function to process non-streaming response
73
- async def process_response(request: ChatRequest):
74
- try:
75
- model = MODEL_MAPPING.get(request.model, request.model)
76
- messages = [
77
- {"role": message.role, "content": message.content}
78
- for message in request.messages
79
- ]
80
-
81
- generator = Editee.create_async_generator(
82
- model=model,
83
- messages=messages,
84
- proxy=None # Add proxy if needed
85
- )
86
-
87
- full_response = ""
88
- async for chunk in generator:
89
- full_response += chunk
90
-
91
- return {
92
- "id": f"chatcmpl-{uuid.uuid4()}",
93
- "object": "chat.completion",
94
- "created": int(uuid.uuid1().time),
95
- "model": model,
96
- "choices": [
97
- {
98
- "index": 0,
99
- "message": {"role": "assistant", "content": full_response},
100
- "finish_reason": "stop",
101
- }
102
- ],
103
- "usage": None,
104
- }
105
- except Exception as e:
106
- logger.error(f"Error processing response: {e}")
107
- raise HTTPException(status_code=500, detail=str(e))
108
-
109
- # Function to process streaming response
110
- async def process_response_stream(request: ChatRequest):
111
- try:
112
- model = MODEL_MAPPING.get(request.model, request.model)
113
- messages = [
114
- {"role": message.role, "content": message.content}
115
- for message in request.messages
116
- ]
117
-
118
- generator = Editee.create_async_generator(
119
- model=model,
120
- messages=messages,
121
- proxy=None # Add proxy if needed
122
- )
123
-
124
- async def event_generator():
125
- try:
126
- async for chunk in generator:
127
- yield f"data: {chunk}\n\n"
128
- yield "data: [DONE]\n\n"
129
- except Exception as e:
130
- logger.error(f"Error in streaming response: {e}")
131
- yield f"data: [ERROR] {str(e)}\n\n"
132
-
133
- return event_generator()
134
- except Exception as e:
135
- logger.error(f"Error processing streaming response: {e}")
136
- 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": "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
- pydantic==1.10.4
3
- python-dotenv==0.21.0
4
- uvicorn==0.21.1
5
- gunicorn==20.1.0
6
- aiohttp==3.8.5
 
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