Spaces:
Sleeping
Sleeping
| import os | |
| import gradio as gr | |
| from openai import OpenAI | |
| # ================= 🔐 安全隐藏区域 ================= | |
| # 核心:只读取变量名,绝不在这里写死任何真实的 URL 或 KEY | |
| FREE_LLM_API_URL = os.getenv("FREE_LLM_API_URL") | |
| FREE_LLM_API_KEY = os.getenv("FREE_LLM_API_KEY") | |
| # 启动前做个基础的安全检查(在容器日志中提示,但不会暴露具体内容) | |
| if not FREE_LLM_API_URL or not FREE_LLM_API_KEY: | |
| print("⚠️ 警告: 环境变量 FREE_LLM_API_URL 或 FREE_LLM_API_KEY 未配置,API 链接可能会失败!") | |
| # ================================================== | |
| # 初始化 OpenAI 客户端(桥接 FreeLLMAPI) | |
| client = OpenAI( | |
| base_url=FREE_LLM_API_URL, | |
| api_key=FREE_LLM_API_KEY | |
| ) | |
| def predict(message, history): | |
| # 再次确保密匙存在才执行 | |
| if not client.api_key or not client.base_url: | |
| yield "❌ 系统未配置 API 密钥,请在平台后台设置 Environment Variables / Secrets。" | |
| return | |
| history_openai = [] | |
| for human, ai in history: | |
| history_openai.append({"role": "user", "content": human}) | |
| history_openai.append({"role": "assistant", "content": ai}) | |
| history_openai.append({"role": "user", "content": message}) | |
| try: | |
| response = client.chat.completions.create( | |
| model="gemini", | |
| messages=history_openai, | |
| stream=True | |
| ) | |
| partial_message = "" | |
| for chunk in response: | |
| if chunk.choices[0].delta.content: | |
| partial_message = partial_message + chunk.choices[0].delta.content | |
| yield partial_message | |
| except Exception as e: | |
| # 安全提示:报错时模糊处理,防止由于报错信息太详细而泄露了敏感的 URL | |
| yield f"⚠️ 接口连接失败,请检查后台配置。" | |
| # Gradio 界面 | |
| demo = gr.ChatInterface( | |
| fn=predict, | |
| title="AI 自动化助手", | |
| textbox=gr.Textbox(placeholder="请输入内容...", container=False, scale=7) | |
| ) | |
| if __name__ == "__main__": | |
| server_name = os.getenv("GRADIO_SERVER_NAME", "0.0.0.0") | |
| server_port = int(os.getenv("GRADIO_SERVER_PORT", 7860)) | |
| demo.queue().launch(server_name=server_name, server_port=server_port) |