datawhalechina/hello-agents · critical · ValueError

MX_APIKEY 环境变量未设置,请先设置环境变量: export MX_APIKEY=your_api_key_he

Error message

MX_APIKEY 环境变量未设置,请先设置环境变量:
export MX_APIKEY=your_api_key_here
或者在初始化时传入 api_key 参数

What it means

MXSelectStock's constructor raises ValueError when no API key is available: it takes api_key from the argument or the MX_APIKEY environment variable, and neither is set. The key authorizes calls to the MiaoXiang stock-screening endpoint (mkapi2.dfcfs.com), so the client refuses to construct without it.

Source

Thrown at Co-creation-projects/lcyting-StockSage-agent/skills/智能选股/mx-xuangu/mx_xuangu.py:129

            else:
                cn_row[cn_name] = str(val)
        rows.append(cn_row)

    return rows

class MXSelectStock:
    """妙想智能选股客户端"""
    
    BASE_URL = "https://mkapi2.dfcfs.com/finskillshub/api/claw/stock-screen"
    
    def __init__(self, api_key: Optional[str] = None):
        """
        初始化客户端
        :param api_key: MX API Key,如果不提供则从环境变量 MX_APIKEY 读取
        """
        self.api_key = api_key or os.getenv("MX_APIKEY")
        if not self.api_key:
            raise ValueError(
                "MX_APIKEY 环境变量未设置,请先设置环境变量:\n"
                "export MX_APIKEY=your_api_key_here\n"
                "或者在初始化时传入 api_key 参数"
            )
    
    def search(self, query: str) -> Dict[str, Any]:
        """
        智能选股
        :param query: 自然语言查询,如 "今天A股价格大于10元"
        :return: API 响应结果
        """
        headers = {
            "Content-Type": "application/json",
            "apikey": self.api_key
        }
        data = {
            "keyword": query
        }

View on GitHub (pinned to 606a07d341)

Solutions

  1. export MX_APIKEY=your_key in the shell/environment that runs the code, or pass api_key="..." to MXSelectStock(api_key=...).
  2. If the key lives in .env, call load_dotenv() before constructing the client.
  3. In Docker/compose, add MX_APIKEY to environment: or env_file:.
  4. Standardize on one env-loading mechanism across skills to avoid the .env-vs-env mismatch.

Example fix

# before
client = MXSelectStock()  # ValueError: MX_APIKEY not set

# after
from dotenv import load_dotenv
load_dotenv()  # reads .env into os.environ
client = MXSelectStock()  # or MXSelectStock(api_key=os.environ["MX_APIKEY"])
Defensive patterns

Strategy: validation

Validate before calling

from dotenv import load_dotenv
load_dotenv()  # this class reads only os.getenv, not .env directly
if not os.getenv("MX_APIKEY"):
    raise SystemExit("MX_APIKEY not set; export it or pass api_key= to MXSelectStock")
client = MXSelectStock()

Type guard

def mx_key_present(api_key: str | None = None) -> bool:
    return bool(api_key or os.getenv("MX_APIKEY"))

Try / catch

try:
    client = MXSelectStock()
except ValueError as e:
    if "MX_APIKEY" in str(e):
        client = MXSelectStock(api_key=os.environ["MX_APIKEY_FILE_CONTENTS"])  # explicit injection
    else:
        raise

Prevention

When it happens

Trigger: MXSelectStock() with no api_key argument while MX_APIKEY is unset; .env present in the project root but this class reads only os.getenv (it does not parse .env itself), so a .env alone does not help unless loaded.

Common situations: Assuming .env is read automatically (unlike mx_zixuan which hand-parses .env, this class only reads env); running under a launcher that doesn't source .env; key stored under a different variable name.

Related errors


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