Spaces:
Sleeping
Sleeping
import time | |
import gradio as gr | |
import openai | |
import os | |
import requests | |
import json | |
# 從 Hugging Face secrets 中讀取 OpenAI API 金鑰 | |
api_key = os.getenv('OPENAI_API_KEY') | |
if not api_key: | |
raise ValueError("請設置 'OPENAI_API_KEY' 環境變數") | |
# OpenAI API key | |
openai_api_key = api_key | |
# 將 Gradio 的歷史紀錄轉換為 OpenAI 格式 | |
def transform_history(history): | |
new_history = [] | |
for chat in history: | |
new_history.append({"role": "user", "content": chat[0]}) | |
new_history.append({"role": "assistant", "content": chat[1]}) | |
return new_history | |
# 回應生成函數,使用 requests 來呼叫 OpenAI API | |
def response(message, history): | |
global conversation_history | |
# 將 Gradio 的歷史紀錄轉換為 OpenAI 的格式 | |
conversation_history = transform_history(history) | |
url = "https://api.openai.com/v1/chat/completions" | |
headers = { | |
"Content-Type": "application/json", | |
"Authorization": f"Bearer {openai_api_key}" | |
def transform_history(history): | |
new_history = [] | |
for chat in history: | |
new_history.append({"parts": [{"text": chat[0]}], "role": "user"}) | |
new_history.append({"parts": [{"text": chat[1]}], "role": "model"}) | |
return new_history | |
# 回應生成函數 | |
def response(message, history): | |
global chat | |
# 將 Gradio 的歷史紀錄轉換為 Gemini 的格式 | |
chat.history = transform_history(history) | |
# 發送訊息到 Gemini API | |
response = chat.send_message(message) | |
response.resolve() | |
# 逐字回傳生成的文字,實現打字機效果 | |
for i in range(len(response.text)): | |
time.sleep(0.05) # 每個字符間隔 0.05 秒 | |
yield response.text[: i+1] | |
# 建立 Gradio 聊天界面 | |
gr.ChatInterface(response, | |
title='Gemini Chat', | |
textbox=gr.Textbox(placeholder="Question to Gemini")).launch(share=True) | |