Spaces:
Runtime error
Runtime error
| #!/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()) |