Skip to main content

ModelScope API Python SDK

PyPI version License Python 3.11+

一个异步类型安全的 Python SDK,用于调用 ModelScope 开放 API

它提供了直观的对象化接口,覆盖了合集、创空间、魔粒、用户等核心模块,让您能以 Pythonic 的方式与 ModelScope 平台交互。

✨ 特性

  • 🚀 全异步 – 基于 httpx.AsyncClient,支持高并发请求。
  • 🧩 模块化设计 – 按业务领域拆分:UserMagicubeStudioCollection 等。
  • 📦 类型安全 – 使用 Pydantic 数据模型,提供 IDE 自动补全和校验。
  • 🔐 自动认证 – 通过环境变量或构造参数传入 API Token,自动注入请求头。
  • 🛠️ 开箱即用 – 支持 .env 配置,内置随机 UA 伪装,简化开发。

📦 安装

pip install modelscope-api

或直接从源码安装:

git clone https://github.com/Jerry-Wu-GitHub/modelscope-api.git
cd modelscope-api
pip install -e .

🚀 快速开始

1. 获取 API Token

访问 ModelScope 个人设置 生成您的 MODELSCOPE_API_TOKEN

2. 配置环境变量(推荐)

在项目根目录创建 .env 文件:

MODELSCOPE_API_TOKEN=your_token_here

也可以直接在代码中传入:

from modelscope_api import ModelScopeClient

client = ModelScopeClient(api_key="your_token_here")

3. 基础用法

import asyncio
from modelscope_api import ModelScopeClient

async def main():
    async with ModelScopeClient() as client:
        # 获取当前用户信息
        user_info = await client.user.get_current_user_info()
        print(f"当前用户: {user_info.username}")

        # 查询魔粒余额
        balance = await client.magicube.query_magicube_balance()
        print(f"可用魔粒: {balance.available_balance}")

        # 搜索创空间
        studios = await client.studio.search_studio_infos(search="chatbot", owner="iic")
        for studio in studios:
            print(f"- {studio.display_name} ({studio.id})")

if __name__ == "__main__":
    asyncio.run(main())

📖 API 概览

SDK 的所有功能通过 ModelScopeClient 聚合,您可以通过其属性访问各子客户端:

子客户端 说明 主要方法
client.user 用户信息 get_current_user_info()
client.magicube 魔粒(积分) query_magicube_balance()
client.studio 创空间管理 search_studio_infos(), create_studio(), get_studio()
client.collection 合集管理 search_collection_infos(), create_collection(), get_collection()

每个子客户端返回的数据均为 Pydantic 模型,可直接访问属性。

详细示例:操作创空间

async def studio_example(client):
    # 创建创空间
    studio = await client.studio.create_studio(
        repo_name="my-awesome-space",
        display_name="我的炫酷空间",
        visibility="public",
        sdk_type="gradio",
        hardware="platform/2v-cpu-16g-mem"
    )
    print(f"创建成功: {studio.id}")

    # 部署
    runtime = await studio.deploy(timeout=30)
    print(f"部署状态: {runtime.status}")

    # 查看日志
    logs = await studio.get_logs("run", page_size=50)
    for line in logs.logs:
        print(line)

    # 添加环境变量
    await studio.variables.add("MY_KEY", "my_value")

详细示例:操作合集

async def collection_example(client):
    # 创建合集
    collection = await client.collection.create_collection(
        title="我的收藏",
        visibility="private"
    )

    # 添加条目(模型)
    failed = await collection.items.add_items([
        {
            "item_type": "model",
            "item_object_id": "Qwen/Qwen3.8-27B",
            "position": 1
        }
    ])
    if failed:
        print("添加失败:", failed)

    # 获取条目列表
    items = await collection.items.get_items()
    for item in items:
        print(f"- {item.item_object_id}")

    # 删除合集
    await collection.delete()

🧪 运行测试

项目包含完整的测试用例,位于 tests/ 目录。运行前请确保已设置有效的 MODELSCOPE_API_TOKEN

[!CAUTION]

测试用例里包含“删除创空间”,这是一个危险的操作,请确保您没有会受影响的创空间。

要实现该操作,需要使用“管理员权限”的 API Token。

📄 许可证

本项目使用 MIT 许可证。

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

modelscope_api-0.0.2.tar.gz (26.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

modelscope_api-0.0.2-py3-none-any.whl (38.2 kB view details)

Uploaded Python 3

File details

Details for the file modelscope_api-0.0.2.tar.gz.

File metadata

  • Download URL: modelscope_api-0.0.2.tar.gz
  • Upload date:
  • Size: 26.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.12.7

File hashes

Hashes for modelscope_api-0.0.2.tar.gz
Algorithm Hash digest
SHA256 7b67f7655397c05f543d005b2cbc5bf42d345fbd68932270df8c7be8b0fc991d
MD5 ef0b24fd61d5a46c541c3d107e1ef239
BLAKE2b-256 3a421d897d1bc076d851e179dab5dc59773a8215e91758892c6e73c62c8a309e

See more details on using hashes here.

File details

Details for the file modelscope_api-0.0.2-py3-none-any.whl.

File metadata

  • Download URL: modelscope_api-0.0.2-py3-none-any.whl
  • Upload date:
  • Size: 38.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.12.7

File hashes

Hashes for modelscope_api-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 1c521ff200667cb37281dd6eaf5aebdab95429598bfe2eda070fa6362d655c99
MD5 47bc55fd94a990f38242e9c7b12101cc
BLAKE2b-256 d0a5674b2656818fef686caeb326eaaefcd1dc374d83981b06b736ab7436ab3b

See more details on using hashes here.

Release history Release notifications | RSS feed

0.0.4

2 files

0.0.3

2 files

This release

0.0.2 This release

2 files

0.0.1

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page