Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -12,9 +12,47 @@ logger = logging.getLogger(__name__)
|
|
| 12 |
# 加载环境变量
|
| 13 |
load_dotenv()
|
| 14 |
|
|
|
|
|
|
|
| 15 |
# API配置
|
| 16 |
-
|
| 17 |
-
API_KEY = os.getenv("API_KEY")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
def format_message(role, content):
|
| 20 |
return {"role": role, "content": content}
|
|
|
|
| 12 |
# 加载环境变量
|
| 13 |
load_dotenv()
|
| 14 |
|
| 15 |
+
|
| 16 |
+
|
| 17 |
# API配置
|
| 18 |
+
BASE_URL = os.getenv("API_URL", "").rstrip('/') # 移除末尾的斜杠
|
| 19 |
+
API_KEY = os.getenv("API_KEY", "")
|
| 20 |
+
|
| 21 |
+
# 构建完整的API URL
|
| 22 |
+
API_URL = f"{BASE_URL}/v1/chat/completions"
|
| 23 |
+
|
| 24 |
+
# 验证环境变量
|
| 25 |
+
if not BASE_URL or not API_KEY:
|
| 26 |
+
raise ValueError("""
|
| 27 |
+
请确保设置了必要的环境变量:
|
| 28 |
+
- API_URL: API基础地址 (例如: https://api.example.com)
|
| 29 |
+
- API_KEY: API密钥
|
| 30 |
+
可以在Hugging Face Space的Settings -> Repository Secrets中设置这些变量
|
| 31 |
+
""")
|
| 32 |
+
|
| 33 |
+
class ChatBot:
|
| 34 |
+
def __init__(self):
|
| 35 |
+
# 修正 headers 的设置
|
| 36 |
+
self.headers = {
|
| 37 |
+
"Authorization": f"Bearer {API_KEY}", # 正确使用 API_KEY
|
| 38 |
+
"Content-Type": "application/json",
|
| 39 |
+
"Accept": "text/event-stream"
|
| 40 |
+
}
|
| 41 |
+
self.verify_api_config()
|
| 42 |
+
|
| 43 |
+
def verify_api_config(self):
|
| 44 |
+
try:
|
| 45 |
+
# 使用 OPTIONS 请求来验证API端点
|
| 46 |
+
response = requests.options(API_URL, timeout=5)
|
| 47 |
+
logger.info(f"API endpoint: {API_URL}")
|
| 48 |
+
logger.info(f"API headers: {self.headers}")
|
| 49 |
+
|
| 50 |
+
if response.status_code >= 400:
|
| 51 |
+
logger.error(f"API配置可能有误: {response.status_code}")
|
| 52 |
+
logger.error(f"API响应: {response.text[:200]}")
|
| 53 |
+
except Exception as e:
|
| 54 |
+
logger.error(f"API连接测试失败: {str(e)}")
|
| 55 |
+
|
| 56 |
|
| 57 |
def format_message(role, content):
|
| 58 |
return {"role": role, "content": content}
|