JuiKuang commited on
Commit
7d5b6a0
·
verified ·
1 Parent(s): 22946ee

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +36 -22
  2. requirements.txt +2 -1
app.py CHANGED
@@ -32,29 +32,43 @@ def response(message, history):
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:
38
- new_history.append({"parts": [{"text": chat[0]}], "role": "user"})
39
- new_history.append({"parts": [{"text": chat[1]}], "role": "model"})
40
- return new_history
41
 
42
- # 回應生成函數
43
- def response(message, history):
44
- global chat
45
- # 將 Gradio 的歷史紀錄轉換為 Gemini 的格式
46
- chat.history = transform_history(history)
47
-
48
- # 發送訊息到 Gemini API
49
- response = chat.send_message(message)
50
- response.resolve()
51
-
52
- # 逐字回傳生成的文字,實現打字機效果
53
- for i in range(len(response.text)):
54
- time.sleep(0.05) # 每個字符間隔 0.05 秒
55
- yield response.text[: i+1]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
  # 建立 Gradio 聊天界面
58
  gr.ChatInterface(response,
59
- title='Gemini Chat',
60
- textbox=gr.Textbox(placeholder="Question to Gemini")).launch(share=True)
 
32
  headers = {
33
  "Content-Type": "application/json",
34
  "Authorization": f"Bearer {openai_api_key}"
35
+ }
 
 
 
 
 
36
 
37
+ # 設置初始的 prompt_instruction
38
+ prompt_instruction = """
39
+ 你是廖老師的專業小助教,名字叫做 '小確' ,要以專業、熱情、善解人意且非常有禮貌,親切的的口氣,與用戶互動並解答問題:
40
+ """
41
+ prompt_to_gpt = prompt_instruction + message
42
+
43
+ # 新增至 conversation_history
44
+ conversation_history.append({"role": "system", "content": prompt_to_gpt})
45
+
46
+ # 設置請求的數據
47
+ data = {
48
+ "model": "gpt-4o", # 確認使用的模型是 gpt-4 或 gpt-3.5-turbo
49
+ "messages": conversation_history,
50
+ "max_tokens": 200 # 控制生成的最大令牌數
51
+ }
52
+
53
+ # 發送請求到 OpenAI API
54
+ response = requests.post(url, headers=headers, data=json.dumps(data))
55
+
56
+ # 處理回應
57
+ response_json = response.json()
58
+
59
+ # 提取模型的回應並加入歷史紀錄
60
+ if 'choices' in response_json and len(response_json['choices']) > 0:
61
+ model_response = response_json['choices'][0]['message']['content']
62
+ conversation_history.append({"role": "assistant", "content": model_response})
63
+
64
+ # 逐字回傳生成的文字,實現打字機效果
65
+ for i in range(len(model_response)):
66
+ time.sleep(0.05) # 每個字符間隔 0.05 秒
67
+ yield model_response[: i+1]
68
+ else:
69
+ yield "Error: No response from the model."
70
 
71
  # 建立 Gradio 聊天界面
72
  gr.ChatInterface(response,
73
+ title='OpenAI Chat',
74
+ textbox=gr.Textbox(placeholder="Question to OpenAI")).launch(share=True)
requirements.txt CHANGED
@@ -1,2 +1,3 @@
 
1
  gradio
2
- google-generativeai
 
1
+ #requirements.txt
2
  gradio
3
+ openai