Spaces:
Runtime error
Runtime error
File size: 2,024 Bytes
da55789 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | #!/usr/bin/env python3
import os
import sys
import sqlite3
import requests
from datetime import datetime
# 设置数据库路径和百炼API端点
DB_PATH = "/app/server/data/freeapi.db"
BAILIAN_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/models"
def main():
# 获取百炼的API Key
api_key = os.getenv("BAILIAN_API_KEY")
if not api_key:
print("❌ 错误: 环境变量 BAILIAN_API_KEY 未设置")
return 1
# 调用百炼API获取模型列表
headers = {"Authorization": f"Bearer {api_key}"}
try:
response = requests.get(BAILIAN_URL, headers=headers, timeout=30)
response.raise_for_status()
models_data = response.json()
# 假设返回的JSON结构与 OpenAI 兼容模式一致,即包含一个 'data' 列表
models_list = [item["id"] for item in models_data.get("data", [])]
if not models_list:
print("⚠️ 警告: 未能从API获取到任何模型。")
return 1
except Exception as e:
print(f"❌ 请求百炼API失败: {e}")
return 1
# 连接数据库
try:
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
except Exception as e:
print(f"❌ 无法连接数据库: {e}")
return 1
# 同步模型列表
added_count = 0
for model_id in models_list:
# 检查模型是否已存在
cursor.execute("SELECT 1 FROM models WHERE id = ?", (model_id,))
if not cursor.fetchone():
cursor.execute("INSERT INTO models (id, name, provider_id, enabled, created_at) VALUES (?, ?, ?, 1, ?)",
(model_id, model_id, 1, datetime.utcnow().isoformat()))
added_count += 1
print(f"➕ 添加模型: {model_id}")
else:
print(f"⏭️ 模型已存在: {model_id}")
conn.commit()
conn.close()
print(f"✅ 同步完成。新增模型数量: {added_count}")
return 0
if __name__ == "__main__":
sys.exit(main()) |