datawhalechina/hello-agents · error · 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

MXSearch.__init__ raises ValueError when neither the api_key parameter nor the MX_APIKEY environment variable yields a non-empty string. This is a startup-time configuration guard: the client refuses to build without credentials because every request to the mx news-search endpoint (https://mkapi2.dfcfs.com/finskillshub/api/claw/news-search) requires the key in its headers. It fires before any network I/O happens, so seeing it means the object was never constructed, not that a request failed.

Source

Thrown at Co-creation-projects/lcyting-StockSage-agent/skills/资讯搜索/mx-search/mx_search.py:31

def safe_filename(text: str, max_len: int = 80) -> str:
    """Convert query string to safe filenameh"""
    cleaned = re.sub(r'[<>:"/\\|?*]', "_", text).strip().replace(" ", "_")
    return (cleaned[:max_len] or "query").strip("._")

class MXSearch:
    """妙想资讯搜索客户端"""
    
    BASE_URL = "https://mkapi2.dfcfs.com/finskillshub/api/claw/news-search"
    
    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: 搜索问句
        :return: API 响应结果
        """
        headers = {
            "Content-Type": "application/json",
            "apikey": self.api_key
        }
        data = {
            "query": query
        }

View on GitHub (pinned to 606a07d341)

Solutions

  1. Pass the key explicitly at construction: MXSearch(api_key=os.environ["MX_APIKEY"]) or a literal/secret-manager value.
  2. Export the exact variable in the launching shell: export MX_APIKEY=your_api_key_here, then re-run from that same shell.
  3. If the key lives in .env, load it before constructing: from dotenv import load_dotenv; load_dotenv() (verify the .env line spells MX_APIKEY=... with no quotes/spaces issues).
  4. For containers/services, add MX_APIKEY to the container env / systemd Environment= / CI secret so the process inherits it.
  5. Add a fail-fast check at app startup (os.getenv("MX_APIKEY")) so the error surfaces in logs with context instead of deep in the skill.

Example fix

// before
client = MXSearch()
// after
import os
from dotenv import load_dotenv
load_dotenv()
client = MXSearch(api_key=os.getenv("MX_APIKEY"))  # raises early with your own context if still missing
Defensive patterns

Strategy: validation

Validate before calling

import os
api_key = os.getenv("MX_APIKEY")
if not api_key:
    raise SystemExit("MX_APIKEY not set — export it or pass api_key= to MXSearch")

Try / catch

try:
    client = MXSearch(api_key=os.getenv("MX_APIKEY"))
except ValueError as e:
    # config error, not transient — fix environment, do not retry
    logger.error("MXSearch config missing: %s", e)
    raise

Prevention

When it happens

Trigger: Calling MXSearch() (or MXSearch(api_key=None)/api_key="") in a shell/process where MX_APIKEY was never exported; exporting it in one terminal but running the Python process from another (or from an IDE/systemd/cron) that does not inherit it; .env file exists but nothing loads it (no load_dotenv() in this skill module); key set only under a different name (MX_API_KEY vs MX_APIKEY).

Common situations: Fresh clone of StockSage-agent without copying .env.example; deploying to a server/container where the env var was not added to the service unit/image; running under an IDE launch configuration that bypasses the shell profile; typo in the variable name (MX_APIKEY is not the same as MX_API_KEY).

Related errors


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