mirror of
https://github.com/lanqian528/chat2api.git
synced 2026-06-13 21:02:46 +08:00
fix Logger.py
This commit is contained in:
parent
440be6c656
commit
8d339e6ba8
18
app.py
18
app.py
@ -1,6 +1,4 @@
|
||||
from typing import AsyncGenerator
|
||||
|
||||
from fastapi import FastAPI, Request, Depends
|
||||
from fastapi import FastAPI, Request, Depends, HTTPException
|
||||
from fastapi.responses import StreamingResponse, JSONResponse
|
||||
|
||||
from chatgpt.ChatService import ChatService
|
||||
@ -14,13 +12,13 @@ app = FastAPI()
|
||||
async def send_conversation(request: Request, token=Depends(verify_token)):
|
||||
access_token = None
|
||||
if not token:
|
||||
return JSONResponse({"error": "Not authenticated"}, status_code=401)
|
||||
elif token.startswith("ey"):
|
||||
raise HTTPException(status_code=401, detail={"error": "Not authenticated"})
|
||||
elif token.startswith("eyJhb"):
|
||||
access_token = token
|
||||
try:
|
||||
request_data = await request.json()
|
||||
except Exception:
|
||||
return JSONResponse({"error": "Invalid JSON body"}, status_code=400)
|
||||
raise HTTPException(status_code=400, detail={"error": "Invalid JSON body"})
|
||||
|
||||
async def to_send_conversation(request_data):
|
||||
chat_service = ChatService(request_data, access_token)
|
||||
@ -30,7 +28,7 @@ async def send_conversation(request: Request, token=Depends(verify_token)):
|
||||
chat_service = await async_retry(to_send_conversation, request_data)
|
||||
chat_service.prepare_send_conversation()
|
||||
stream = request_data.get("stream", False)
|
||||
if stream:
|
||||
if stream is True:
|
||||
return StreamingResponse(await chat_service.send_conversation_for_stream(), media_type="text/event-stream")
|
||||
else:
|
||||
return JSONResponse(await chat_service.send_conversation(), media_type="application/json")
|
||||
@ -38,5 +36,9 @@ async def send_conversation(request: Request, token=Depends(verify_token)):
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
log_config = uvicorn.config.LOGGING_CONFIG
|
||||
default_format = "%(asctime)s | %(levelname)s | %(message)s"
|
||||
access_format = r'%(asctime)s | %(levelname)s | %(client_addr)s: %(request_line)s %(status_code)s'
|
||||
log_config["formatters"]["default"]["fmt"] = default_format
|
||||
log_config["formatters"]["access"]["fmt"] = access_format
|
||||
uvicorn.run("app:app", host="0.0.0.0", port=5005)
|
||||
|
||||
@ -1,12 +1,12 @@
|
||||
import logging
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(levelname)s | %(message)s')
|
||||
|
||||
|
||||
class Logger:
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s | %(levelname)s | %(message)s')
|
||||
|
||||
@staticmethod
|
||||
def info(message):
|
||||
logging.info("\033[0;32m" + str(message) + "\033[0m")
|
||||
logging.info(str(message))
|
||||
|
||||
@staticmethod
|
||||
def warning(message):
|
||||
@ -19,3 +19,6 @@ class Logger:
|
||||
@staticmethod
|
||||
def debug(message):
|
||||
logging.debug("\033[0;37m" + str(message) + "\033[0m")
|
||||
|
||||
|
||||
logger = Logger()
|
||||
@ -2,15 +2,25 @@ import os
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
from utils.Logger import Logger
|
||||
from utils.Logger import logger
|
||||
|
||||
load_dotenv()
|
||||
|
||||
|
||||
def is_true(stream):
|
||||
if isinstance(stream, str): # 检查是否为字符串
|
||||
return stream.lower() in ['true', '1', 't', 'y', 'yes']
|
||||
elif isinstance(stream, int): # 检查是否为整数
|
||||
return stream == 1
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
authorization = os.getenv('AUTHORIZATION', '').replace(' ', '')
|
||||
free35_base_url = os.getenv('FREE35_BASE_URL', 'https://chat.openai.com/backend-anon').replace(' ', '')
|
||||
chatgpt_base_url = os.getenv('CHATGPT_BASE_URL', 'https://chat.openai.com/backend-api').replace(' ', '')
|
||||
history_disabled_str = os.getenv('HISTORY_DISABLED', 'false').replace(' ', '')
|
||||
history_disabled = history_disabled_str.lower() in ['true', '1', 't', 'y', 'yes']
|
||||
history_disabled = is_true(history_disabled_str)
|
||||
proxy_url = os.getenv('PROXY_URL', '').replace(' ', '')
|
||||
retry_times = int(os.getenv('RETRY_TIMES', 3))
|
||||
|
||||
@ -19,9 +29,9 @@ free35_base_url_list = free35_base_url.split(',') if free35_base_url else [free3
|
||||
chatgpt_base_url_list = chatgpt_base_url.split(',') if chatgpt_base_url else [chatgpt_base_url]
|
||||
proxy_url_list = proxy_url.split(',') if proxy_url else [proxy_url]
|
||||
|
||||
Logger.info("Environment variables (no AUTHORIZATION):")
|
||||
Logger.info("FREE35_BASE_URL: " + str(free35_base_url_list))
|
||||
Logger.info("CHATGPT_BASE_URL: " + str(chatgpt_base_url_list))
|
||||
Logger.info("PROXY_URL: " + str(proxy_url_list))
|
||||
Logger.info("HISTORY_DISABLED: " + str(history_disabled))
|
||||
Logger.info("RETRY_TIMES: " + str(retry_times))
|
||||
logger.info("Environment variables (no AUTHORIZATION):")
|
||||
logger.info("FREE35_BASE_URL: " + str(free35_base_url_list))
|
||||
logger.info("CHATGPT_BASE_URL: " + str(chatgpt_base_url_list))
|
||||
logger.info("PROXY_URL: " + str(proxy_url_list))
|
||||
logger.info("HISTORY_DISABLED: " + str(history_disabled))
|
||||
logger.info("RETRY_TIMES: " + str(retry_times))
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
from utils.Logger import Logger
|
||||
from utils.Logger import logger
|
||||
from fastapi import HTTPException
|
||||
|
||||
from utils.config import retry_times
|
||||
@ -12,7 +12,7 @@ async def async_retry(func, *args, max_retries=retry_times, **kwargs):
|
||||
except HTTPException as e:
|
||||
if attempt == max_retries:
|
||||
raise HTTPException(status_code=e.status_code, detail=e.detail)
|
||||
Logger.info(f"Retry {attempt + 1} failed with status code {e.status_code}. Retrying...")
|
||||
logger.info(f"Retry {attempt + 1} failed with status code {e.status_code}. Retrying...")
|
||||
|
||||
|
||||
def retry(func, *args, max_retries=retry_times, **kwargs):
|
||||
@ -23,4 +23,4 @@ def retry(func, *args, max_retries=retry_times, **kwargs):
|
||||
except HTTPException as e:
|
||||
if attempt == max_retries:
|
||||
raise HTTPException(status_code=e.status_code, detail=e.detail)
|
||||
Logger.info(f"Attempt {attempt + 1} failed with status code {e.status_code}. Retrying...")
|
||||
logger.info(f"Attempt {attempt + 1} failed with status code {e.status_code}. Retrying...")
|
||||
|
||||
Loading…
Reference in New Issue
Block a user