{"record":{"id":"ff42ea47df20d3a1","repo":"datawhalechina/hello-agents","slug":"str-e-ff42ea","errorCode":null,"errorMessage":"向量生成器初始化失败: {str(e)}","messagePattern":"向量生成器初始化失败: (.+?)","errorType":"exception","errorClass":"AgentException","httpStatus":null,"severity":"critical","filePath":"Co-creation-projects/Apricity-InnocoreAI/utils/embedding.py","lineNumber":32,"sourceCode":"\nclass EmbeddingGenerator:\n    \"\"\"向量生成器\"\"\"\n    \n    def __init__(self):\n        self.config = get_config()\n        self.client = None\n        self.embedding_model = self.config.vector_db.embedding_model\n        self.cache = {}  # 简单的内存缓存\n    \n    async def initialize(self):\n        \"\"\"初始化向量生成器\"\"\"\n        try:\n            self.client = AsyncOpenAI(\n                api_key=self.config.llm.api_key,\n                base_url=self.config.llm.base_url\n            )\n        except Exception as e:\n            raise AgentException(f\"向量生成器初始化失败: {str(e)}\")\n    \n    async def generate_embedding(self, text: str, use_cache: bool = True) -> List[float]:\n        \"\"\"生成文本向量\"\"\"\n        if not text:\n            return [0.0] * 1536  # 返回零向量\n        \n        # 检查缓存\n        if use_cache:\n            cache_key = self._get_cache_key(text)\n            if cache_key in self.cache:\n                return self.cache[cache_key]\n        \n        try:\n            # 清理文本\n            cleaned_text = self._clean_text(text)\n            \n            # 调用OpenAI API\n            response = await self.client.embeddings.create(","sourceCodeStart":14,"sourceCodeEnd":50,"githubUrl":"https://github.com/datawhalechina/hello-agents/blob/606a07d341a47be773fab7f4b71177f53f96b2c3/Co-creation-projects/Apricity-InnocoreAI/utils/embedding.py#L14-L50","documentation":"An AgentException raised by EmbeddingGenerator.initialize() in utils/embedding.py when constructing the AsyncOpenAI client fails. The client is built from config.llm.api_key and config.llm.base_url; failure almost always means those settings are missing/malformed (None api_key, invalid base_url scheme) or the openai package is unavailable. The wrapper preserves the original message via str(e).","triggerScenarios":"Calling await embedding_generator.initialize() when config.llm.api_key is None (OpenAI() raises OpenAIError: api_key must be set), when base_url is not a valid URL (httpx.ParseError), or in exotic cases where the openai import inside the module failed. Note it reuses the LLM key config for embeddings rather than a dedicated embedding credential.","commonSituations":"Missing/empty OPENAI_API_KEY at startup; using a custom embedding provider (e.g. a local sentence-transformers server or Azure) whose URL is not set in base_url; config file loaded after the generator is constructed; typo in the config key names so api_key is None.","solutions":["Ensure config.llm.api_key and config.llm.base_url are populated before calling initialize(); check with a quick print of the config object","If using a non-OpenAI embedding endpoint, set base_url to the provider's OpenAI-compatible URL and confirm the model name in config.vector_db.embedding_model is served there","Add the missing key to .env / environment and restart the service","Catch AgentException at the call site and fail startup with a clear configuration error instead of proceeding with a dead embedder"],"exampleFix":"# before\nself.client = AsyncOpenAI(\n    api_key=self.config.llm.api_key,\n    base_url=self.config.llm.base_url\n)\nexcept Exception as e:\n    raise AgentException(f\"向量生成器初始化失败: {str(e)}\")\n\n# after\nif not self.config.llm.api_key:\n    raise AgentException(\"向量生成器初始化失败: config.llm.api_key is empty\")\nself.client = AsyncOpenAI(\n    api_key=self.config.llm.api_key,\n    base_url=self.config.llm.base_url\n)","handlingStrategy":"validation","validationCode":"cfg = load_config()\nassert cfg.llm.api_key, 'config.llm.api_key missing — embedding init will fail'\nassert cfg.llm.base_url and cfg.llm.base_url.startswith('http'), 'config.llm.base_url invalid'","typeGuard":null,"tryCatchPattern":"try:\n    await embedder.initialize()\nexcept AgentException as e:\n    if '初始化失败' in str(e):\n        fail_startup(f'Embedding misconfiguration: {e}')  # do not continue with dead embedder\n    raise","preventionTips":["Validate llm.api_key/base_url in a startup readiness check before serving traffic","Use a dedicated embedding credential/config block instead of reusing the chat LLM key","Smoke-test initialize() in deployment health checks"],"tags":["configuration","openai","embeddings","initialization","environment-variables"],"backgroundTag":null,"analyzedSha":"606a07d341a47be773fab7f4b71177f53f96b2c3","analyzedAt":"2026-08-14T22:57:27.446Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}