Spaces:
Paused
Paused
Upload 2 files
Browse files58 unmodified lines59606162636412 unmodified lines777879808182147 unmodified lines23023123223323423523652 unmodified lines28929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538649 unmodified lines43643743843944044144244344444544644744844945045160 unmodified lines51251351451551651751851952052152252352452552652752852953053153253353415 unmodified lines55055155255355455555613 unmodified lines57057157257357457557678 unmodified lines65565665765865966066158 unmodified lines{"category": "HARM_CATEGORY_DANGEROUS_CONTENT","threshold": "BLOCK_NONE"}]safety_settings_g2 = [12 unmodified lines{"category": "HARM_CATEGORY_DANGEROUS_CONTENT","threshold": "OFF"}]@dataclass147 unmodified lines@app.route('/')def index():main_content = "Moonfanz Reminiproxy v2.3.3 2025-01-14"html_template = """<!DOCTYPE html><html>52 unmodified linesrequest_counts[api_key] = deque()request_counts[api_key].append(now)def handle_api_error(error, attempt):if attempt > MAX_RETRIES:logger.error(f"{MAX_RETRIES} 次尝试后仍然失败,请修改预设或输入")return 0, jsonify({'error': {'message': f"{MAX_RETRIES} 次尝试后仍然失败,请修改预设或输入",'type': 'max_retries_exceeded'}})if isinstance(error, InvalidArgument):logger.error(f"{current_api_key[:8]} → 无效,可能已过期或被删除")key_manager.blacklist_key(current_api_key)switch_api_key()return 0, Noneelif isinstance(error, ResourceExhausted):delay = min(RETRY_DELAY * (2 ** attempt), MAX_RETRY_DELAY)logger.warning(f"{current_api_key[:8]} ... {current_api_key[-3:]} → 429 官方资源耗尽 → {delay} 秒后重试...")key_manager.blacklist_key(current_api_key)switch_api_key()time.sleep(delay)return 0, Noneelif isinstance(error, Aborted):delay = min(RETRY_DELAY * (2 ** attempt), MAX_RETRY_DELAY)logger.warning(f"{current_api_key[:8]} ... {current_api_key[-3:]} → 操作被中止 → {delay} 秒后重试...")switch_api_key()time.sleep(delay)return 0, Noneelif isinstance(error, InternalServerError):delay = min(RETRY_DELAY * (2 ** attempt), MAX_RETRY_DELAY)logger.warning(f"{current_api_key[:8]} ... {current_api_key[-3:]} → 500 服务器内部错误 → {delay} 秒后重试...")switch_api_key()time.sleep(delay)return 0, Noneelif isinstance(error, ServiceUnavailable):delay = min(RETRY_DELAY * (2 ** attempt), MAX_RETRY_DELAY)logger.warning(f"{current_api_key[:8]} ... {current_api_key[-3:]} → 503 服务不可用 → {delay} 秒后重试...")switch_api_key()time.sleep(delay)return 0, Noneelif isinstance(error, PermissionDenied):logger.error(f"{current_api_key[:8]} ... {current_api_key[-3:]} → 403 权限被拒绝,该 API KEY 可能已经被官方封禁")key_manager.blacklist_key(current_api_key)switch_api_key()return 0, Noneelif isinstance(error, StopCandidateException):logger.warning(f"AI输出内容被Gemini官方阻挡,代理没有得到有效回复")switch_api_key()return 0, Noneelif isinstance(error, BlockedPromptException):try:full_reason_str = str(error.args[0])logger.error(f"{full_reason_str}")if "block_reason:" in full_reason_str:start_index = full_reason_str.find("block_reason:") + len("block_reason:")block_reason_str = full_reason_str[start_index:].strip()if block_reason_str == "SAFETY":logger.warning(f"用户输入因安全原因被阻止")return 1, Noneelif block_reason_str == "BLOCKLIST":logger.warning(f"用户输入因包含阻止列表中的术语而被阻止")return 1, Noneelif block_reason_str == "PROHIBITED_CONTENT":logger.warning(f"用户输入因包含禁止内容而被阻止")return 1, Noneelif block_reason_str == "OTHER":logger.warning(f"用户输入因未知原因被阻止")return 1, Noneelse:logger.warning(f"用户输入被阻止,原因: {block_reason_str}")return 1, Noneelse:logger.warning(f"用户输入被阻止,原因: {full_reason_str}")return 1, Noneexcept (IndexError, AttributeError) as e:logger.error(f"获取提示原因失败↙\n{e}")logger.error(f"提示被阻止↙\n{error}")return 2, Noneelse:logger.error(f"该模型还未发布,暂时不可用,请更换模型或未来一段时间再试")logger.error(f"证明↙\n{error}")return 2, None@app.route('/hf/v1/chat/completions', methods=['POST'])def chat_completions():49 unmodified linestry:response = requests.post(url, headers=headers, json=data, stream=True)response.raise_for_status()if stream:return 1, responseelse:return 1, ResponseWrapper(response.json())except requests.exceptions.RequestException as e:return handle_api_error(e, attempt)except (StopCandidateException, BlockedPromptException) as e:return handle_api_error(e, attempt)def generate_stream(response):logger.info(f"流式开始 →")60 unmodified linesif success == 0:continueelif success == 2:logger.error(f"{model} 很可能暂时不可用,请更换模型或未来���段时间再试")response = {'error': {'message': f'{model} 很可能暂时不可用,请更换模型或未来一段时间再试','type': 'internal_server_error'}}return jsonify(response), 503if stream:return Response(stream_with_context(generate_stream(response)),mimetype='text/event-stream')else:try:text_content = response.textprompt_tokens = response.prompt_token_count15 unmodified linescontinueresponse_data = {'id': 'chatcmpl-xxxxxxxxxxxx','object': 'chat.completion','created': int(datetime.now().timestamp()),'model': model,13 unmodified lines}logger.info(f"200!")return jsonify(response_data)else:logger.error(f"{MAX_RETRIES} 次尝试均失败,请调整配置,或等待官方恢复,或向Moonfanz反馈")response = {78 unmodified linesscheduler.add_job(keep_alive, 'interval', hours=12)scheduler.start()logger.info(f"Reminiproxy v2.3.3 启动")logger.info(f"最大尝试次数/MaxRetries: {MAX_RETRIES}")logger.info(f"最大请求次数/MaxRequests: {MAX_REQUESTS}")logger.info(f"请求限额窗口/LimitWindow: {LIMIT_WINDOW} 秒")58 unmodified lines5960616263646566676812 unmodified lines81828384858687888990147 unmodified lines23823924024124224324452 unmodified lines29729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739849 unmodified lines44844945045145245345445545645745845946046160 unmodified lines52252352452552652752852953053153253353453515 unmodified lines55155255355455555655713 unmodified lines57157257357457557657757857958058158258358458558658778 unmodified lines66666766866967067167258 unmodified lines{"category": "HARM_CATEGORY_DANGEROUS_CONTENT","threshold": "BLOCK_NONE"},{"category": 'HARM_CATEGORY_CIVIC_INTEGRITY',"threshold": 'BLOCK_NONE'}]safety_settings_g2 = [12 unmodified lines{"category": "HARM_CATEGORY_DANGEROUS_CONTENT","threshold": "OFF"},{"category": 'HARM_CATEGORY_CIVIC_INTEGRITY',"threshold": 'OFF'}]@dataclass147 unmodified lines@app.route('/')def index():main_content = "Moonfanz Reminiproxy v2.3.4 2025-01-14"html_template = """<!DOCTYPE html><html>52 unmodified linesrequest_counts[api_key] = deque()request_counts[api_key].append(now)def handle_api_error(error, attempt, current_api_key):if attempt > MAX_RETRIES:logger.error(f"{MAX_RETRIES} 次尝试后仍然失败,请修改预设或输入")return 0, jsonify({'error': {'message': f"{MAX_RETRIES} 次尝试后仍然失败,请修改预设或输入",'type': 'max_retries_exceeded'}})if isinstance(error, requests.exceptions.HTTPError):status_code = error.response.status_codeif status_code == 400:try:error_data = error.response.json()if 'error' in error_data:if error_data['error'].get('code') == "invalid_argument":logger.error(f"{current_api_key[:8]} ... {current_api_key[-3:]} → 无效,可能已过期或被删除")key_manager.blacklist_key(current_api_key)switch_api_key()return 0, Noneerror_message = error_data['error'].get('message', 'Bad Request')error_type = error_data['error'].get('type', 'invalid_request_error')logger.warning(f"400 Bad Request: {error_message}")return 1, jsonify({'error': {'message': error_message, 'type': error_type}})except ValueError:logger.warning("400 Bad Request (Unable to parse error response)")return 1, jsonify({'error': {'message': 'Bad Request', 'type': 'invalid_request_error'}})elif status_code == 429:delay = min(RETRY_DELAY * (2 ** attempt), MAX_RETRY_DELAY)logger.warning(f"{current_api_key[:8]} ... {current_api_key[-3:]} → 429 官方资源耗尽 → {delay} 秒后重试...")key_manager.blacklist_key(current_api_key)switch_api_key()time.sleep(delay)return 0, Noneelif status_code == 403:logger.error(f"{current_api_key[:8]} ... {current_api_key[-3:]} → 403 权限被拒绝,该 API KEY 可能已经被官方封禁")key_manager.blacklist_key(current_api_key)switch_api_key()return 0, Noneelif status_code == 500:delay = min(RETRY_DELAY * (2 ** attempt), MAX_RETRY_DELAY)logger.warning(f"{current_api_key[:8]} ... {current_api_key[-3:]} → 500 服务器内部错误 → {delay} 秒后重试...")switch_api_key()time.sleep(delay)return 0, Noneelif status_code == 503:delay = min(RETRY_DELAY * (2 ** attempt), MAX_RETRY_DELAY)logger.warning(f"{current_api_key[:8]} ... {current_api_key[-3:]} → 503 ��务不可用 → {delay} 秒后重试...")switch_api_key()time.sleep(delay)return 0, Noneelse:delay = min(RETRY_DELAY * (2 ** attempt), MAX_RETRY_DELAY)logger.warning(f"{current_api_key[:8]} ... {current_api_key[-3:]} → {status_code} 未知错误 → {delay} 秒后重试...")switch_api_key()time.sleep(delay)return 0, Noneelif isinstance(error, requests.exceptions.ConnectionError):delay = min(RETRY_DELAY * (2 ** attempt), MAX_RETRY_DELAY)logger.warning(f"连接错误 → {delay} 秒后重试...")time.sleep(delay)return 0, Noneelif isinstance(error, requests.exceptions.Timeout):delay = min(RETRY_DELAY * (2 ** attempt), MAX_RETRY_DELAY)logger.warning(f"请求超时 → {delay} 秒后重试...")time.sleep(delay)return 0, Noneelse:logger.error(f"发生未知错误: {error}")return 0, jsonify({'error': {'message': f"发生未知错误: {error}",'type': 'unknown_error'}})@app.route('/hf/v1/chat/completions', methods=['POST'])def chat_completions():49 unmodified linestry:response = requests.post(url, headers=headers, json=data, stream=True)response.raise_for_status() # This will raise an HTTPError for bad responsesif stream:return 1, responseelse:return 1, ResponseWrapper(response.json())except requests.exceptions.RequestException as e:return handle_api_error(e, attempt, current_api_key)def generate_stream(response):logger.info(f"流式开始 →")60 unmodified linesif success == 0:continueelif success == 1 and response is None:continueelif success == 1 and isinstance(response, Response):return Response(stream_with_context(generate_stream(response)),mimetype='text/event-stream')elif success == 1 and isinstance(response, ResponseWrapper):try:text_content = response.textprompt_tokens = response.prompt_token_count15 unmodified linescontinueresponse_data = {'id': 'chatcmpl-xxxxxxxxxxxx','object': 'chat.completion','created': int(datetime.now().timestamp()),'model': model,13 unmodified lines}logger.info(f"200!")return jsonify(response_data)elif success == 1 and isinstance(response, tuple):return response[1], response[0]elif success == 2:logger.error(f"{model} 很可能暂时不可用,请更换模型或未来一段时间再试")response = {'error': {'message': f'{model} 很可能暂时不可用,请更换模型或未来一段时间再试','type': 'internal_server_error'}}return jsonify(response), 503else:logger.error(f"{MAX_RETRIES} 次尝试均失败,请调整配置,或等待官方恢复,或向Moonfanz反馈")response = {78 unmodified linesscheduler.add_job(keep_alive, 'interval', hours=12)scheduler.start()logger.info(f"Reminiproxy v2.3.4 启动")logger.info(f"最大尝试次数/MaxRetries: {MAX_RETRIES}")logger.info(f"最大请求次数/MaxRequests: {MAX_REQUESTS}")logger.info(f"请求限额窗口/LimitWindow: {LIMIT_WINDOW} 秒")
app.py+110-99