使用LangChain的ChatOpenAI时出现AuthenticationError空消息认证错误
LangChain ChatOpenAI 认证错误问题
问题重现
- 已通过
pip install langchain安装库并导入ChatOpenAI,在Colab中通过以下命令设置API密钥:
%env OPENAI_API_KEY= my_api_key
- 初始化
ChatOpenAI无报错,输出显示参数已加载:
chat = ChatOpenAI(temperature=0.0,openai_organization='Personal') chat
输出结果:
ChatOpenAI(verbose=False, callbacks=None, callback_manager=None, client=<class 'openai.api_resources.chat_completion.ChatCompletion'>, model_name='gpt-3.5-turbo', temperature=0.0, model_kwargs={}, openai_api_key='my_api_key', openai_api_base='', openai_organization='Personal', openai_proxy='', request_timeout=None, max_retries=6, streaming=False, n=1, max_tokens=None)
- 调用模型时抛出认证错误:
customer_response = chat(customer_messages)
错误栈:
--------------------------------------------------------------------------- AuthenticationError Traceback (most recent call last) <ipython-input-64-a39359b08f39> in <cell line: 1>() ----> 1 customer_response = chat(customer_messages) 17 frames /usr/local/lib/python3.10/dist-packages/openai/api_requestor.py in _interpret_response_line(self, rbody, rcode, rheaders, stream) 761 stream_error = stream and "error" in resp.data 762 if stream_error or not 200 <= rcode < 300: --> 763 raise self.handle_error_response( 764 rbody, rcode, resp.data, rheaders, stream_error=stream_error 765 ) AuthenticationError: <empty message>
解决方法
- 修正环境变量格式:
%env命令中等号后不能加空格,正确写法为:
原命令的空格会导致密钥字符串带无效空格,无法通过认证。%env OPENAI_API_KEY=my_api_key - 替换为组织ID而非名称:
openai_organization参数需填写OpenAI平台的组织ID,不是自定义名称(比如"Personal")。登录OpenAI后台,在「设置-组织」页面查看组织ID并替换。 - 直接传入密钥参数:绕过环境变量读取问题,初始化时直接指定密钥和组织ID:
chat = ChatOpenAI( temperature=0.0, openai_api_key="你的有效API密钥", openai_organization="你的组织ID" ) - 验证密钥有效性:检查API密钥是否过期、是否具备gpt-3.5-turbo调用权限,同时确认OpenAI账户有可用余额。
内容的提问来源于stack exchange,提问作者Sinan
相关产品推荐
相关产品推荐

