{"record":{"id":"6d233eeb2a177120","repo":"datawhalechina/hello-agents","slug":"mx-apikey","errorCode":null,"errorMessage":"MX_APIKEY 未配置","messagePattern":"MX_APIKEY 未配置","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"critical","filePath":"Co-creation-projects/lcyting-StockSage-agent/skills/自选股管理/mx-zixuan/mx_zixuan.py","lineNumber":50,"sourceCode":"        # 尝试从.env文件读取\n        env_file = os.path.join(os.path.dirname(os.path.dirname(__file__)), \".env\")\n        if os.path.exists(env_file):\n            try:\n                with open(env_file, \"r\") as f:\n                    for line in f:\n                        line = line.strip()\n                        if line and not line.startswith(\"#\") and \"=\" in line:\n                            key, value = line.split(\"=\", 1)\n                            if key.strip() == \"MX_APIKEY\":\n                                apikey = value.strip()\n                                break\n            except Exception as e:\n                print(f\"⚠️  读取.env文件失败: {e}\", file=sys.stderr)\n    \n    if not apikey:\n        print(\"❌ 未找到MX_APIKEY，请设置环境变量：\", file=sys.stderr)\n        print(\"   export MX_APIKEY=your_apikey\", file=sys.stderr)\n        raise RuntimeError(\"MX_APIKEY 未配置\")\n    \n    return apikey\n\ndef query_self_select(apikey: str) -> Dict:\n    \"\"\"查询自选股列表\"\"\"\n    headers = {\n        \"Content-Type\": \"application/json\",\n        \"apikey\": apikey\n    }\n    \n    response = requests.post(QUERY_URL, headers=headers, json={}, timeout=30)\n    response.raise_for_status()\n    return response.json()\n\ndef manage_self_select(apikey: str, query: str) -> Dict:\n    \"\"\"添加或删除自选股\"\"\"\n    headers = {\n        \"Content-Type\": \"application/json\",","sourceCodeStart":32,"sourceCodeEnd":68,"githubUrl":"https://github.com/datawhalechina/hello-agents/blob/606a07d341a47be773fab7f4b71177f53f96b2c3/Co-creation-projects/lcyting-StockSage-agent/skills/自选股管理/mx-zixuan/mx_zixuan.py#L32-L68","documentation":"The mx_zixuan helper raises RuntimeError(\"MX_APIKEY not configured\") when key resolution fails entirely: it checks the environment, then hand-parses .env files for a `MX_APIKEY=` line (splitting on the first '='), and only raises after both come up empty. It also prints stderr diagnostics naming where to look before raising.","triggerScenarios":"No MX_APIKEY in os.environ and no .env (or .env without an MX_APIKEY= line) reachable from the working directory; .env line malformed so the parser misses it (no '=', or key written as MXAPIKEY); read failure on .env is only warned about, then the RuntimeError follows.","commonSituations":"Running the skill from a directory where no .env exists along the helper's search paths; malformed .env lines (missing '=', key written as MXAPIKEY, inline comments); CI/cron processes without the env var exported; key stored under a different variable name.","solutions":["export MX_APIKEY=your_key, or ensure a .env file containing `MX_APIKEY=...` exists in the location the helper searches.","Check the stderr output — it prints the exact remediation and any .env read failure reason.","Verify the .env line format: key exactly `MX_APIKEY`, one `=`, value on the same line; comment lines starting with # are skipped.","Pass the key explicitly if the API exposes an apikey parameter (the query functions take apikey as an argument)."],"exampleFix":"# before\napikey = get_apikey()  # RuntimeError if neither env nor .env has the key\n\n# after\nimport os\nos.environ.setdefault(\"MX_APIKEY\", \"your_key_here\")  # or fix .env: MX_APIKEY=your_key\napikey = get_apikey()","handlingStrategy":"validation","validationCode":"import os, sys\nkey = os.getenv(\"MX_APIKEY\")\nif not key:\n    # mirror the helper's .env lookup before calling it\n    for path in (\".env\", os.path.expanduser(\"~/.env\")):\n        try:\n            with open(path) as f:\n                for line in f:\n                    line = line.strip()\n                    if line.startswith(\"MX_APIKEY=\"):\n                        key = line.split(\"=\", 1)[1].strip()\n                        break\n        except FileNotFoundError:\n            continue\nif not key:\n    raise SystemExit(\"MX_APIKEY not configured; set env var or .env entry\")","typeGuard":"def mx_apikey_resolvable() -> bool:\n    if os.getenv(\"MX_APIKEY\"):\n        return True\n    try:\n        with open(\".env\") as f:\n            return any(l.strip().startswith(\"MX_APIKEY=\") for l in f)\n    except OSError:\n        return False","tryCatchPattern":"try:\n    apikey = get_apikey()\nexcept RuntimeError as e:\n    if \"MX_APIKEY\" in str(e):\n        raise SystemExit(\"configure MX_APIKEY (export or .env line 'MX_APIKEY=...')\") from e\n    raise","preventionTips":["Watch stderr — the helper prints exactly which sources it checked before raising.","Keep the .env line format exact: 'MX_APIKEY=value' with no spaces around '='.","Prefer setting the env var in the launching process over relying on .env parsing."],"tags":["env-vars","api-key","configuration","python"],"backgroundTag":null,"analyzedSha":"606a07d341a47be773fab7f4b71177f53f96b2c3","analyzedAt":"2026-08-14T22:57:27.446Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}