mod4
Browse files
app.py
CHANGED
@@ -7,7 +7,7 @@ api_key = os.getenv("GOOGLE_API_KEY")
|
|
7 |
client = genai.Client(api_key=api_key)
|
8 |
chat = client.chats.create(model="gemini-2.0-flash")
|
9 |
|
10 |
-
#
|
11 |
def respond(
|
12 |
message,
|
13 |
history: list[dict],
|
@@ -18,16 +18,22 @@ def respond(
|
|
18 |
api_key="GEMINI_API_KEY",
|
19 |
):
|
20 |
response = chat.send_message(message)
|
21 |
-
return response.text
|
22 |
|
23 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
demo = gr.ChatInterface(
|
25 |
fn=respond,
|
26 |
-
type="messages", # ✅
|
27 |
-
chatbot=gr.Chatbot(), #
|
28 |
textbox=gr.Textbox(placeholder="輸入訊息...", container=False, scale=7),
|
29 |
-
title="Gemini 2 Chat",
|
30 |
-
description="Gemini 2
|
31 |
theme="soft",
|
32 |
cache_examples=False,
|
33 |
additional_inputs=[
|
|
|
7 |
client = genai.Client(api_key=api_key)
|
8 |
chat = client.chats.create(model="gemini-2.0-flash")
|
9 |
|
10 |
+
# 回應函數(符合 type="messages" 的格式)
|
11 |
def respond(
|
12 |
message,
|
13 |
history: list[dict],
|
|
|
18 |
api_key="GEMINI_API_KEY",
|
19 |
):
|
20 |
response = chat.send_message(message)
|
|
|
21 |
|
22 |
+
# 使用 OpenAI-style 格式的 history
|
23 |
+
user_entry = {"role": "user", "content": message}
|
24 |
+
assistant_entry = {"role": "assistant", "content": response.text}
|
25 |
+
updated_history = history + [user_entry, assistant_entry]
|
26 |
+
|
27 |
+
return response.text, updated_history
|
28 |
+
|
29 |
+
# Gradio Chat Interface
|
30 |
demo = gr.ChatInterface(
|
31 |
fn=respond,
|
32 |
+
type="messages", # ✅ 告訴 Gradio 使用 role/content 格式
|
33 |
+
chatbot=gr.Chatbot(), # 不用再指定 type,會自動使用 interface 的
|
34 |
textbox=gr.Textbox(placeholder="輸入訊息...", container=False, scale=7),
|
35 |
+
title="Gemini 2 Chat (記得上下文)",
|
36 |
+
description="使用 Gemini 2.0 Flash 建立的多輪對話助理。",
|
37 |
theme="soft",
|
38 |
cache_examples=False,
|
39 |
additional_inputs=[
|