datawhalechina/hello-agents · critical · HelloAgentsException

API密钥和服务地址必须被提供或在.env文件中定义。

Error message

API密钥和服务地址必须被提供或在.env文件中定义。

What it means

HelloAgentsException raised in LLM.__init__ when, after provider auto-detection and credential resolution, either api_key or base_url is still falsy. The class refuses to construct an OpenAI client without both, whether from explicit args, provider defaults, or .env loading.

Source

Thrown at Co-creation-projects/YYHDBL-HelloCodeAgentCli/core/llm.py:68

        """
        # 优先使用传入参数,如果未提供,则从环境变量加载
        self.model = model or os.getenv("LLM_MODEL_ID")
        self.temperature = temperature
        self.max_tokens = max_tokens
        self.timeout = timeout or int(os.getenv("LLM_TIMEOUT", "60"))
        self.kwargs = kwargs

        # 自动检测provider或使用指定的provider
        self.provider = provider or self._auto_detect_provider(api_key, base_url)

        # 根据provider确定API密钥和base_url
        self.api_key, self.base_url = self._resolve_credentials(api_key, base_url)

        # 验证必要参数
        if not self.model:
            self.model = self._get_default_model()
        if not all([self.api_key, self.base_url]):
            raise HelloAgentsException("API密钥和服务地址必须被提供或在.env文件中定义。")

        # 创建OpenAI客户端
        self._client = self._create_client()

    def _auto_detect_provider(self, api_key: Optional[str], base_url: Optional[str]) -> str:
        """
        自动检测LLM提供商

        检测逻辑:
        1. 优先检查特定提供商的环境变量
        2. 根据API密钥格式判断
        3. 根据base_url判断
        4. 默认返回通用配置
        """
        # 1. 检查特定提供商的环境变量
        if os.getenv("OPENAI_API_KEY"):
            return "openai"
        if os.getenv("DEEPSEEK_API_KEY"):

View on GitHub (pinned to 606a07d341)

Solutions

  1. Set the provider's API key and base URL in .env at the project root and verify the names match what _resolve_credentials expects.
  2. Pass them explicitly: LLM(api_key='sk-...', base_url='https://api.example.com/v1').
  3. Print the detected provider before construction to confirm the right credential variables are being read.
  4. Check the .env file is loaded from the directory the process runs in, or load it with an absolute path.

Example fix

# before
llm = LLM(model='gpt-4o-mini')  # KeyError -> exception if env missing

# after
llm = LLM(
    model='gpt-4o-mini',
    api_key=os.environ['OPENAI_API_KEY'],
    base_url='https://api.openai.com/v1',
)
Defensive patterns

Strategy: validation

Validate before calling

def llm_ready(api_key, base_url) -> bool:
    return bool(api_key) and bool(base_url)

api_key = api_key or os.getenv('OPENAI_API_KEY')
base_url = base_url or os.getenv('OPENAI_BASE_URL')
if not llm_ready(api_key, base_url):
    raise SystemExit('set OPENAI_API_KEY / OPENAI_BASE_URL (or a .env) before starting')

Try / catch

try:
    llm = LLM(model=MODEL)
except HelloAgentsException as e:
    if 'API密钥' in str(e) or 'API' in str(e):
        raise SystemExit('missing credentials: check .env / env vars')
    raise

Prevention

When it happens

Trigger: Instantiating core.llm.LLM with no api_key while the relevant environment variable (per detected provider) and .env are absent; providing api_key but no base_url for a provider whose default base_url resolution returns None; a .env file in the wrong directory so it is never loaded.

Common situations: Missing/typo'd env var names for the chosen provider; .env not on the expected path (cwd vs project root); switching providers without updating env; API key set to empty string.

Related errors


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