Niansuh commited on
Commit
3eec113
1 Parent(s): 0464e0f

Upload 22 files

Browse files
.dockerignore ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ *.pyc
3
+ *.pyo
4
+ *.pyd
5
+ *.swp
6
+ *.swo
7
+ *.log
8
+ .env
9
+ .git
.env ADDED
@@ -0,0 +1 @@
 
 
1
+ APP_SECRET=123456
Dockerfile CHANGED
@@ -1,33 +1,18 @@
1
- # Use the official Python 3.11 slim image as the base
2
- FROM python:3.11-slim
3
 
4
- # Install Tesseract OCR and its development libraries
5
- RUN apt-get update && apt-get install -y --no-install-recommends \
6
- tesseract-ocr \
7
- libtesseract-dev \
8
- && rm -rf /var/lib/apt/lists/*
9
-
10
- # Set environment variables to prevent Python from writing .pyc files and to buffer stdout/stderr
11
- ENV PYTHONDONTWRITEBYTECODE=1
12
- ENV PYTHONUNBUFFERED=1
13
-
14
- # Set the working directory inside the container
15
  WORKDIR /app
16
 
17
- # Copy the requirements file into the container
18
- COPY requirements.txt .
19
-
20
- # Upgrade pip to the latest version
21
- RUN pip install --upgrade pip
22
-
23
- # Install Python dependencies from requirements.txt
24
- RUN pip install -r requirements.txt
25
 
26
- # Copy the rest of your application code into the container
27
- COPY . .
 
28
 
29
- # Expose port 8000 to the outside world
30
- EXPOSE 8000
31
 
32
- # Define the default command to run your application using Uvicorn
33
- CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
 
1
+ # Use an official Python runtime as a parent image
2
+ FROM python:3.10-slim
3
 
4
+ # Set the working directory in the container
 
 
 
 
 
 
 
 
 
 
5
  WORKDIR /app
6
 
7
+ # Copy the current directory contents into the container
8
+ COPY . /app
 
 
 
 
 
 
9
 
10
+ # Install any needed packages specified in requirements.txt
11
+ RUN pip install --no-cache-dir --upgrade pip && \
12
+ pip install --no-cache-dir -r requirements.txt
13
 
14
+ # Expose the port that the FastAPI app runs on
15
+ EXPOSE 8001
16
 
17
+ # Command to run the app with Gunicorn and Uvicorn workers
18
+ CMD ["gunicorn", "-k", "uvicorn.workers.UvicornWorker", "--workers", "4", "--bind", "0.0.0.0:8001", "main:app"]
__pycache__/main.cpython-310.pyc ADDED
Binary file (246 Bytes). View file
 
api/__init__.py ADDED
File without changes
api/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (153 Bytes). View file
 
api/__pycache__/app.cpython-310.pyc ADDED
Binary file (1.13 kB). View file
 
api/__pycache__/auth.cpython-310.pyc ADDED
Binary file (594 Bytes). View file
 
api/__pycache__/config.cpython-310.pyc ADDED
Binary file (1.06 kB). View file
 
api/__pycache__/logger.cpython-310.pyc ADDED
Binary file (541 Bytes). View file
 
api/__pycache__/models.cpython-310.pyc ADDED
Binary file (853 Bytes). View file
 
api/__pycache__/routes.cpython-310.pyc ADDED
Binary file (2.58 kB). View file
 
api/__pycache__/utils.cpython-310.pyc ADDED
Binary file (4.69 kB). View file
 
api/app.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 # 导入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)}")
27
+ return JSONResponse(
28
+ status_code=500,
29
+ content={"message": "An internal server error occurred."},
30
+ )
31
+
32
+ return app
33
+
34
+ app = create_app()
api/auth.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import Depends, HTTPException
2
+ from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
3
+ from api.config import APP_SECRET
4
+
5
+ security = HTTPBearer()
6
+
7
+ def verify_app_secret(credentials: HTTPAuthorizationCredentials = Depends(security)):
8
+ if credentials.credentials != APP_SECRET:
9
+ raise HTTPException(status_code=403, detail="Invalid APP_SECRET")
10
+ return credentials.credentials
api/config.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ 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
+ }
api/logger.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
api/models.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
api/routes.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"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(
43
+ status_code=400,
44
+ detail=f"Model {request.model} is not allowed. Allowed models are: {', '.join(model['id'] for model in ALLOWED_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
+
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")
api/utils.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "userSelectedModel": MODEL_MAPPING.get(request.model),
83
+ }
84
+
85
+ async with httpx.AsyncClient() as client:
86
+ try:
87
+ async with client.stream(
88
+ "POST",
89
+ f"{BASE_URL}/api/chat",
90
+ headers=headers,
91
+ json=json_data,
92
+ timeout=100,
93
+ ) as response:
94
+ response.raise_for_status()
95
+ async for line in response.aiter_lines():
96
+ timestamp = int(datetime.now().timestamp())
97
+ if line:
98
+ content = line + "\n"
99
+ if content.startswith("$@$v=undefined-rv1$@$"):
100
+ yield f"data: {json.dumps(create_chat_completion_data(content[21:], request.model, timestamp))}\n\n"
101
+ else:
102
+ yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
103
+
104
+ yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
105
+ yield "data: [DONE]\n\n"
106
+ except httpx.HTTPStatusError as e:
107
+ logger.error(f"HTTP error occurred: {e}")
108
+ raise HTTPException(status_code=e.response.status_code, detail=str(e))
109
+ except httpx.RequestError as e:
110
+ logger.error(f"Error occurred during request: {e}")
111
+ raise HTTPException(status_code=500, detail=str(e))
112
+
113
+
114
+ async def process_non_streaming_response(request: ChatRequest):
115
+ json_data = {
116
+ "messages": [message_to_dict(msg) for msg in request.messages],
117
+ "previewToken": None,
118
+ "userId": None,
119
+ "codeModelMode": True,
120
+ "agentMode": {},
121
+ "trendingAgentMode": {},
122
+ "isMicMode": False,
123
+ "userSystemPrompt": None,
124
+ "maxTokens": request.max_tokens,
125
+ "playgroundTopP": request.top_p,
126
+ "playgroundTemperature": request.temperature,
127
+ "isChromeExt": False,
128
+ "githubToken": None,
129
+ "clickedAnswer2": False,
130
+ "clickedAnswer3": False,
131
+ "clickedForceWebSearch": False,
132
+ "visitFromDelta": False,
133
+ "mobileClient": False,
134
+ "userSelectedModel": MODEL_MAPPING.get(request.model),
135
+ }
136
+ full_response = ""
137
+ async with httpx.AsyncClient() as client:
138
+ async with client.stream(
139
+ method="POST", url=f"{BASE_URL}/api/chat", headers=headers, json=json_data
140
+ ) as response:
141
+ async for chunk in response.aiter_text():
142
+ full_response += chunk
143
+ if full_response.startswith("$@$v=undefined-rv1$@$"):
144
+ full_response = full_response[21:]
145
+ return {
146
+ "id": f"chatcmpl-{uuid.uuid4()}",
147
+ "object": "chat.completion",
148
+ "created": int(datetime.now().timestamp()),
149
+ "model": request.model,
150
+ "choices": [
151
+ {
152
+ "index": 0,
153
+ "message": {"role": "assistant", "content": full_response},
154
+ "finish_reason": "stop",
155
+ }
156
+ ],
157
+ "usage": None,
158
+ }
main.py CHANGED
@@ -1,757 +1,5 @@
1
- import os
2
- import re
3
- import random
4
- import string
5
- import uuid
6
- import json
7
- import logging
8
- import asyncio
9
- import time
10
- from collections import defaultdict
11
- from typing import List, Dict, Any, Optional, AsyncGenerator, Union
12
-
13
- from datetime import datetime
14
-
15
- from aiohttp import ClientSession, ClientTimeout, ClientError
16
- from fastapi import FastAPI, HTTPException, Request, Depends, Header
17
- from fastapi.responses import StreamingResponse, JSONResponse, RedirectResponse
18
- from pydantic import BaseModel
19
-
20
- from PIL import Image
21
- import base64
22
- from io import BytesIO
23
-
24
- # Configure logging
25
- logging.basicConfig(
26
- level=logging.INFO,
27
- format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
28
- handlers=[logging.StreamHandler()]
29
- )
30
- logger = logging.getLogger(__name__)
31
-
32
- # Load environment variables
33
- API_KEYS = os.getenv('API_KEYS', '').split(',') # Comma-separated API keys
34
- RATE_LIMIT = int(os.getenv('RATE_LIMIT', '60')) # Requests per minute
35
- AVAILABLE_MODELS = os.getenv('AVAILABLE_MODELS', '') # Comma-separated available models
36
-
37
- if not API_KEYS or API_KEYS == ['']:
38
- logger.error("No API keys found. Please set the API_KEYS environment variable.")
39
- raise Exception("API_KEYS environment variable not set.")
40
-
41
- # Process available models
42
- if AVAILABLE_MODELS:
43
- AVAILABLE_MODELS = [model.strip() for model in AVAILABLE_MODELS.split(',') if model.strip()]
44
- else:
45
- AVAILABLE_MODELS = [] # If empty, all models are available
46
-
47
- # Simple in-memory rate limiter based solely on IP addresses
48
- rate_limit_store = defaultdict(lambda: {"count": 0, "timestamp": time.time()})
49
-
50
- # Define cleanup interval and window
51
- CLEANUP_INTERVAL = 60 # seconds
52
- RATE_LIMIT_WINDOW = 60 # seconds
53
-
54
- async def cleanup_rate_limit_stores():
55
- """
56
- Periodically cleans up stale entries in the rate_limit_store to prevent memory bloat.
57
- """
58
- while True:
59
- current_time = time.time()
60
- ips_to_delete = [ip for ip, value in rate_limit_store.items() if current_time - value["timestamp"] > RATE_LIMIT_WINDOW * 2]
61
- for ip in ips_to_delete:
62
- del rate_limit_store[ip]
63
- logger.debug(f"Cleaned up rate_limit_store for IP: {ip}")
64
- await asyncio.sleep(CLEANUP_INTERVAL)
65
-
66
- async def rate_limiter_per_ip(request: Request):
67
- """
68
- Rate limiter that enforces a limit based on the client's IP address.
69
- """
70
- client_ip = request.client.host
71
- current_time = time.time()
72
-
73
- # Initialize or update the count and timestamp
74
- if current_time - rate_limit_store[client_ip]["timestamp"] > RATE_LIMIT_WINDOW:
75
- rate_limit_store[client_ip] = {"count": 1, "timestamp": current_time}
76
- else:
77
- if rate_limit_store[client_ip]["count"] >= RATE_LIMIT:
78
- logger.warning(f"Rate limit exceeded for IP address: {client_ip}")
79
- raise HTTPException(status_code=429, detail='Rate limit exceeded for IP address | NiansuhAI')
80
- rate_limit_store[client_ip]["count"] += 1
81
-
82
- async def get_api_key(request: Request, authorization: str = Header(None)) -> str:
83
- """
84
- Dependency to extract and validate the API key from the Authorization header.
85
- """
86
- client_ip = request.client.host
87
- if authorization is None or not authorization.startswith('Bearer '):
88
- logger.warning(f"Invalid or missing authorization header from IP: {client_ip}")
89
- raise HTTPException(status_code=401, detail='Invalid authorization header format')
90
- api_key = authorization[7:]
91
- if api_key not in API_KEYS:
92
- logger.warning(f"Invalid API key attempted: {api_key} from IP: {client_ip}")
93
- raise HTTPException(status_code=401, detail='Invalid API key')
94
- return api_key
95
-
96
- # Custom exception for model not working
97
- class ModelNotWorkingException(Exception):
98
- def __init__(self, model: str):
99
- self.model = model
100
- self.message = f"The model '{model}' is currently not working. Please try another model or wait for it to be fixed."
101
- super().__init__(self.message)
102
-
103
- # Mock implementations for ImageResponse and to_data_uri
104
- class ImageResponse:
105
- def __init__(self, url: str, alt: str):
106
- self.url = url
107
- self.alt = alt
108
-
109
- def to_data_uri(image: Any) -> str:
110
- return "data:image/png;base64,..." # Replace with actual base64 data
111
-
112
- class Blackbox:
113
- url = "https://www.blackbox.ai"
114
- api_endpoint = "https://www.blackbox.ai/api/chat"
115
- working = True
116
- supports_stream = True
117
- supports_system_message = True
118
- supports_message_history = True
119
-
120
- default_model = 'blackboxai'
121
- image_models = ['ImageGeneration']
122
- models = [
123
- default_model,
124
- 'blackboxai-pro',
125
- "llama-3.1-8b",
126
- 'llama-3.1-70b',
127
- 'llama-3.1-405b',
128
- 'gpt-4o',
129
- 'gemini-pro',
130
- 'gemini-1.5-flash',
131
- 'claude-sonnet-3.5',
132
- 'PythonAgent',
133
- 'JavaAgent',
134
- 'JavaScriptAgent',
135
- 'HTMLAgent',
136
- 'GoogleCloudAgent',
137
- 'AndroidDeveloper',
138
- 'SwiftDeveloper',
139
- 'Next.jsAgent',
140
- 'MongoDBAgent',
141
- 'PyTorchAgent',
142
- 'ReactAgent',
143
- 'XcodeAgent',
144
- 'AngularJSAgent',
145
- *image_models,
146
- 'Niansuh',
147
- ]
148
-
149
- # Filter models based on AVAILABLE_MODELS
150
- if AVAILABLE_MODELS:
151
- models = [model for model in models if model in AVAILABLE_MODELS]
152
-
153
- agentMode = {
154
- 'ImageGeneration': {'mode': True, 'id': "ImageGenerationLV45LJp", 'name': "Image Generation"},
155
- 'Niansuh': {'mode': True, 'id': "NiansuhAIk1HgESy", 'name': "Niansuh"},
156
- }
157
- trendingAgentMode = {
158
- "blackboxai": {},
159
- "gemini-1.5-flash": {'mode': True, 'id': 'Gemini'},
160
- "llama-3.1-8b": {'mode': True, 'id': "llama-3.1-8b"},
161
- 'llama-3.1-70b': {'mode': True, 'id': "llama-3.1-70b"},
162
- 'llama-3.1-405b': {'mode': True, 'id': "llama-3.1-405b"},
163
- 'blackboxai-pro': {'mode': True, 'id': "BLACKBOXAI-PRO"},
164
- 'PythonAgent': {'mode': True, 'id': "Python Agent"},
165
- 'JavaAgent': {'mode': True, 'id': "Java Agent"},
166
- 'JavaScriptAgent': {'mode': True, 'id': "JavaScript Agent"},
167
- 'HTMLAgent': {'mode': True, 'id': "HTML Agent"},
168
- 'GoogleCloudAgent': {'mode': True, 'id': "Google Cloud Agent"},
169
- 'AndroidDeveloper': {'mode': True, 'id': "Android Developer"},
170
- 'SwiftDeveloper': {'mode': True, 'id': "Swift Developer"},
171
- 'Next.jsAgent': {'mode': True, 'id': "Next.js Agent"},
172
- 'MongoDBAgent': {'mode': True, 'id': "MongoDB Agent"},
173
- 'PyTorchAgent': {'mode': True, 'id': "PyTorch Agent"},
174
- 'ReactAgent': {'mode': True, 'id': "React Agent"},
175
- 'XcodeAgent': {'mode': True, 'id': "Xcode Agent"},
176
- 'AngularJSAgent': {'mode': True, 'id': "AngularJS Agent"},
177
- }
178
-
179
- userSelectedModel = {
180
- "gpt-4o": "gpt-4o",
181
- "gemini-pro": "gemini-pro",
182
- 'claude-sonnet-3.5': "claude-sonnet-3.5",
183
- }
184
-
185
- model_prefixes = {
186
- 'gpt-4o': '@GPT-4o',
187
- 'gemini-pro': '@Gemini-PRO',
188
- 'claude-sonnet-3.5': '@Claude-Sonnet-3.5',
189
- 'PythonAgent': '@Python Agent',
190
- 'JavaAgent': '@Java Agent',
191
- 'JavaScriptAgent': '@JavaScript Agent',
192
- 'HTMLAgent': '@HTML Agent',
193
- 'GoogleCloudAgent': '@Google Cloud Agent',
194
- 'AndroidDeveloper': '@Android Developer',
195
- 'SwiftDeveloper': '@Swift Developer',
196
- 'Next.jsAgent': '@Next.js Agent',
197
- 'MongoDBAgent': '@MongoDB Agent',
198
- 'PyTorchAgent': '@PyTorch Agent',
199
- 'ReactAgent': '@React Agent',
200
- 'XcodeAgent': '@Xcode Agent',
201
- 'AngularJSAgent': '@AngularJS Agent',
202
- 'blackboxai-pro': '@BLACKBOXAI-PRO',
203
- 'ImageGeneration': '@Image Generation',
204
- 'Niansuh': '@Niansuh',
205
- }
206
-
207
- model_referers = {
208
- "blackboxai": f"{url}/?model=blackboxai",
209
- "gpt-4o": f"{url}/?model=gpt-4o",
210
- "gemini-pro": f"{url}/?model=gemini-pro",
211
- "claude-sonnet-3.5": f"{url}/?model=claude-sonnet-3.5"
212
- }
213
-
214
- model_aliases = {
215
- "gemini-flash": "gemini-1.5-flash",
216
- "claude-3.5-sonnet": "claude-sonnet-3.5",
217
- "flux": "ImageGeneration",
218
- "niansuh": "Niansuh",
219
- }
220
-
221
- @classmethod
222
- def get_model(cls, model: str) -> Optional[str]:
223
- if model in cls.models:
224
- return model
225
- elif model in cls.userSelectedModel and cls.userSelectedModel[model] in cls.models:
226
- return cls.userSelectedModel[model]
227
- elif model in cls.model_aliases and cls.model_aliases[model] in cls.models:
228
- return cls.model_aliases[model]
229
- else:
230
- return cls.default_model if cls.default_model in cls.models else None
231
-
232
- @classmethod
233
- async def create_async_generator(
234
- cls,
235
- model: str,
236
- messages: List[Dict[str, str]],
237
- proxy: Optional[str] = None,
238
- image: Any = None,
239
- image_name: Optional[str] = None,
240
- webSearchMode: bool = False,
241
- **kwargs
242
- ) -> AsyncGenerator[Any, None]:
243
- model = cls.get_model(model)
244
- if model is None:
245
- logger.error(f"Model {model} is not available.")
246
- raise ModelNotWorkingException(model)
247
-
248
- logger.info(f"Selected model: {model}")
249
-
250
- if not cls.working or model not in cls.models:
251
- logger.error(f"Model {model} is not working or not supported.")
252
- raise ModelNotWorkingException(model)
253
-
254
- headers = {
255
- "accept": "*/*",
256
- "accept-language": "en-US,en;q=0.9",
257
- "cache-control": "no-cache",
258
- "content-type": "application/json",
259
- "origin": cls.url,
260
- "pragma": "no-cache",
261
- "priority": "u=1, i",
262
- "referer": cls.model_referers.get(model, cls.url),
263
- "sec-ch-ua": '"Chromium";v="129", "Not=A?Brand";v="8"',
264
- "sec-ch-ua-mobile": "?0",
265
- "sec-ch-ua-platform": '"Linux"',
266
- "sec-fetch-dest": "empty",
267
- "sec-fetch-mode": "cors",
268
- "sec-fetch-site": "same-origin",
269
- "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
270
- }
271
-
272
- if model in cls.model_prefixes:
273
- prefix = cls.model_prefixes[model]
274
- if not messages[0]['content'].startswith(prefix):
275
- logger.debug(f"Adding prefix '{prefix}' to the first message.")
276
- messages[0]['content'] = f"{prefix} {messages[0]['content']}"
277
-
278
- random_id = ''.join(random.choices(string.ascii_letters + string.digits, k=7))
279
- messages[-1]['id'] = random_id
280
- messages[-1]['role'] = 'user'
281
-
282
- # Don't log the full message content for privacy
283
- logger.debug(f"Generated message ID: {random_id} for model: {model}")
284
-
285
- if image is not None:
286
- messages[-1]['data'] = {
287
- 'fileText': '',
288
- 'imageBase64': to_data_uri(image),
289
- 'title': image_name
290
- }
291
- messages[-1]['content'] = 'FILE:BB\n$#$\n\n$#$\n' + messages[-1]['content']
292
- logger.debug("Image data added to the message.")
293
-
294
- data = {
295
- "messages": messages,
296
- "id": random_id,
297
- "previewToken": None,
298
- "userId": None,
299
- "codeModelMode": True,
300
- "agentMode": {},
301
- "trendingAgentMode": {},
302
- "isMicMode": False,
303
- "userSystemPrompt": None,
304
- "maxTokens": 99999999,
305
- "playgroundTopP": 0.9,
306
- "playgroundTemperature": 0.5,
307
- "isChromeExt": False,
308
- "githubToken": None,
309
- "clickedAnswer2": False,
310
- "clickedAnswer3": False,
311
- "clickedForceWebSearch": False,
312
- "visitFromDelta": False,
313
- "mobileClient": False,
314
- "userSelectedModel": None,
315
- "webSearchMode": webSearchMode,
316
- }
317
-
318
- if model in cls.agentMode:
319
- data["agentMode"] = cls.agentMode[model]
320
- elif model in cls.trendingAgentMode:
321
- data["trendingAgentMode"] = cls.trendingAgentMode[model]
322
- elif model in cls.userSelectedModel:
323
- data["userSelectedModel"] = cls.userSelectedModel[model]
324
- logger.info(f"Sending request to {cls.api_endpoint} with data (excluding messages).")
325
-
326
- timeout = ClientTimeout(total=60) # Set an appropriate timeout
327
- retry_attempts = 10 # Set the number of retry attempts
328
-
329
- for attempt in range(retry_attempts):
330
- try:
331
- async with ClientSession(headers=headers, timeout=timeout) as session:
332
- async with session.post(cls.api_endpoint, json=data, proxy=proxy) as response:
333
- response.raise_for_status()
334
- logger.info(f"Received response with status {response.status}")
335
- if model == 'ImageGeneration':
336
- response_text = await response.text()
337
- url_match = re.search(r'https://storage\.googleapis\.com/[^\s\)]+', response_text)
338
- if url_match:
339
- image_url = url_match.group(0)
340
- logger.info(f"Image URL found.")
341
- yield ImageResponse(image_url, alt=messages[-1]['content'])
342
- else:
343
- logger.error("Image URL not found in the response.")
344
- raise Exception("Image URL not found in the response")
345
- else:
346
- full_response = ""
347
- search_results_json = ""
348
- try:
349
- async for chunk, _ in response.content.iter_chunks():
350
- if chunk:
351
- decoded_chunk = chunk.decode(errors='ignore')
352
- decoded_chunk = re.sub(r'\$@\$v=[^$]+\$@\$', '', decoded_chunk)
353
- if decoded_chunk.strip():
354
- if '$~~~$' in decoded_chunk:
355
- search_results_json += decoded_chunk
356
- else:
357
- full_response += decoded_chunk
358
- yield decoded_chunk
359
- logger.info("Finished streaming response chunks.")
360
- except Exception as e:
361
- logger.exception("Error while iterating over response chunks.")
362
- raise e
363
- if data["webSearchMode"] and search_results_json:
364
- match = re.search(r'\$~~~\$(.*?)\$~~~\$', search_results_json, re.DOTALL)
365
- if match:
366
- try:
367
- search_results = json.loads(match.group(1))
368
- formatted_results = "\n\n**Sources:**\n"
369
- for i, result in enumerate(search_results[:5], 1):
370
- formatted_results += f"{i}. [{result['title']}]({result['link']})\n"
371
- logger.info("Formatted search results.")
372
- yield formatted_results
373
- except json.JSONDecodeError as je:
374
- logger.error("Failed to parse search results JSON.")
375
- raise je
376
- except ClientError as ce:
377
- logger.error(f"Client error occurred: {ce}. Retrying attempt {attempt + 1}/{retry_attempts}")
378
- if attempt == retry_attempts - 1:
379
- raise HTTPException(status_code=502, detail="Error communicating with the external API.")
380
- except asyncio.TimeoutError:
381
- logger.error(f"Request timed out. Retrying attempt {attempt + 1}/{retry_attempts}")
382
- if attempt == retry_attempts - 1:
383
- raise HTTPException(status_code=504, detail="External API request timed out.")
384
- except Exception as e:
385
- logger.error(f"Unexpected error: {e}. Retrying attempt {attempt + 1}/{retry_attempts}")
386
- if attempt == retry_attempts - 1:
387
- raise HTTPException(status_code=500, detail=str(e))
388
-
389
- # FastAPI app setup
390
- app = FastAPI()
391
-
392
- # Add the cleanup task when the app starts
393
- @app.on_event("startup")
394
- async def startup_event():
395
- asyncio.create_task(cleanup_rate_limit_stores())
396
- logger.info("Started rate limit store cleanup task.")
397
-
398
- # Middleware to enhance security and enforce Content-Type for specific endpoints
399
- @app.middleware("http")
400
- async def security_middleware(request: Request, call_next):
401
- client_ip = request.client.host
402
- # Enforce that POST requests to /v1/chat/completions must have Content-Type: application/json
403
- if request.method == "POST" and request.url.path == "/v1/chat/completions":
404
- content_type = request.headers.get("Content-Type")
405
- if content_type != "application/json":
406
- logger.warning(f"Invalid Content-Type from IP: {client_ip} for path: {request.url.path}")
407
- return JSONResponse(
408
- status_code=400,
409
- content={
410
- "error": {
411
- "message": "Content-Type must be application/json",
412
- "type": "invalid_request_error",
413
- "param": None,
414
- "code": None
415
- }
416
- },
417
- )
418
- response = await call_next(request)
419
- return response
420
-
421
- # Request Models
422
- class Message(BaseModel):
423
- role: str
424
- content: Union[str, List[Any]] # content can be a string or a list (for images)
425
-
426
- class ChatRequest(BaseModel):
427
- model: str
428
- messages: List[Message]
429
- temperature: Optional[float] = 1.0
430
- top_p: Optional[float] = 1.0
431
- n: Optional[int] = 1
432
- stream: Optional[bool] = False
433
- stop: Optional[Union[str, List[str]]] = None
434
- max_tokens: Optional[int] = None
435
- presence_penalty: Optional[float] = 0.0
436
- frequency_penalty: Optional[float] = 0.0
437
- logit_bias: Optional[Dict[str, float]] = None
438
- user: Optional[str] = None
439
- webSearchMode: Optional[bool] = False # Custom parameter
440
- image: Optional[str] = None # Base64-encoded image
441
-
442
- class TokenizerRequest(BaseModel):
443
- text: str
444
-
445
- def calculate_estimated_cost(prompt_tokens: int, completion_tokens: int) -> float:
446
- """
447
- Calculate the estimated cost based on the number of tokens.
448
- Replace the pricing below with your actual pricing model.
449
- """
450
- # Example pricing: $0.00000268 per token
451
- cost_per_token = 0.00000268
452
- return round((prompt_tokens + completion_tokens) * cost_per_token, 8)
453
-
454
- def create_response(content: str, model: str, finish_reason: Optional[str] = None) -> Dict[str, Any]:
455
- return {
456
- "id": f"chatcmpl-{uuid.uuid4()}",
457
- "object": "chat.completion",
458
- "created": int(datetime.now().timestamp()),
459
- "model": model,
460
- "choices": [
461
- {
462
- "index": 0,
463
- "message": {
464
- "role": "assistant",
465
- "content": content
466
- },
467
- "finish_reason": finish_reason
468
- }
469
- ],
470
- "usage": None, # To be filled in non-streaming responses
471
- }
472
-
473
- @app.post("/v1/chat/completions", dependencies=[Depends(rate_limiter_per_ip)])
474
- async def chat_completions(request: ChatRequest, req: Request, api_key: str = Depends(get_api_key)):
475
- client_ip = req.client.host
476
- # Redact user messages only for logging purposes
477
- redacted_messages = [{"role": msg.role, "content": "[redacted]"} for msg in request.messages]
478
-
479
- logger.info(f"Received chat completions request from API key: {api_key} | IP: {client_ip} | Model: {request.model} | Messages: {redacted_messages}")
480
-
481
- analysis_result = None
482
- if request.image:
483
- try:
484
- image = decode_base64_image(request.image)
485
- analysis_result = analyze_image(image)
486
- logger.info("Image analysis completed successfully.")
487
- except HTTPException as he:
488
- logger.error(f"Image analysis failed: {he.detail}")
489
- raise he
490
- except Exception as e:
491
- logger.exception("Unexpected error during image analysis.")
492
- raise HTTPException(status_code=500, detail="Image analysis failed.") from e
493
-
494
- # Prepare messages to send to the external API, excluding image data
495
- processed_messages = []
496
- for msg in request.messages:
497
- if isinstance(msg.content, list) and len(msg.content) == 2:
498
- # Assume the second item is image data, skip it
499
- processed_messages.append({
500
- "role": msg.role,
501
- "content": msg.content[0]["text"] # Only include the text part
502
- })
503
- else:
504
- processed_messages.append({
505
- "role": msg.role,
506
- "content": msg.content
507
- })
508
-
509
- # Create a modified ChatRequest without the image
510
- modified_request = ChatRequest(
511
- model=request.model,
512
- messages=[msg for msg in processed_messages],
513
- stream=request.stream,
514
- temperature=request.temperature,
515
- top_p=request.top_p,
516
- max_tokens=request.max_tokens,
517
- presence_penalty=request.presence_penalty,
518
- frequency_penalty=request.frequency_penalty,
519
- logit_bias=request.logit_bias,
520
- user=request.user,
521
- webSearchMode=request.webSearchMode,
522
- image=None # Exclude image from external API
523
- )
524
-
525
- try:
526
- if request.stream:
527
- logger.info("Streaming response")
528
- # **Removed the 'await' keyword here**
529
- streaming_response = Blackbox.create_async_generator(
530
- model=modified_request.model,
531
- messages=[{"role": msg.role, "content": msg.content} for msg in modified_request.messages],
532
- proxy=None,
533
- image=None,
534
- image_name=None,
535
- webSearchMode=modified_request.webSearchMode
536
- )
537
-
538
- # Wrap the streaming generator to include image analysis at the end
539
- async def generate_with_analysis():
540
- assistant_content = ""
541
- try:
542
- async for chunk in streaming_response:
543
- if isinstance(chunk, ImageResponse):
544
- # Handle image responses if necessary
545
- image_markdown = f"![image]({chunk.url})\n"
546
- assistant_content += image_markdown
547
- response_chunk = create_response(image_markdown, modified_request.model, finish_reason=None)
548
- else:
549
- assistant_content += chunk
550
- # Yield the chunk as a partial choice
551
- response_chunk = {
552
- "id": f"chatcmpl-{uuid.uuid4()}",
553
- "object": "chat.completion.chunk",
554
- "created": int(datetime.now().timestamp()),
555
- "model": modified_request.model,
556
- "choices": [
557
- {
558
- "index": 0,
559
- "delta": {"content": chunk, "role": "assistant"},
560
- "finish_reason": None,
561
- }
562
- ],
563
- "usage": None, # Usage can be updated if you track tokens in real-time
564
- }
565
- yield f"data: {json.dumps(response_chunk)}\n\n"
566
-
567
- # After all chunks are sent, send the final message with finish_reason
568
- prompt_tokens = sum(len(msg["content"].split()) for msg in modified_request.messages)
569
- completion_tokens = len(assistant_content.split())
570
- total_tokens = prompt_tokens + completion_tokens
571
- estimated_cost = calculate_estimated_cost(prompt_tokens, completion_tokens)
572
-
573
- final_content = assistant_content
574
- if analysis_result:
575
- final_content += f"\n\n**Image Analysis:** {analysis_result}"
576
-
577
- final_response = {
578
- "id": f"chatcmpl-{uuid.uuid4()}",
579
- "object": "chat.completion",
580
- "created": int(datetime.now().timestamp()),
581
- "model": modified_request.model,
582
- "choices": [
583
- {
584
- "message": {
585
- "role": "assistant",
586
- "content": final_content
587
- },
588
- "finish_reason": "stop",
589
- "index": 0
590
- }
591
- ],
592
- "usage": {
593
- "prompt_tokens": prompt_tokens,
594
- "completion_tokens": completion_tokens,
595
- "total_tokens": total_tokens,
596
- "estimated_cost": estimated_cost
597
- },
598
- }
599
-
600
- yield f"data: {json.dumps(final_response)}\n\n"
601
- yield "data: [DONE]\n\n"
602
- except HTTPException as he:
603
- error_response = {"error": he.detail}
604
- yield f"data: {json.dumps(error_response)}\n\n"
605
- except Exception as e:
606
- logger.exception(f"Error during streaming response generation from IP: {client_ip}.")
607
- error_response = {"error": str(e)}
608
- yield f"data: {json.dumps(error_response)}\n\n"
609
-
610
- return StreamingResponse(generate_with_analysis(), media_type="text/event-stream")
611
- else:
612
- logger.info("Non-streaming response")
613
- # **Removed the 'await' keyword here as well**
614
- streaming_response = Blackbox.create_async_generator(
615
- model=modified_request.model,
616
- messages=[{"role": msg.role, "content": msg.content} for msg in modified_request.messages],
617
- proxy=None,
618
- image=None,
619
- image_name=None,
620
- webSearchMode=modified_request.webSearchMode
621
- )
622
-
623
- response_content = ""
624
- async for chunk in streaming_response:
625
- if isinstance(chunk, ImageResponse):
626
- response_content += f"![image]({chunk.url})\n"
627
- else:
628
- response_content += chunk
629
-
630
- prompt_tokens = sum(len(msg["content"].split()) for msg in modified_request.messages)
631
- completion_tokens = len(response_content.split())
632
- total_tokens = prompt_tokens + completion_tokens
633
- estimated_cost = calculate_estimated_cost(prompt_tokens, completion_tokens)
634
-
635
- if analysis_result:
636
- response_content += f"\n\n**Image Analysis:** {analysis_result}"
637
-
638
- logger.info(f"Completed non-streaming response generation for API key: {api_key} | IP: {client_ip}")
639
-
640
- response = {
641
- "id": f"chatcmpl-{uuid.uuid4()}",
642
- "object": "chat.completion",
643
- "created": int(datetime.now().timestamp()),
644
- "model": modified_request.model,
645
- "choices": [
646
- {
647
- "message": {
648
- "role": "assistant",
649
- "content": response_content
650
- },
651
- "finish_reason": "stop",
652
- "index": 0
653
- }
654
- ],
655
- "usage": {
656
- "prompt_tokens": prompt_tokens,
657
- "completion_tokens": completion_tokens,
658
- "total_tokens": total_tokens,
659
- "estimated_cost": estimated_cost
660
- },
661
- }
662
-
663
- return response
664
- except ModelNotWorkingException as e:
665
- logger.warning(f"Model not working: {e} | IP: {client_ip}")
666
- raise HTTPException(status_code=503, detail=str(e))
667
- except HTTPException as he:
668
- logger.warning(f"HTTPException: {he.detail} | IP: {client_ip}")
669
- raise he
670
- except Exception as e:
671
- logger.exception(f"An unexpected error occurred while processing the chat completions request from IP: {client_ip}.")
672
- raise HTTPException(status_code=500, detail=str(e))
673
-
674
- # Endpoint: POST /v1/tokenizer
675
- @app.post("/v1/tokenizer", dependencies=[Depends(rate_limiter_per_ip)])
676
- async def tokenizer(request: TokenizerRequest, req: Request):
677
- client_ip = req.client.host
678
- text = request.text
679
- token_count = len(text.split())
680
- logger.info(f"Tokenizer requested from IP: {client_ip} | Text length: {len(text)}")
681
- return {"text": text, "tokens": token_count}
682
-
683
- # Endpoint: GET /v1/models
684
- @app.get("/v1/models", dependencies=[Depends(rate_limiter_per_ip)])
685
- async def get_models(req: Request):
686
- client_ip = req.client.host
687
- logger.info(f"Fetching available models from IP: {client_ip}")
688
- return {"data": [{"id": model, "object": "model"} for model in Blackbox.models]}
689
-
690
- # Endpoint: GET /v1/models/{model}/status
691
- @app.get("/v1/models/{model}/status", dependencies=[Depends(rate_limiter_per_ip)])
692
- async def model_status(model: str, req: Request):
693
- client_ip = req.client.host
694
- logger.info(f"Model status requested for '{model}' from IP: {client_ip}")
695
- if model in Blackbox.models:
696
- return {"model": model, "status": "available"}
697
- elif model in Blackbox.model_aliases and Blackbox.model_aliases[model] in Blackbox.models:
698
- actual_model = Blackbox.model_aliases[model]
699
- return {"model": actual_model, "status": "available via alias"}
700
- else:
701
- logger.warning(f"Model not found: {model} from IP: {client_ip}")
702
- raise HTTPException(status_code=404, detail="Model not found")
703
-
704
- # Endpoint: GET /v1/health
705
- @app.get("/v1/health", dependencies=[Depends(rate_limiter_per_ip)])
706
- async def health_check(req: Request):
707
- client_ip = req.client.host
708
- logger.info(f"Health check requested from IP: {client_ip}")
709
- return {"status": "ok"}
710
-
711
- # Endpoint: GET /v1/chat/completions (GET method)
712
- @app.get("/v1/chat/completions")
713
- async def chat_completions_get(req: Request):
714
- client_ip = req.client.host
715
- logger.info(f"GET request made to /v1/chat/completions from IP: {client_ip}, redirecting to 'about:blank'")
716
- return RedirectResponse(url='about:blank')
717
-
718
- # Custom exception handler to match OpenAI's error format
719
- @app.exception_handler(HTTPException)
720
- async def http_exception_handler(request: Request, exc: HTTPException):
721
- client_ip = request.client.host
722
- logger.error(f"HTTPException: {exc.detail} | Path: {request.url.path} | IP: {client_ip}")
723
- return JSONResponse(
724
- status_code=exc.status_code,
725
- content={
726
- "error": {
727
- "message": exc.detail,
728
- "type": "invalid_request_error",
729
- "param": None,
730
- "code": None
731
- }
732
- },
733
- )
734
-
735
- # Image Processing Utilities
736
- def decode_base64_image(base64_str: str) -> Image.Image:
737
- try:
738
- image_data = base64.b64decode(base64_str)
739
- image = Image.open(BytesIO(image_data))
740
- return image
741
- except Exception as e:
742
- logger.error("Failed to decode base64 image.")
743
- raise HTTPException(status_code=400, detail="Invalid base64 image data.") from e
744
-
745
- def analyze_image(image: Image.Image) -> str:
746
- """
747
- Placeholder for image analysis.
748
- Replace this with actual image analysis logic.
749
- """
750
- # Example: Return image size as analysis
751
- width, height = image.size
752
- return f"Image analyzed successfully. Width: {width}px, Height: {height}px."
753
-
754
- # Run the application
755
- if __name__ == "__main__":
756
- import uvicorn
757
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
1
+ import uvicorn
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,9 +1,7 @@
1
- fastapi==0.95.1
2
- uvicorn==0.22.0
3
- httpx==0.24.0
4
- python-multipart==0.0.5
5
- python-dotenv==1.0.0
6
- Pillow==10.0.0
7
- aiohttp==3.8.4
8
- pytesseract==0.3.10
9
- numpy==1.21.0
 
1
+ fastapi
2
+ httpx
3
+ pydantic
4
+ pyinstaller
5
+ python-dotenv
6
+ starlette
7
+ uvicorn