datawhalechina/hello-agents · critical · AgentException

向量生成器初始化失败: {str(e)}

Error message

向量生成器初始化失败: {str(e)}

What it means

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).

Source

Thrown at Co-creation-projects/Apricity-InnocoreAI/utils/embedding.py:32

class EmbeddingGenerator:
    """向量生成器"""
    
    def __init__(self):
        self.config = get_config()
        self.client = None
        self.embedding_model = self.config.vector_db.embedding_model
        self.cache = {}  # 简单的内存缓存
    
    async def initialize(self):
        """初始化向量生成器"""
        try:
            self.client = AsyncOpenAI(
                api_key=self.config.llm.api_key,
                base_url=self.config.llm.base_url
            )
        except Exception as e:
            raise AgentException(f"向量生成器初始化失败: {str(e)}")
    
    async def generate_embedding(self, text: str, use_cache: bool = True) -> List[float]:
        """生成文本向量"""
        if not text:
            return [0.0] * 1536  # 返回零向量
        
        # 检查缓存
        if use_cache:
            cache_key = self._get_cache_key(text)
            if cache_key in self.cache:
                return self.cache[cache_key]
        
        try:
            # 清理文本
            cleaned_text = self._clean_text(text)
            
            # 调用OpenAI API
            response = await self.client.embeddings.create(

View on GitHub (pinned to 606a07d341)

Solutions

  1. Ensure config.llm.api_key and config.llm.base_url are populated before calling initialize(); check with a quick print of the config object
  2. 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
  3. Add the missing key to .env / environment and restart the service
  4. Catch AgentException at the call site and fail startup with a clear configuration error instead of proceeding with a dead embedder

Example fix

# before
self.client = AsyncOpenAI(
    api_key=self.config.llm.api_key,
    base_url=self.config.llm.base_url
)
except Exception as e:
    raise AgentException(f"向量生成器初始化失败: {str(e)}")

# after
if not self.config.llm.api_key:
    raise AgentException("向量生成器初始化失败: config.llm.api_key is empty")
self.client = AsyncOpenAI(
    api_key=self.config.llm.api_key,
    base_url=self.config.llm.base_url
)
Defensive patterns

Strategy: validation

Validate before calling

cfg = load_config()
assert cfg.llm.api_key, 'config.llm.api_key missing — embedding init will fail'
assert cfg.llm.base_url and cfg.llm.base_url.startswith('http'), 'config.llm.base_url invalid'

Try / catch

try:
    await embedder.initialize()
except AgentException as e:
    if '初始化失败' in str(e):
        fail_startup(f'Embedding misconfiguration: {e}')  # do not continue with dead embedder
    raise

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


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