{"record":{"id":"476317bc2beabfa9","repo":"datawhalechina/hello-agents","slug":"modelscope-api-key-not-found-please-set-modelscop","errorCode":null,"errorMessage":"ModelScope API key not found. Please set MODELSCOPE_API_KEY environment variable.","messagePattern":"ModelScope API key not found\\. Please set MODELSCOPE_API_KEY environment variable\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"code/chapter7/my_llm.py","lineNumber":27,"sourceCode":"        self,\n        model: Optional[str] = None,\n        api_key: Optional[str] = None,\n        base_url: Optional[str] = None,\n        provider: Optional[str] = \"auto\",\n        **kwargs\n    ):\n        # 检查provider是否为我们想处理的'modelscope'\n        if provider == \"modelscope\":\n            print(\"正在使用自定义的 ModelScope Provider\")\n            self.provider = \"modelscope\"\n            \n            # 解析 ModelScope 的凭证\n            self.api_key = api_key or os.getenv(\"MODELSCOPE_API_KEY\")\n            self.base_url = base_url or \"https://api-inference.modelscope.cn/v1/\"\n            \n            # 验证凭证是否存在\n            if not self.api_key:\n                raise ValueError(\"ModelScope API key not found. Please set MODELSCOPE_API_KEY environment variable.\")\n\n            # 设置默认模型和其他参数\n            self.model = model or os.getenv(\"LLM_MODEL_ID\") or \"Qwen/Qwen2.5-VL-72B-Instruct\"\n            self.temperature = kwargs.get('temperature', 0.7)\n            self.max_tokens = kwargs.get('max_tokens')\n            self.timeout = kwargs.get('timeout', 60)\n            \n            # 使用获取的参数创建OpenAI客户端实例\n            self._client = OpenAI(api_key=self.api_key, base_url=self.base_url, timeout=self.timeout)\n\n        else:\n            # 如果不是 modelscope, 则完全使用父类的原始逻辑来处理\n            super().__init__(model=model, api_key=api_key, base_url=base_url, provider=provider, **kwargs)\n","sourceCodeStart":9,"sourceCodeEnd":41,"githubUrl":"https://github.com/datawhalechina/hello-agents/blob/606a07d341a47be773fab7f4b71177f53f96b2c3/code/chapter7/my_llm.py#L9-L41","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Get a token from modelscope.cn and set MODELSCOPE_API_KEY in .env (and ensure dotenv loads before constructing the client).","Or pass the key directly: Client(provider='modelscope', api_key='ms-...').","Verify: python -c \"import os; print(bool(os.getenv('MODELSCOPE_API_KEY'))\") — False means the env is not visible to the process.","In CI, add MODELSCOPE_API_KEY to the secret store and environment mapping."],"exampleFix":"# before\nclient = MyLLM(provider=\"modelscope\")  # ValueError: key missing\n\n# after\nimport os\nfrom dotenv import load_dotenv\nload_dotenv()\nassert os.getenv(\"MODELSCOPE_API_KEY\"), \"set MODELSCOPE_API_KEY in .env\"\nclient = MyLLM(provider=\"modelscope\")\n# or explicit:\nclient = MyLLM(provider=\"modelscope\", api_key=\"ms-xxxx\")","handlingStrategy":"validation","validationCode":"from dotenv import load_dotenv; load_dotenv()\nimport os\nif not (os.getenv(\"MODELSCOPE_API_KEY\") or explicit_api_key):\n    raise EnvironmentError(\"MODELSCOPE_API_KEY not set\")","typeGuard":"null","tryCatchPattern":"try:\n    client = MyLLM(provider=\"modelscope\")\nexcept ValueError:\n    client = MyLLM(provider=\"modelscope\", api_key=os.environ[\"MS_TOKEN\"])","preventionTips":["Set MODELSCOPE_API_KEY in .env and load dotenv before client construction.","Pass api_key explicitly in scripts to decouple from env naming.","Add a startup assertion so misconfig surfaces immediately."],"tags":["configuration","modelscope","api-key","valueerror"],"backgroundTag":null,"analyzedSha":"606a07d341a47be773fab7f4b71177f53f96b2c3","analyzedAt":"2026-08-14T22:57:27.446Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}