{"record":{"id":"38c3567a052df01f","repo":"datawhalechina/hello-agents","slug":"ai-openai-api-key-38c356","errorCode":null,"errorMessage":"AI 服务未配置，请设置 OPENAI_API_KEY","messagePattern":"AI 服务未配置，请设置 OPENAI_API_KEY","errorType":"http","errorClass":"HTTPException","httpStatus":503,"severity":"error","filePath":"Co-creation-projects/Apricity-InnocoreAI/api/routes/writing.py","lineNumber":63,"sourceCode":"\nclass MimicRequest(BaseModel):\n    user_id: str\n    text: str\n    target_style: str\n    reference_papers: Optional[list] = []\n    context: Optional[Dict[str, Any]] = {}\n\nclass SuggestRequest(BaseModel):\n    user_id: str\n    text: str\n    context: Optional[Dict[str, Any]] = {}\n\n@router.post(\"/coach\", response_model=Dict[str, Any])\nasync def writing_coach(request: WritingCoachRequest):\n    \"\"\"写作助手 - 使用真实的 AI 处理\"\"\"\n    try:\n        if not llm:\n            raise HTTPException(status_code=503, detail=\"AI 服务未配置，请设置 OPENAI_API_KEY\")\n        \n        logger.info(f\"处理写作任务: {request.task}, 风格: {request.style}\")\n        \n        # 根据任务类型生成提示词\n        prompts = {\n            \"polish\": f\"\"\"作为一位专业的学术写作编辑，请帮我润色以下文本，使其符合{request.style}学术写作标准：\n\n原文：\n{request.text}\n\n请提供：\n1. 润色后的文本（保持原意，提升表达质量）\n2. 具体的改进说明\n3. 写作建议\n\n要求：\n- 保持学术严谨性\n- 提升表达清晰度","sourceCodeStart":45,"sourceCodeEnd":81,"githubUrl":"https://github.com/datawhalechina/hello-agents/blob/606a07d341a47be773fab7f4b71177f53f96b2c3/Co-creation-projects/Apricity-InnocoreAI/api/routes/writing.py#L45-L81","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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"],"exampleFix":"# before\nif not llm:\n    raise HTTPException(status_code=503, detail=\"AI 服务未配置，请设置 OPENAI_API_KEY\")\n\n# after (fail fast at startup in main.py)\n# settings validated once, llm never None when routes serve traffic\nassert settings.llm.api_key, \"OPENAI_API_KEY must be set at startup\"","handlingStrategy":"validation","validationCode":"import os\nassert os.getenv('OPENAI_API_KEY'), 'OPENAI_API_KEY missing — /writing/coach will return 503'\n# or as a readiness probe before accepting traffic:\nready = bool(os.getenv('OPENAI_API_KEY'))","typeGuard":null,"tryCatchPattern":"try:\n    result = client.post('/writing/coach', json=payload)\nexcept HTTPError as e:\n    if e.response.status_code == 503:\n        fail_deployment('AI service unconfigured: set OPENAI_API_KEY')\n    raise","preventionTips":["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"],"tags":["configuration","openai","http-503","environment-variables","fastapi"],"backgroundTag":null,"analyzedSha":"606a07d341a47be773fab7f4b71177f53f96b2c3","analyzedAt":"2026-08-14T22:57:27.446Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}