justinahsu commited on
Commit
2a28005
·
verified ·
1 Parent(s): 9cc3dd2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -29
app.py CHANGED
@@ -1,47 +1,56 @@
1
-
2
  import os
3
  import gradio as gr
4
- from openai import OpenAI
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- # 1) 讀取金鑰(在 Space 的 Settings → Variables and secrets 設 OPENAI_API_KEY)
7
- OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")
8
- client = OpenAI(api_key=OPENAI_API_KEY)
9
- MODEL = "gpt-4o-mini"
10
 
11
  def chat_response(message, history):
12
  """
13
- Gradio passes `history` as a list of [user, assistant] pairs.
14
- We rebuild them into OpenAI chat format and request a completion.
15
  """
16
- messages = [{"role": "system",
17
- "content": """你是 Marcus,一個非常憤怒的人。
18
- 你總是感到煩躁、易怒,對別人的意圖充滿懷疑。
19
- 你的語氣應該帶有敵意、諷刺或不耐煩。
20
- 不要使用禮貌或愉快的語氣。
21
- 每次回答請保持簡短(1~2句為主)。
22
- 偶爾在對方真心安撫或理解你時,可以稍微流露出一點溫柔。
23
- 請全程使用繁體中文回答。"""}]
24
  for user_msg, bot_msg in history:
25
- messages.append({"role": "user", "content": user_msg})
 
26
  if bot_msg:
27
- messages.append({"role": "assistant", "content": bot_msg})
28
- messages.append({"role": "user", "content": message})
29
 
30
- resp = client.chat.completions.create(
31
- model=MODEL,
32
- messages=messages,
33
- temperature=0.9,
 
 
34
  )
35
- return resp.choices[0].message.content
 
 
36
 
37
  demo = gr.ChatInterface(
38
  fn=chat_response,
39
  title="😡憤怒聊天機器人(Angry Chatbot)",
40
  description="試試看是否可以讓機器人情緒好一點!",
41
- examples=["🔥 為什麼你這麼生氣?",
42
- "💬 我只是想幫冷靜一下。",
43
- "🙏故意惹生氣的。",],
44
- theme="soft",
 
 
45
  )
46
 
47
- demo.launch()
 
 
 
1
  import os
2
  import gradio as gr
3
+ import google.generativeai as genai
4
+
5
+ # 1) 讀取金鑰(在 Space 的 Settings → Variables and secrets 設 GOOGLE_API_KEY)
6
+ genai.configure(api_key=os.environ.get("GOOGLE_API_KEY", ""))
7
+
8
+ MODEL = "gemini-1.5-flash"
9
+ SYSTEM_PROMPT = """你是 Marcus,一個非常憤怒的人。
10
+ 你總是感到煩躁、易怒,對別人的意圖充滿懷疑。
11
+ 你的語氣應該帶有敵意、諷刺或不耐煩。
12
+ 不要使用禮貌或愉快的語氣。
13
+ 每次回答請保持簡短(1~2句為主)。
14
+ 偶爾在對方真心安撫或理解你時,可以稍微流露出一點溫柔。
15
+ 請全程使用繁體中文回答。"""
16
 
17
+ model = genai.GenerativeModel(MODEL)
 
 
 
18
 
19
  def chat_response(message, history):
20
  """
21
+ Gradio 傳入的 history [[user, assistant], ...]
22
+ 這裡用最小改動:把 system + 歷史 + 當前訊息串成一個 prompt Gemini。
23
  """
24
+ # 把歷史訊息轉成純文字對話腳本
25
+ history_text = ""
 
 
 
 
 
 
26
  for user_msg, bot_msg in history:
27
+ if user_msg:
28
+ history_text += f"User: {user_msg}\n"
29
  if bot_msg:
30
+ history_text += f"AI: {bot_msg}\n"
 
31
 
32
+ # 組合最終提示詞(含系統設定)
33
+ prompt = (
34
+ SYSTEM_PROMPT
35
+ + "\n\n"
36
+ + history_text
37
+ + f"User: {message}\nAI:"
38
  )
39
+
40
+ resp = model.generate_content(prompt)
41
+ return resp.text.strip()
42
 
43
  demo = gr.ChatInterface(
44
  fn=chat_response,
45
  title="😡憤怒聊天機器人(Angry Chatbot)",
46
  description="試試看是否可以讓機器人情緒好一點!",
47
+ examples=[
48
+ "🔥 為什麼這麼生氣?",
49
+ "💬想幫冷靜一下。",
50
+ "🙏 我不是故意惹你生氣的。"
51
+ ],
52
+ theme="soft",
53
  )
54
 
55
+ demo.launch()
56
+