JuiKuang commited on
Commit
22946ee
·
verified ·
1 Parent(s): 33f5e8f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -15
app.py CHANGED
@@ -1,26 +1,37 @@
1
- #app.py
2
  import time
3
  import gradio as gr
4
- import google.generativeai as genai
5
  import os
 
 
6
 
7
- # 從 Hugging Face secrets 中讀取 API 金鑰(如果需要)
8
- api_key = os.getenv('GOOGLE_API_KEY')
9
  if not api_key:
10
- raise ValueError("請設置 'GOOGLE_API_KEY' 環境變數")
11
 
12
- # 設定 API 金鑰
13
- genai.configure(api_key=api_key)
14
 
15
- # 初始化模型
16
- try:
17
- model = genai.GenerativeModel('gemini-1.5-pro')
18
- chat = model.start_chat(history=[])
19
- print("模型載入成功。")
20
- except Exception as e:
21
- raise ValueError(f"無法載入模型:{e}")
 
 
 
 
 
 
 
22
 
23
- # Gradio 的歷史紀錄轉換為 Gemini 格式
 
 
 
24
  def transform_history(history):
25
  new_history = []
26
  for chat in history:
 
 
1
  import time
2
  import gradio as gr
3
+ import openai
4
  import os
5
+ import requests
6
+ import json
7
 
8
+ # 從 Hugging Face secrets 中讀取 OpenAI API 金鑰
9
+ api_key = os.getenv('OPENAI_API_KEY')
10
  if not api_key:
11
+ raise ValueError("請設置 'OPENAI_API_KEY' 環境變數")
12
 
13
+ # OpenAI API key
14
+ openai_api_key = api_key
15
 
16
+ # 將 Gradio 的歷史紀錄轉換為 OpenAI 格式
17
+ def transform_history(history):
18
+ new_history = []
19
+ for chat in history:
20
+ new_history.append({"role": "user", "content": chat[0]})
21
+ new_history.append({"role": "assistant", "content": chat[1]})
22
+ return new_history
23
+
24
+ # 回應生成函數,使用 requests 來呼叫 OpenAI API
25
+ def response(message, history):
26
+ global conversation_history
27
+
28
+ # 將 Gradio 的歷史紀錄轉換為 OpenAI 的格式
29
+ conversation_history = transform_history(history)
30
 
31
+ url = "https://api.openai.com/v1/chat/completions"
32
+ headers = {
33
+ "Content-Type": "application/json",
34
+ "Authorization": f"Bearer {openai_api_key}"
35
  def transform_history(history):
36
  new_history = []
37
  for chat in history: