Upload 22 files
Browse filesFiles changed (22)
- .dockerignoreAdded+9
- .envAdded+1
- Dockerfile+12-27
- __pycache__/main.cpython-310.pycAdded
- api/__init__.pyAdded
- api/__pycache__/__init__.cpython-310.pycAdded
- api/__pycache__/app.cpython-310.pycAdded
- api/__pycache__/auth.cpython-310.pycAdded
- api/__pycache__/config.cpython-310.pycAdded
- api/__pycache__/logger.cpython-310.pycAdded
- api/__pycache__/models.cpython-310.pycAdded
- api/__pycache__/routes.cpython-310.pycAdded
- api/__pycache__/utils.cpython-310.pycAdded
- api/app.pyAdded+34
- api/auth.pyAdded+10
- api/config.pyAdded+36
- api/logger.pyAdded+20
- api/models.pyAdded+16
- api/routes.pyAdded+62
- api/utils.pyAdded+158
- main.py+5-757
- requirements.txt+7-9
123456789__pycache__*.pyc*.pyo*.pyd*.swp*.swo*.log.env.git1APP_SECRET=123456123456789101112131415161718192021222324252627282930313233# Use the official Python 3.11 slim image as the baseFROM python:3.11-slim# Install Tesseract OCR and its development librariesRUN apt-get update && apt-get install -y --no-install-recommends \tesseract-ocr \libtesseract-dev \&& rm -rf /var/lib/apt/lists/*# Set environment variables to prevent Python from writing .pyc files and to buffer stdout/stderrENV PYTHONDONTWRITEBYTECODE=1ENV PYTHONUNBUFFERED=1# Set the working directory inside the containerWORKDIR /app# Copy the requirements file into the containerCOPY requirements.txt .# Upgrade pip to the latest versionRUN pip install --upgrade pip# Install Python dependencies from requirements.txtRUN pip install -r requirements.txt# Copy the rest of your application code into the containerCOPY . .# Expose port 8000 to the outside worldEXPOSE 8000# Define the default command to run your application using UvicornCMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]123456789101112131415161718# Use an official Python runtime as a parent imageFROM python:3.10-slim# Set the working directory in the containerWORKDIR /app# Copy the current directory contents into the containerCOPY . /app# Install any needed packages specified in requirements.txtRUN pip install --no-cache-dir --upgrade pip && \pip install --no-cache-dir -r requirements.txt# Expose the port that the FastAPI app runs onEXPOSE 8001# Command to run the app with Gunicorn and Uvicorn workersCMD ["gunicorn", "-k", "uvicorn.workers.UvicornWorker", "--workers", "4", "--bind", "0.0.0.0:8001", "main:app"]
12345678910111213141516171819202122232425262728293031323334from fastapi import FastAPI, Request
from starlette.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from api.logger import setup_logger
from api.routes import router # 导入router而不是单独的函数
logger = setup_logger(__name__)
def create_app():
app = FastAPI()
# 配置CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 添加路由
app.include_router(router)
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
logger.error(f"An error occurred: {str(exc)}")
return JSONResponse(
status_code=500,
content={"message": "An internal server error occurred."},
)
return app
app = create_app()12345678910from fastapi import Depends, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from api.config import APP_SECRET
security = HTTPBearer()
def verify_app_secret(credentials: HTTPAuthorizationCredentials = Depends(security)):
if credentials.credentials != APP_SECRET:
raise HTTPException(status_code=403, detail="Invalid APP_SECRET")
return credentials.credentials123456789101112131415161718192021222324252627282930313233343536import os
from dotenv import load_dotenv
load_dotenv()
BASE_URL = "https://www.blackbox.ai"
headers = {
'accept': '*/*',
'accept-language': 'zh-CN,zh;q=0.9',
'origin': 'https://www.blackbox.ai',
'priority': 'u=1, i',
'sec-ch-ua': '"Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
'sec-fetch-dest': 'empty',
'sec-fetch-mode': 'cors',
'sec-fetch-site': 'same-origin',
'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',
}
APP_SECRET = os.getenv("APP_SECRET")
ALLOWED_MODELS = [
{"id": "gpt-4o", "name": "gpt-4o"},
{"id": "gemini-1.5-pro-latest", "name": "gemini-pro"},
{"id": "gemini-1.5-pro", "name": "gemini-pro"},
{"id": "gemini-pro", "name": "gemini-pro"},
{"id": "claude-3-5-sonnet-20240620", "name": "claude-sonnet-3.5"},
{"id": "claude-3-5-sonnet", "name": "claude-sonnet-3.5"},
]
MODEL_MAPPING = {
"gpt-4o":"gpt-4o",
"gemini-1.5-pro-latest": "gemini-pro",
"gemini-1.5-pro":"gemini-1.5-pro",
"gemini-pro":"gemini-pro",
"claude-3-5-sonnet-20240620":"claude-sonnet-3.5",
"claude-3-5-sonnet":"claude-sonnet-3.5",
}1234567891011121314151617181920import logging
def setup_logger(name):
logger = logging.getLogger(name)
if not logger.handlers:
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 控制台处理器
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
# 文件处理器 - 错误级别
# error_file_handler = logging.FileHandler('error.log')
# error_file_handler.setFormatter(formatter)
# error_file_handler.setLevel(logging.ERROR)
# logger.addHandler(error_file_handler)
return logger12345678910111213141516from typing import List, Optional
from pydantic import BaseModel
class Message(BaseModel):
role: str
content: str | list
class ChatRequest(BaseModel):
model: str
messages: List[Message]
stream: Optional[bool] = False
temperature: Optional[float] = 0.7
top_p: Optional[float] = 0.9
max_tokens: Optional[int] = 81921234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162import json
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from fastapi.responses import StreamingResponse
from api.auth import verify_app_secret
from api.config import ALLOWED_MODELS
from api.models import ChatRequest
from api.utils import process_non_streaming_response, process_streaming_response
from api.logger import setup_logger
logger = setup_logger(__name__)
router = APIRouter()
@router.options("/v1/chat/completions")
@router.options("/api/v1/chat/completions")
async def chat_completions_options():
return Response(
status_code=200,
headers={
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
},
)
@router.get("/v1/models")
@router.get("/api/v1/models")
async def list_models():
return {"object": "list", "data": ALLOWED_MODELS}
@router.post("/v1/chat/completions")
@router.post("/api/v1/chat/completions")
async def chat_completions(
request: ChatRequest, app_secret: str = Depends(verify_app_secret)
):
logger.info("Entering chat_completions route")
logger.info(f"Received request: {request}")
logger.info(f"App secret: {app_secret}")
logger.info(f"Received chat completion request for model: {request.model}")
if request.model not in [model["id"] for model in ALLOWED_MODELS]:
raise HTTPException(
status_code=400,
detail=f"Model {request.model} is not allowed. Allowed models are: {', '.join(model['id'] for model in ALLOWED_MODELS)}",
)
if request.stream:
logger.info("Streaming response")
return StreamingResponse(process_streaming_response(request), media_type="text/event-stream")
else:
logger.info("Non-streaming response")
return await process_non_streaming_response(request)
@router.route('/')
@router.route('/healthz')
@router.route('/ready')
@router.route('/alive')
@router.route('/status')
@router.get("/health")
def health_check(request: Request):
return Response(content=json.dumps({"status": "ok"}), media_type="application/json") 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158from datetime import datetime
from http.client import HTTPException
import json
from typing import Any, Dict, Optional
import uuid
import httpx
from api.config import MODEL_MAPPING, headers
from fastapi import Depends, security
from fastapi.security import HTTPAuthorizationCredentials
from api.config import APP_SECRET, BASE_URL
from api.models import ChatRequest
from api.logger import setup_logger
logger = setup_logger(__name__)
def create_chat_completion_data(
content: str, model: str, timestamp: int, finish_reason: Optional[str] = None
) -> Dict[str, Any]:
return {
"id": f"chatcmpl-{uuid.uuid4()}",
"object": "chat.completion.chunk",
"created": timestamp,
"model": model,
"choices": [
{
"index": 0,
"delta": {"content": content, "role": "assistant"},
"finish_reason": finish_reason,
}
],
"usage": None,
}
def verify_app_secret(credentials: HTTPAuthorizationCredentials = Depends(security)):
if credentials.credentials != APP_SECRET:
raise HTTPException(status_code=403, detail="Invalid APP_SECRET")
return credentials.credentials
def message_to_dict(message):
if isinstance(message.content, str):
return {"role": message.role, "content": message.content}
elif isinstance(message.content, list) and len(message.content) == 2:
return {
"role": message.role,
"content": message.content[0]["text"],
"data": {
"imageBase64": message.content[1]["image_url"]["url"],
"fileText": "",
"title": "snapshoot",
},
}
else:
return {"role": message.role, "content": message.content}
async def process_streaming_response(request: ChatRequest):
json_data = {
"messages": [message_to_dict(msg) for msg in request.messages],
"previewToken": None,
"userId": None,
"codeModelMode": True,
"agentMode": {},
"trendingAgentMode": {},
"isMicMode": False,
"userSystemPrompt": None,
"maxTokens": request.max_tokens,
"playgroundTopP": request.top_p,
"playgroundTemperature": request.temperature,
"isChromeExt": False,
"githubToken": None,
"clickedAnswer2": False,
"clickedAnswer3": False,
"clickedForceWebSearch": False,
"visitFromDelta": False,
"mobileClient": False,
"userSelectedModel": MODEL_MAPPING.get(request.model),
}
async with httpx.AsyncClient() as client:
try:
async with client.stream(
"POST",
f"{BASE_URL}/api/chat",
headers=headers,
json=json_data,
timeout=100,
) as response:
response.raise_for_status()
async for line in response.aiter_lines():
timestamp = int(datetime.now().timestamp())
if line:
content = line + "\n"
if content.startswith("$@$v=undefined-rv1$@$"):
yield f"data: {json.dumps(create_chat_completion_data(content[21:], request.model, timestamp))}\n\n"
else:
yield f"data: {json.dumps(create_chat_completion_data(content, request.model, timestamp))}\n\n"
yield f"data: {json.dumps(create_chat_completion_data('', request.model, timestamp, 'stop'))}\n\n"
yield "data: [DONE]\n\n"
except httpx.HTTPStatusError as e:
logger.error(f"HTTP error occurred: {e}")
raise HTTPException(status_code=e.response.status_code, detail=str(e))
except httpx.RequestError as e:
logger.error(f"Error occurred during request: {e}")
raise HTTPException(status_code=500, detail=str(e))
async def process_non_streaming_response(request: ChatRequest):
json_data = {
"messages": [message_to_dict(msg) for msg in request.messages],
"previewToken": None,
"userId": None,
"codeModelMode": True,
"agentMode": {},
"trendingAgentMode": {},
"isMicMode": False,
"userSystemPrompt": None,
"maxTokens": request.max_tokens,
"playgroundTopP": request.top_p,
"playgroundTemperature": request.temperature,
"isChromeExt": False,
"githubToken": None,
"clickedAnswer2": False,
"clickedAnswer3": False,
"clickedForceWebSearch": False,
"visitFromDelta": False,
"mobileClient": False,
"userSelectedModel": MODEL_MAPPING.get(request.model),
}
full_response = ""
async with httpx.AsyncClient() as client:
async with client.stream(
method="POST", url=f"{BASE_URL}/api/chat", headers=headers, json=json_data
) as response:
async for chunk in response.aiter_text():
full_response += chunk
if full_response.startswith("$@$v=undefined-rv1$@$"):
full_response = full_response[21:]
return {
"id": f"chatcmpl-{uuid.uuid4()}",
"object": "chat.completion",
"created": int(datetime.now().timestamp()),
"model": request.model,
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": full_response},
"finish_reason": "stop",
}
],
"usage": None,
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757import osimport reimport randomimport stringimport uuidimport jsonimport loggingimport asyncioimport timefrom collections import defaultdictfrom typing import List, Dict, Any, Optional, AsyncGenerator, Unionfrom datetime import datetimefrom aiohttp import ClientSession, ClientTimeout, ClientErrorfrom fastapi import FastAPI, HTTPException, Request, Depends, Headerfrom fastapi.responses import StreamingResponse, JSONResponse, RedirectResponsefrom pydantic import BaseModelfrom PIL import Imageimport base64from io import BytesIO# Configure logginglogging.basicConfig(level=logging.INFO,format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",handlers=[logging.StreamHandler()])logger = logging.getLogger(__name__)# Load environment variablesAPI_KEYS = os.getenv('API_KEYS', '').split(',') # Comma-separated API keysRATE_LIMIT = int(os.getenv('RATE_LIMIT', '60')) # Requests per minuteAVAILABLE_MODELS = os.getenv('AVAILABLE_MODELS', '') # Comma-separated available modelsif not API_KEYS or API_KEYS == ['']:logger.error("No API keys found. Please set the API_KEYS environment variable.")raise Exception("API_KEYS environment variable not set.")# Process available modelsif AVAILABLE_MODELS:AVAILABLE_MODELS = [model.strip() for model in AVAILABLE_MODELS.split(',') if model.strip()]else:AVAILABLE_MODELS = [] # If empty, all models are available# Simple in-memory rate limiter based solely on IP addressesrate_limit_store = defaultdict(lambda: {"count": 0, "timestamp": time.time()})# Define cleanup interval and windowCLEANUP_INTERVAL = 60 # secondsRATE_LIMIT_WINDOW = 60 # secondsasync def cleanup_rate_limit_stores():"""Periodically cleans up stale entries in the rate_limit_store to prevent memory bloat."""while True:current_time = time.time()ips_to_delete = [ip for ip, value in rate_limit_store.items() if current_time - value["timestamp"] > RATE_LIMIT_WINDOW * 2]for ip in ips_to_delete:del rate_limit_store[ip]logger.debug(f"Cleaned up rate_limit_store for IP: {ip}")await asyncio.sleep(CLEANUP_INTERVAL)async def rate_limiter_per_ip(request: Request):"""Rate limiter that enforces a limit based on the client's IP address."""client_ip = request.client.hostcurrent_time = time.time()# Initialize or update the count and timestampif current_time - rate_limit_store[client_ip]["timestamp"] > RATE_LIMIT_WINDOW:rate_limit_store[client_ip] = {"count": 1, "timestamp": current_time}else:if rate_limit_store[client_ip]["count"] >= RATE_LIMIT:logger.warning(f"Rate limit exceeded for IP address: {client_ip}")raise HTTPException(status_code=429, detail='Rate limit exceeded for IP address | NiansuhAI')rate_limit_store[client_ip]["count"] += 1async def get_api_key(request: Request, authorization: str = Header(None)) -> str:"""Dependency to extract and validate the API key from the Authorization header."""client_ip = request.client.hostif authorization is None or not authorization.startswith('Bearer '):logger.warning(f"Invalid or missing authorization header from IP: {client_ip}")raise HTTPException(status_code=401, detail='Invalid authorization header format')api_key = authorization[7:]if api_key not in API_KEYS:logger.warning(f"Invalid API key attempted: {api_key} from IP: {client_ip}")raise HTTPException(status_code=401, detail='Invalid API key')return api_key# Custom exception for model not workingclass ModelNotWorkingException(Exception):def __init__(self, model: str):self.model = modelself.message = f"The model '{model}' is currently not working. Please try another model or wait for it to be fixed."super().__init__(self.message)# Mock implementations for ImageResponse and to_data_uriclass ImageResponse:def __init__(self, url: str, alt: str):self.url = urlself.alt = altdef to_data_uri(image: Any) -> str:return "data:image/png;base64,..." # Replace with actual base64 dataclass Blackbox:url = "https://www.blackbox.ai"api_endpoint = "https://www.blackbox.ai/api/chat"working = Truesupports_stream = Truesupports_system_message = Truesupports_message_history = Truedefault_model = 'blackboxai'image_models = ['ImageGeneration']models = [default_model,'blackboxai-pro',"llama-3.1-8b",'llama-3.1-70b','llama-3.1-405b','gpt-4o','gemini-pro','gemini-1.5-flash','claude-sonnet-3.5','PythonAgent','JavaAgent','JavaScriptAgent','HTMLAgent','GoogleCloudAgent','AndroidDeveloper','SwiftDeveloper','Next.jsAgent','MongoDBAgent','PyTorchAgent','ReactAgent','XcodeAgent','AngularJSAgent',*image_models,'Niansuh',]# Filter models based on AVAILABLE_MODELSif AVAILABLE_MODELS:models = [model for model in models if model in AVAILABLE_MODELS]agentMode = {'ImageGeneration': {'mode': True, 'id': "ImageGenerationLV45LJp", 'name': "Image Generation"},'Niansuh': {'mode': True, 'id': "NiansuhAIk1HgESy", 'name': "Niansuh"},}trendingAgentMode = {"blackboxai": {},"gemini-1.5-flash": {'mode': True, 'id': 'Gemini'},"llama-3.1-8b": {'mode': True, 'id': "llama-3.1-8b"},'llama-3.1-70b': {'mode': True, 'id': "llama-3.1-70b"},'llama-3.1-405b': {'mode': True, 'id': "llama-3.1-405b"},'blackboxai-pro': {'mode': True, 'id': "BLACKBOXAI-PRO"},'PythonAgent': {'mode': True, 'id': "Python Agent"},'JavaAgent': {'mode': True, 'id': "Java Agent"},'JavaScriptAgent': {'mode': True, 'id': "JavaScript Agent"},'HTMLAgent': {'mode': True, 'id': "HTML Agent"},'GoogleCloudAgent': {'mode': True, 'id': "Google Cloud Agent"},'AndroidDeveloper': {'mode': True, 'id': "Android Developer"},'SwiftDeveloper': {'mode': True, 'id': "Swift Developer"},'Next.jsAgent': {'mode': True, 'id': "Next.js Agent"},'MongoDBAgent': {'mode': True, 'id': "MongoDB Agent"},'PyTorchAgent': {'mode': True, 'id': "PyTorch Agent"},'ReactAgent': {'mode': True, 'id': "React Agent"},'XcodeAgent': {'mode': True, 'id': "Xcode Agent"},'AngularJSAgent': {'mode': True, 'id': "AngularJS Agent"},}userSelectedModel = {"gpt-4o": "gpt-4o","gemini-pro": "gemini-pro",'claude-sonnet-3.5': "claude-sonnet-3.5",}model_prefixes = {'gpt-4o': '@GPT-4o','gemini-pro': '@Gemini-PRO','claude-sonnet-3.5': '@Claude-Sonnet-3.5','PythonAgent': '@Python Agent','JavaAgent': '@Java Agent','JavaScriptAgent': '@JavaScript Agent','HTMLAgent': '@HTML Agent','GoogleCloudAgent': '@Google Cloud Agent','AndroidDeveloper': '@Android Developer','SwiftDeveloper': '@Swift Developer','Next.jsAgent': '@Next.js Agent','MongoDBAgent': '@MongoDB Agent','PyTorchAgent': '@PyTorch Agent','ReactAgent': '@React Agent','XcodeAgent': '@Xcode Agent','AngularJSAgent': '@AngularJS Agent','blackboxai-pro': '@BLACKBOXAI-PRO','ImageGeneration': '@Image Generation','Niansuh': '@Niansuh',}model_referers = {"blackboxai": f"{url}/?model=blackboxai","gpt-4o": f"{url}/?model=gpt-4o","gemini-pro": f"{url}/?model=gemini-pro","claude-sonnet-3.5": f"{url}/?model=claude-sonnet-3.5"}model_aliases = {"gemini-flash": "gemini-1.5-flash","claude-3.5-sonnet": "claude-sonnet-3.5","flux": "ImageGeneration","niansuh": "Niansuh",}@classmethoddef get_model(cls, model: str) -> Optional[str]:if model in cls.models:return modelelif model in cls.userSelectedModel and cls.userSelectedModel[model] in cls.models:return cls.userSelectedModel[model]elif model in cls.model_aliases and cls.model_aliases[model] in cls.models:return cls.model_aliases[model]else:return cls.default_model if cls.default_model in cls.models else None@classmethodasync def create_async_generator(cls,model: str,messages: List[Dict[str, str]],proxy: Optional[str] = None,image: Any = None,image_name: Optional[str] = None,webSearchMode: bool = False,**kwargs) -> AsyncGenerator[Any, None]:model = cls.get_model(model)if model is None:logger.error(f"Model {model} is not available.")raise ModelNotWorkingException(model)logger.info(f"Selected model: {model}")if not cls.working or model not in cls.models:logger.error(f"Model {model} is not working or not supported.")raise ModelNotWorkingException(model)headers = {"accept": "*/*","accept-language": "en-US,en;q=0.9","cache-control": "no-cache","content-type": "application/json","origin": cls.url,"pragma": "no-cache","priority": "u=1, i","referer": cls.model_referers.get(model, cls.url),"sec-ch-ua": '"Chromium";v="129", "Not=A?Brand";v="8"',"sec-ch-ua-mobile": "?0","sec-ch-ua-platform": '"Linux"',"sec-fetch-dest": "empty","sec-fetch-mode": "cors","sec-fetch-site": "same-origin","user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",}if model in cls.model_prefixes:prefix = cls.model_prefixes[model]if not messages[0]['content'].startswith(prefix):logger.debug(f"Adding prefix '{prefix}' to the first message.")messages[0]['content'] = f"{prefix} {messages[0]['content']}"random_id = ''.join(random.choices(string.ascii_letters + string.digits, k=7))messages[-1]['id'] = random_idmessages[-1]['role'] = 'user'# Don't log the full message content for privacylogger.debug(f"Generated message ID: {random_id} for model: {model}")if image is not None:messages[-1]['data'] = {'fileText': '','imageBase64': to_data_uri(image),'title': image_name}messages[-1]['content'] = 'FILE:BB\n$#$\n\n$#$\n' + messages[-1]['content']logger.debug("Image data added to the message.")data = {"messages": messages,"id": random_id,"previewToken": None,"userId": None,"codeModelMode": True,"agentMode": {},"trendingAgentMode": {},"isMicMode": False,"userSystemPrompt": None,"maxTokens": 99999999,"playgroundTopP": 0.9,"playgroundTemperature": 0.5,"isChromeExt": False,"githubToken": None,"clickedAnswer2": False,"clickedAnswer3": False,"clickedForceWebSearch": False,"visitFromDelta": False,"mobileClient": False,"userSelectedModel": None,"webSearchMode": webSearchMode,}if model in cls.agentMode:data["agentMode"] = cls.agentMode[model]elif model in cls.trendingAgentMode:data["trendingAgentMode"] = cls.trendingAgentMode[model]elif model in cls.userSelectedModel:data["userSelectedModel"] = cls.userSelectedModel[model]logger.info(f"Sending request to {cls.api_endpoint} with data (excluding messages).")timeout = ClientTimeout(total=60) # Set an appropriate timeoutretry_attempts = 10 # Set the number of retry attemptsfor attempt in range(retry_attempts):try:async with ClientSession(headers=headers, timeout=timeout) as session:async with session.post(cls.api_endpoint, json=data, proxy=proxy) as response:response.raise_for_status()logger.info(f"Received response with status {response.status}")if model == 'ImageGeneration':response_text = await response.text()url_match = re.search(r'https://storage\.googleapis\.com/[^\s\)]+', response_text)if url_match:image_url = url_match.group(0)logger.info(f"Image URL found.")yield ImageResponse(image_url, alt=messages[-1]['content'])else:logger.error("Image URL not found in the response.")raise Exception("Image URL not found in the response")else:full_response = ""search_results_json = ""try:async for chunk, _ in response.content.iter_chunks():if chunk:decoded_chunk = chunk.decode(errors='ignore')decoded_chunk = re.sub(r'\$@\$v=[^$]+\$@\$', '', decoded_chunk)if decoded_chunk.strip():if '$~~~$' in decoded_chunk:search_results_json += decoded_chunkelse:full_response += decoded_chunkyield decoded_chunklogger.info("Finished streaming response chunks.")except Exception as e:logger.exception("Error while iterating over response chunks.")raise eif data["webSearchMode"] and search_results_json:match = re.search(r'\$~~~\$(.*?)\$~~~\$', search_results_json, re.DOTALL)if match:try:search_results = json.loads(match.group(1))formatted_results = "\n\n**Sources:**\n"for i, result in enumerate(search_results[:5], 1):formatted_results += f"{i}. [{result['title']}]({result['link']})\n"logger.info("Formatted search results.")yield formatted_resultsexcept json.JSONDecodeError as je:logger.error("Failed to parse search results JSON.")raise jeexcept ClientError as ce:logger.error(f"Client error occurred: {ce}. Retrying attempt {attempt + 1}/{retry_attempts}")if attempt == retry_attempts - 1:raise HTTPException(status_code=502, detail="Error communicating with the external API.")except asyncio.TimeoutError:logger.error(f"Request timed out. Retrying attempt {attempt + 1}/{retry_attempts}")if attempt == retry_attempts - 1:raise HTTPException(status_code=504, detail="External API request timed out.")except Exception as e:logger.error(f"Unexpected error: {e}. Retrying attempt {attempt + 1}/{retry_attempts}")if attempt == retry_attempts - 1:raise HTTPException(status_code=500, detail=str(e))# FastAPI app setupapp = FastAPI()# Add the cleanup task when the app starts@app.on_event("startup")async def startup_event():asyncio.create_task(cleanup_rate_limit_stores())logger.info("Started rate limit store cleanup task.")# Middleware to enhance security and enforce Content-Type for specific endpoints@app.middleware("http")async def security_middleware(request: Request, call_next):client_ip = request.client.host# Enforce that POST requests to /v1/chat/completions must have Content-Type: application/jsonif request.method == "POST" and request.url.path == "/v1/chat/completions":content_type = request.headers.get("Content-Type")if content_type != "application/json":logger.warning(f"Invalid Content-Type from IP: {client_ip} for path: {request.url.path}")return JSONResponse(status_code=400,content={"error": {"message": "Content-Type must be application/json","type": "invalid_request_error","param": None,"code": None}},)response = await call_next(request)return response# Request Modelsclass Message(BaseModel):role: strcontent: Union[str, List[Any]] # content can be a string or a list (for images)class ChatRequest(BaseModel):model: strmessages: List[Message]temperature: Optional[float] = 1.0top_p: Optional[float] = 1.0n: Optional[int] = 1stream: Optional[bool] = Falsestop: Optional[Union[str, List[str]]] = Nonemax_tokens: Optional[int] = Nonepresence_penalty: Optional[float] = 0.0frequency_penalty: Optional[float] = 0.0logit_bias: Optional[Dict[str, float]] = Noneuser: Optional[str] = NonewebSearchMode: Optional[bool] = False # Custom parameterimage: Optional[str] = None # Base64-encoded imageclass TokenizerRequest(BaseModel):text: strdef calculate_estimated_cost(prompt_tokens: int, completion_tokens: int) -> float:"""Calculate the estimated cost based on the number of tokens.Replace the pricing below with your actual pricing model."""# Example pricing: $0.00000268 per tokencost_per_token = 0.00000268return round((prompt_tokens + completion_tokens) * cost_per_token, 8)def create_response(content: str, model: str, finish_reason: Optional[str] = None) -> Dict[str, Any]:return {"id": f"chatcmpl-{uuid.uuid4()}","object": "chat.completion","created": int(datetime.now().timestamp()),"model": model,"choices": [{"index": 0,"message": {"role": "assistant","content": content},"finish_reason": finish_reason}],"usage": None, # To be filled in non-streaming responses}@app.post("/v1/chat/completions", dependencies=[Depends(rate_limiter_per_ip)])async def chat_completions(request: ChatRequest, req: Request, api_key: str = Depends(get_api_key)):client_ip = req.client.host# Redact user messages only for logging purposesredacted_messages = [{"role": msg.role, "content": "[redacted]"} for msg in request.messages]logger.info(f"Received chat completions request from API key: {api_key} | IP: {client_ip} | Model: {request.model} | Messages: {redacted_messages}")analysis_result = Noneif request.image:try:image = decode_base64_image(request.image)analysis_result = analyze_image(image)logger.info("Image analysis completed successfully.")except HTTPException as he:logger.error(f"Image analysis failed: {he.detail}")raise heexcept Exception as e:logger.exception("Unexpected error during image analysis.")raise HTTPException(status_code=500, detail="Image analysis failed.") from e# Prepare messages to send to the external API, excluding image dataprocessed_messages = []for msg in request.messages:if isinstance(msg.content, list) and len(msg.content) == 2:# Assume the second item is image data, skip itprocessed_messages.append({"role": msg.role,"content": msg.content[0]["text"] # Only include the text part})else:processed_messages.append({"role": msg.role,"content": msg.content})# Create a modified ChatRequest without the imagemodified_request = ChatRequest(model=request.model,messages=[msg for msg in processed_messages],stream=request.stream,temperature=request.temperature,top_p=request.top_p,max_tokens=request.max_tokens,presence_penalty=request.presence_penalty,frequency_penalty=request.frequency_penalty,logit_bias=request.logit_bias,user=request.user,webSearchMode=request.webSearchMode,image=None # Exclude image from external API)try:if request.stream:logger.info("Streaming response")# **Removed the 'await' keyword here**streaming_response = Blackbox.create_async_generator(model=modified_request.model,messages=[{"role": msg.role, "content": msg.content} for msg in modified_request.messages],proxy=None,image=None,image_name=None,webSearchMode=modified_request.webSearchMode)# Wrap the streaming generator to include image analysis at the endasync def generate_with_analysis():assistant_content = ""try:async for chunk in streaming_response:if isinstance(chunk, ImageResponse):# Handle image responses if necessaryimage_markdown = f"\n"assistant_content += image_markdownresponse_chunk = create_response(image_markdown, modified_request.model, finish_reason=None)else:assistant_content += chunk# Yield the chunk as a partial choiceresponse_chunk = {"id": f"chatcmpl-{uuid.uuid4()}","object": "chat.completion.chunk","created": int(datetime.now().timestamp()),"model": modified_request.model,"choices": [{"index": 0,"delta": {"content": chunk, "role": "assistant"},"finish_reason": None,}],"usage": None, # Usage can be updated if you track tokens in real-time}yield f"data: {json.dumps(response_chunk)}\n\n"# After all chunks are sent, send the final message with finish_reasonprompt_tokens = sum(len(msg["content"].split()) for msg in modified_request.messages)completion_tokens = len(assistant_content.split())total_tokens = prompt_tokens + completion_tokensestimated_cost = calculate_estimated_cost(prompt_tokens, completion_tokens)final_content = assistant_contentif analysis_result:final_content += f"\n\n**Image Analysis:** {analysis_result}"final_response = {"id": f"chatcmpl-{uuid.uuid4()}","object": "chat.completion","created": int(datetime.now().timestamp()),"model": modified_request.model,"choices": [{"message": {"role": "assistant","content": final_content},"finish_reason": "stop","index": 0}],"usage": {"prompt_tokens": prompt_tokens,"completion_tokens": completion_tokens,"total_tokens": total_tokens,"estimated_cost": estimated_cost},}yield f"data: {json.dumps(final_response)}\n\n"yield "data: [DONE]\n\n"except HTTPException as he:error_response = {"error": he.detail}yield f"data: {json.dumps(error_response)}\n\n"except Exception as e:logger.exception(f"Error during streaming response generation from IP: {client_ip}.")error_response = {"error": str(e)}yield f"data: {json.dumps(error_response)}\n\n"return StreamingResponse(generate_with_analysis(), media_type="text/event-stream")else:logger.info("Non-streaming response")# **Removed the 'await' keyword here as well**streaming_response = Blackbox.create_async_generator(model=modified_request.model,messages=[{"role": msg.role, "content": msg.content} for msg in modified_request.messages],proxy=None,image=None,image_name=None,webSearchMode=modified_request.webSearchMode)response_content = ""async for chunk in streaming_response:if isinstance(chunk, ImageResponse):response_content += f"\n"else:response_content += chunkprompt_tokens = sum(len(msg["content"].split()) for msg in modified_request.messages)completion_tokens = len(response_content.split())total_tokens = prompt_tokens + completion_tokensestimated_cost = calculate_estimated_cost(prompt_tokens, completion_tokens)if analysis_result:response_content += f"\n\n**Image Analysis:** {analysis_result}"logger.info(f"Completed non-streaming response generation for API key: {api_key} | IP: {client_ip}")response = {"id": f"chatcmpl-{uuid.uuid4()}","object": "chat.completion","created": int(datetime.now().timestamp()),"model": modified_request.model,"choices": [{"message": {"role": "assistant","content": response_content},"finish_reason": "stop","index": 0}],"usage": {"prompt_tokens": prompt_tokens,"completion_tokens": completion_tokens,"total_tokens": total_tokens,"estimated_cost": estimated_cost},}return responseexcept ModelNotWorkingException as e:logger.warning(f"Model not working: {e} | IP: {client_ip}")raise HTTPException(status_code=503, detail=str(e))except HTTPException as he:logger.warning(f"HTTPException: {he.detail} | IP: {client_ip}")raise heexcept Exception as e:logger.exception(f"An unexpected error occurred while processing the chat completions request from IP: {client_ip}.")raise HTTPException(status_code=500, detail=str(e))# Endpoint: POST /v1/tokenizer@app.post("/v1/tokenizer", dependencies=[Depends(rate_limiter_per_ip)])async def tokenizer(request: TokenizerRequest, req: Request):client_ip = req.client.hosttext = request.texttoken_count = len(text.split())logger.info(f"Tokenizer requested from IP: {client_ip} | Text length: {len(text)}")return {"text": text, "tokens": token_count}# Endpoint: GET /v1/models@app.get("/v1/models", dependencies=[Depends(rate_limiter_per_ip)])async def get_models(req: Request):client_ip = req.client.hostlogger.info(f"Fetching available models from IP: {client_ip}")return {"data": [{"id": model, "object": "model"} for model in Blackbox.models]}# Endpoint: GET /v1/models/{model}/status@app.get("/v1/models/{model}/status", dependencies=[Depends(rate_limiter_per_ip)])async def model_status(model: str, req: Request):client_ip = req.client.hostlogger.info(f"Model status requested for '{model}' from IP: {client_ip}")if model in Blackbox.models:return {"model": model, "status": "available"}elif model in Blackbox.model_aliases and Blackbox.model_aliases[model] in Blackbox.models:actual_model = Blackbox.model_aliases[model]return {"model": actual_model, "status": "available via alias"}else:logger.warning(f"Model not found: {model} from IP: {client_ip}")raise HTTPException(status_code=404, detail="Model not found")# Endpoint: GET /v1/health@app.get("/v1/health", dependencies=[Depends(rate_limiter_per_ip)])async def health_check(req: Request):client_ip = req.client.hostlogger.info(f"Health check requested from IP: {client_ip}")return {"status": "ok"}# Endpoint: GET /v1/chat/completions (GET method)@app.get("/v1/chat/completions")async def chat_completions_get(req: Request):client_ip = req.client.hostlogger.info(f"GET request made to /v1/chat/completions from IP: {client_ip}, redirecting to 'about:blank'")return RedirectResponse(url='about:blank')# Custom exception handler to match OpenAI's error format@app.exception_handler(HTTPException)async def http_exception_handler(request: Request, exc: HTTPException):client_ip = request.client.hostlogger.error(f"HTTPException: {exc.detail} | Path: {request.url.path} | IP: {client_ip}")return JSONResponse(status_code=exc.status_code,content={"error": {"message": exc.detail,"type": "invalid_request_error","param": None,"code": None}},)# Image Processing Utilitiesdef decode_base64_image(base64_str: str) -> Image.Image:try:image_data = base64.b64decode(base64_str)image = Image.open(BytesIO(image_data))return imageexcept Exception as e:logger.error("Failed to decode base64 image.")raise HTTPException(status_code=400, detail="Invalid base64 image data.") from edef analyze_image(image: Image.Image) -> str:"""Placeholder for image analysis.Replace this with actual image analysis logic."""# Example: Return image size as analysiswidth, height = image.sizereturn f"Image analyzed successfully. Width: {width}px, Height: {height}px."# Run the applicationif __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=8000)12345import uvicornfrom api.app import appif __name__ == "__main__":uvicorn.run(app, host="0.0.0.0", port=8001)
123456789fastapi==0.95.1uvicorn==0.22.0httpx==0.24.0python-multipart==0.0.5python-dotenv==1.0.0Pillow==10.0.0aiohttp==3.8.4pytesseract==0.3.10numpy==1.21.01234567fastapihttpxpydanticpyinstallerpython-dotenvstarletteuvicorn
.dockerignoreAdded+9
.envAdded+1
Dockerfile+12-27
__pycache__/main.cpython-310.pycAdded
api/__init__.pyAdded
api/__pycache__/__init__.cpython-310.pycAdded
api/__pycache__/app.cpython-310.pycAdded
api/__pycache__/auth.cpython-310.pycAdded
api/__pycache__/config.cpython-310.pycAdded
api/__pycache__/logger.cpython-310.pycAdded
api/__pycache__/models.cpython-310.pycAdded
api/__pycache__/routes.cpython-310.pycAdded
api/__pycache__/utils.cpython-310.pycAdded
api/app.pyAdded+34
api/auth.pyAdded+10
api/config.pyAdded+36
api/logger.pyAdded+20
api/models.pyAdded+16
api/routes.pyAdded+62
api/utils.pyAdded+158
main.py+5-757
requirements.txt+7-9