datawhalechina/hello-agents · error · ValueError

ModelScope API key not found. Please set MODELSCOPE_API_KEY

Error message

ModelScope API key not found. Please set MODELSCOPE_API_KEY environment variable.

What it means

A ValueError raised by the custom ModelScope provider class when provider == 'modelscope' but no API key is available: the constructor checks api_key or os.getenv('MODELSCOPE_API_KEY') and refuses to build the OpenAI client without it. It deliberately validates only ModelScope; other providers fall through to the parent class's own handling.

Source

Thrown at code/chapter7/my_llm.py:27

        self,
        model: Optional[str] = None,
        api_key: Optional[str] = None,
        base_url: Optional[str] = None,
        provider: Optional[str] = "auto",
        **kwargs
    ):
        # 检查provider是否为我们想处理的'modelscope'
        if provider == "modelscope":
            print("正在使用自定义的 ModelScope Provider")
            self.provider = "modelscope"
            
            # 解析 ModelScope 的凭证
            self.api_key = api_key or os.getenv("MODELSCOPE_API_KEY")
            self.base_url = base_url or "https://api-inference.modelscope.cn/v1/"
            
            # 验证凭证是否存在
            if not self.api_key:
                raise ValueError("ModelScope API key not found. Please set MODELSCOPE_API_KEY environment variable.")

            # 设置默认模型和其他参数
            self.model = model or os.getenv("LLM_MODEL_ID") or "Qwen/Qwen2.5-VL-72B-Instruct"
            self.temperature = kwargs.get('temperature', 0.7)
            self.max_tokens = kwargs.get('max_tokens')
            self.timeout = kwargs.get('timeout', 60)
            
            # 使用获取的参数创建OpenAI客户端实例
            self._client = OpenAI(api_key=self.api_key, base_url=self.base_url, timeout=self.timeout)

        else:
            # 如果不是 modelscope, 则完全使用父类的原始逻辑来处理
            super().__init__(model=model, api_key=api_key, base_url=base_url, provider=provider, **kwargs)

View on GitHub (pinned to 606a07d341)

Solutions

  1. Get a token from modelscope.cn and set MODELSCOPE_API_KEY in .env (and ensure dotenv loads before constructing the client).
  2. Or pass the key directly: Client(provider='modelscope', api_key='ms-...').
  3. Verify: python -c "import os; print(bool(os.getenv('MODELSCOPE_API_KEY'))") — False means the env is not visible to the process.
  4. In CI, add MODELSCOPE_API_KEY to the secret store and environment mapping.

Example fix

# before
client = MyLLM(provider="modelscope")  # ValueError: key missing

# after
import os
from dotenv import load_dotenv
load_dotenv()
assert os.getenv("MODELSCOPE_API_KEY"), "set MODELSCOPE_API_KEY in .env"
client = MyLLM(provider="modelscope")
# or explicit:
client = MyLLM(provider="modelscope", api_key="ms-xxxx")
Defensive patterns

Strategy: validation

Validate before calling

from dotenv import load_dotenv; load_dotenv()
import os
if not (os.getenv("MODELSCOPE_API_KEY") or explicit_api_key):
    raise EnvironmentError("MODELSCOPE_API_KEY not set")

Type guard

null

Try / catch

try:
    client = MyLLM(provider="modelscope")
except ValueError:
    client = MyLLM(provider="modelscope", api_key=os.environ["MS_TOKEN"])

Prevention

When it happens

Trigger: Constructing the client with provider='modelscope' while MODELSCOPE_API_KEY is unset or empty and no api_key argument was passed. Note base_url has a default (api-inference.modelscope.cn), so only the key is mandatory; model also falls back to env/default.

Common situations: Missing .env entry for MODELSCOPE_API_KEY; key present under a different name (e.g. LLM_API_KEY) and the caller assumed the generic variable would be used; CI/container secrets not wired; .env loaded after client construction.

Related errors


AI-assisted analysis of datawhalechina/hello-agents@606a07d341 (2026-08-14). Data as JSON: /api/errors/476317bc2beabfa9. Report an issue: GitHub.