datawhalechina/hello-agents · error · HTTPException
AI 服务未配置,请设置 OPENAI_API_KEY
Error message
AI 服务未配置,请设置 OPENAI_API_KEY
What it means
A 503 Service Unavailable raised by the /writing/coach endpoint when the module-level llm client is falsy. The llm object is created at import time from configuration (typically an OpenAI-compatible client requiring OPENAI_API_KEY); when the key or related settings are absent the app intentionally starts anyway but every AI-powered request fails fast with this message. It signals a configuration problem, not a code bug.
Source
Thrown at Co-creation-projects/Apricity-InnocoreAI/api/routes/writing.py:63
class MimicRequest(BaseModel):
user_id: str
text: str
target_style: str
reference_papers: Optional[list] = []
context: Optional[Dict[str, Any]] = {}
class SuggestRequest(BaseModel):
user_id: str
text: str
context: Optional[Dict[str, Any]] = {}
@router.post("/coach", response_model=Dict[str, Any])
async def writing_coach(request: WritingCoachRequest):
"""写作助手 - 使用真实的 AI 处理"""
try:
if not llm:
raise HTTPException(status_code=503, detail="AI 服务未配置,请设置 OPENAI_API_KEY")
logger.info(f"处理写作任务: {request.task}, 风格: {request.style}")
# 根据任务类型生成提示词
prompts = {
"polish": f"""作为一位专业的学术写作编辑,请帮我润色以下文本,使其符合{request.style}学术写作标准:
原文:
{request.text}
请提供:
1. 润色后的文本(保持原意,提升表达质量)
2. 具体的改进说明
3. 写作建议
要求:
- 保持学术严谨性
- 提升表达清晰度View on GitHub (pinned to 606a07d341)
Solutions
- Set OPENAI_API_KEY in the environment or .env file used by the service and restart the app
- Verify the .env file is actually loaded (python-dotenv load_dotenv() runs before the llm factory executes at import time)
- Check the value is non-empty: print(bool(os.getenv('OPENAI_API_KEY'))) in a shell of the same environment
- If you use a custom base_url/self-hosted model, confirm both base_url and api_key entries exist in the config the llm factory reads
- Optionally fail at startup instead of per-request: raise on boot when llm is None so misconfiguration is caught by deployment checks
Example fix
# before
if not llm:
raise HTTPException(status_code=503, detail="AI 服务未配置,请设置 OPENAI_API_KEY")
# after (fail fast at startup in main.py)
# settings validated once, llm never None when routes serve traffic
assert settings.llm.api_key, "OPENAI_API_KEY must be set at startup" Defensive patterns
Strategy: validation
Validate before calling
import os
assert os.getenv('OPENAI_API_KEY'), 'OPENAI_API_KEY missing — /writing/coach will return 503'
# or as a readiness probe before accepting traffic:
ready = bool(os.getenv('OPENAI_API_KEY')) Try / catch
try:
result = client.post('/writing/coach', json=payload)
except HTTPError as e:
if e.response.status_code == 503:
fail_deployment('AI service unconfigured: set OPENAI_API_KEY')
raise Prevention
- Put OPENAI_API_KEY in the service's env/secret store and assert it during startup checks
- Add a health/readiness endpoint that reports llm is configured so orchestrators skip routing to unconfigured replicas
- Fail fast at boot (refuse to start without the key) in environments where AI features are required
When it happens
Trigger: POST /writing/coach when OPENAI_API_KEY (or the equivalent llm config entry) is missing/empty in the environment or .env file, so llm evaluates to None at import time. Also occurs when the key variable is misspelled, the .env file is not loaded before the routes module imports, or the LLM factory silently returns None on invalid config.
Common situations: Fresh clone without .env setup; deploying to a container where the env var was not passed; CI runs without secrets; renaming the config key (OPENAI_API_KEY vs LLM_API_KEY) after a refactor; key present but empty string, which also yields a falsy client.
Related errors
- 向量生成器初始化失败: {str(e)}
- RECOMMEND_UNAVAILABLE
- LLM_MODEL_ID, LLM_API_KEY, and LLM_BASE_URL must be set (via
- 处理失败: {str(e)}
- 向量生成失败: {str(e)}
AI-assisted analysis of datawhalechina/hello-agents@606a07d341 (2026-08-14).
Data as JSON: /api/errors/38c3567a052df01f.
Report an issue: GitHub.