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

部署Streamlit+LlamaIndex应用遇OpenAI API认证错误求助

解决Streamlit部署后OpenAI API认证失败问题

问题概述

开发了一款基于Streamlit(使用streamlit_chat、streamlit_authenticator)、通过LlamaIndex集成OpenAI API的聊天应用。本地执行streamlit run app.py时一切正常,但部署后抛出tenacity.RetryError,底层原因为openai.error.AuthenticationError(未提供API Key)。

相关代码片段

import yaml
from yaml.loader import SafeLoader
with open('./config.yaml') as file:
    config = yaml.load(file, Loader=SafeLoader)
authenticator = stauth.Authenticate(
    config['credentials'],
    config['cookie']['name'],
    config['cookie']['key'],
    config['cookie']['expiry_days'],
    config['preauthorized']
)
name, authentication_status, username = authenticator.login('Login', 'main')
print(username, name, authentication_status)
if authentication_status:
    authenticator.logout('Logout', 'main')
    st.write(f'Welcome *{name}*')
elif authentication_status == False:
    st.error('Username/password is incorrect')
elif authentication_status == None:
    st.warning('Please enter your username and password')
FIRST_OUTPUT="""Hello!"""

if authentication_status:
    API_KEY = config['credentials']['usernames'][username].get('openaiapi', "")
    st.text("""First text""")
    text_input_container = st.empty()
    if API_KEY=="":
        API_KEY = text_input_container.text_input(label='Introduce your OpenAI API Key:', label_visibility = 'hidden', placeholder='Introduce your OpenAI API Key:')
    if API_KEY != "":
        text_input_container.empty()
    os.environ['OPENAI_API_KEY'] = API_KEY

错误栈及剩余代码

[原错误栈及剩余代码内容]

解决方案

1. 修正配置文件路径问题

部署环境中,./config.yaml的相对路径可能无效。需确保配置文件与app.py在同一目录,或使用绝对路径读取:

import os
config_path = os.path.join(os.path.dirname(__file__), 'config.yaml')
with open(config_path) as file:
    config = yaml.load(file, Loader=SafeLoader)

2. 调整API_KEY设置时机

当前代码在认证后设置环境变量,但LlamaIndex可能在更早阶段读取OPENAI_API_KEY。需将环境变量设置代码移至LlamaIndex组件初始化之前,或直接在LlamaIndex中传入API_KEY:

# 替代环境变量设置,直接传入API_KEY到LlamaIndex
from llama_index import OpenAILLM
llm = OpenAILLM(api_key=API_KEY)

3. 用Session State持久化用户输入的API_KEY

部署后页面刷新会丢失用户输入的API_KEY,需借助Streamlit的会话状态保存:

if authentication_status:
    # 初始化会话状态中的API_KEY
    if 'api_key' not in st.session_state:
        st.session_state.api_key = config['credentials']['usernames'][username].get('openaiapi', "")
    
    API_KEY = st.session_state.api_key
    text_input_container = st.empty()
    
    if API_KEY == "":
        API_KEY = text_input_container.text_input(
            label='Introduce your OpenAI API Key:', 
            label_visibility='hidden', 
            placeholder='Introduce your OpenAI API Key:'
        )
        # 更新会话状态
        st.session_state.api_key = API_KEY
    
    if API_KEY != "":
        text_input_container.empty()
    
    os.environ['OPENAI_API_KEY'] = API_KEY
    # 在此之后初始化LlamaIndex相关组件

4. 检查部署平台的文件上传与权限

确认config.yaml已被正确上传至部署平台,且应用拥有读取该文件的权限。部分平台可能会忽略某些文件,需在.gitignore中排除相关规则,或手动确认文件存在。

5. 验证配置文件中的API_KEY字段

检查config.yaml中credentials.usernames.[username].openaiapi字段是否存在且不为空,避免因配置项缺失导致读取到空值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 21:07:12