You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CrewAI自定义嵌入器与知识库报错:缺失OPENAI_API_KEY

解决CrewAI自定义Azure OAuth嵌入器触发litellm认证错误的问题

问题根源

自定义Embedding类虽实现了EmbeddingFunction接口,但CrewAI内部部分流程仍默认依赖litellm的OpenAI集成逻辑,未完全接管嵌入流程,导致触发litellm.AuthenticationError。

解决方案

1. 实现完全独立的自定义嵌入器

不要依赖litellm的封装,直接通过OAuth认证调用Azure OpenAI嵌入接口,确保覆盖EmbeddingFunction的所有核心方法:

from crewai.embeddings import EmbeddingFunction
import requests

class AzureOAuthEmbedding(EmbeddingFunction):
    def __init__(self, azure_endpoint: str, oauth_token: str, deployment_name: str):
        self.azure_endpoint = azure_endpoint
        self.oauth_token = oauth_token
        self.deployment_name = deployment_name
        self.api_version = "2024-02-15-preview"

    def embed_documents(self, texts: list[str]) -> list[list[float]]:
        headers = {
            "Authorization": f"Bearer {self.oauth_token}",
            "Content-Type": "application/json"
        }
        payload = {"input": texts}
        url = f"{self.azure_endpoint}/openai/deployments/{self.deployment_name}/embeddings?api-version={self.api_version}"
        
        response = requests.post(url, headers=headers, json=payload)
        response.raise_for_status()
        return [item["embedding"] for item in response.json()["data"]]

    def embed_query(self, text: str) -> list[float]:
        return self.embed_documents([text])[0]

2. 显式绑定自定义嵌入器到Agent和知识库

  • 关联Agent时,必须显式传入embedding参数,同时确保未设置OPENAI_API_KEY等默认环境变量:
from crewai import Agent

custom_embedding = AzureOAuthEmbedding(
    azure_endpoint="https://your-azure-resource.openai.azure.com/",
    oauth_token="your-valid-oauth-token",
    deployment_name="your-embedding-deployment"
)

agent = Agent(
    role="业务分析专员",
    goal="基于知识库数据生成业务报告",
    backstory="拥有5年行业分析经验",
    embedding=custom_embedding  # 强制使用自定义嵌入器
)
  • 初始化PgVectorStorage和知识库时,直接绑定自定义嵌入器:
from crewai.knowledge import KnowledgeBase
from your_module import PgVectorStorage

vector_storage = PgVectorStorage(
    connection_string="postgresql://user:password@host:5432/vector_db",
    embedding_function=custom_embedding  # 绑定嵌入器到存储层
)

kb = KnowledgeBase(storage=vector_storage)
# 直接添加JSON数据到知识库,绕开默认KnowledgeSource的隐性依赖
kb.add(data=[{"id": 1, "content": "业务数据详情"}, ...])

3. 排查隐性依赖

检查代码中是否有其他地方初始化了默认的OpenAIEmbedding或调用了litellm的embedding方法,这些代码会触发认证检查,需全部替换为自定义嵌入器的调用。


内容的提问来源于stack exchange,提问作者lazzy_ms

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 23:16:07