import gradio as gr import openai import os # 从环境变量中获取密码 ACCESS_PASSWORD = os.getenv("ACCESS_PASSWORD", "your_password_here") # 默认值为"your_password_here",仅测试用 # 初始化 OpenAI 客户端 client = openai.Client( base_url=os.getenv("OPENAI_BASE_URL"), api_key=os.getenv("OPENAI_API_KEY") ) # 可用模型列表 available_models = [ "gpt-3.5-turbo", "gpt-3.5-turbo-1106", "gpt-3.5-turbo-0125", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-16k-0613", "gpt-3.5-turbo-instruct", "gpt-4", "gpt-4-0613", "gpt-4-1106-preview", "gpt-4-0125-preview", "gpt-4-turbo-preview", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-mini", "gpt-4o-mini-2024-07-18", "text-embedding-ada-002", "text-embedding-3-small", "text-embedding-3-large", "text-moderation-latest", "text-moderation-stable", "davinci-002", "babbage-002", "dall-e-2", "dall-e-3", "whisper-1", "tts-1", "tts-1-1106", "tts-1-hd", "tts-1-hd-1106", "o1-mini-2024-09-12", "o1-preview", "o1-mini", "o1-preview-2024-09-12", "gpt-4o-2024-08-06", "chatgpt-4o-latest" ] # 定义与API交互的函数 def generate_response(messages, model): try: response = client.chat.completions.create( model=model, messages=messages ) return response.choices[0].message.content except Exception as e: return str(e) # 聊天处理函数 def chat_fn(history, model, user_input): history.append({"role": "user", "content": user_input}) bot_reply = generate_response(history, model) history.append({"role": "assistant", "content": bot_reply}) chat_history = [(msg["content"], None) if msg["role"] == "user" else (None, msg["content"]) for msg in history] return chat_history, history # 密码验证函数 def check_password(input_password): if input_password == ACCESS_PASSWORD: return "", gr.update(visible=True), gr.update(visible=False), gr.update(visible=False) else: return "Incorrect password. Try again.", gr.update(visible=False), gr.update(visible=True), gr.update(visible=True) # 使用 Gradio Blocks 创建聊天界面 with gr.Blocks() as demo: gr.Markdown("# OpenAI Custom Chat API") # 密码输入和验证区域 password_input = gr.Textbox( placeholder="Enter password...", type="password", show_label=False ) submit_btn = gr.Button("Submit") login_msg = gr.Textbox(visible=False, show_label=False) # 聊天界面部分 with gr.Column(visible=False) as chat_area: model_selector = gr.Dropdown( choices=available_models, label="Select Model", value="gpt-4o" ) chatbot = gr.Chatbot(label="Chat with OpenAI") state = gr.State([]) with gr.Row(): user_input = gr.Textbox(show_label=False, placeholder="Type your message here...", lines=1) send_btn = gr.Button("Send") send_btn.click(chat_fn, inputs=[state, model_selector, user_input], outputs=[chatbot, state], queue=False) user_input.submit(chat_fn, inputs=[state, model_selector, user_input], outputs=[chatbot, state], queue=False) # 提交密码按钮触发密码验证 submit_btn.click( check_password, inputs=password_input, outputs=[login_msg, chat_area, password_input, submit_btn] ) # 运行 Gradio 应用并设置公开访问 demo.launch(share=True)