devbernie commited on
Commit
d120d3f
·
verified ·
1 Parent(s): 883b944

create app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -0
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from google import genai
4
+ from google.genai.types import Tool, GoogleSearch, GenerateContentConfig
5
+ from dotenv import load_dotenv
6
+
7
+ # Load API key từ file .env
8
+ load_dotenv()
9
+ API_KEY = os.getenv("GEMINI_API_KEY")
10
+
11
+ # Cấu hình client của Gemini
12
+ client = genai.Client(api_key=API_KEY)
13
+
14
+ # Công cụ tìm kiếm Google
15
+ google_search_tool = Tool(google_search=GoogleSearch())
16
+
17
+ # Biến lưu trữ model hiện tại
18
+ current_model = "gemini-2.0-flash-exp"
19
+
20
+ # Hàm xử lý hội thoại
21
+ def chatbot_gemini(user_input):
22
+ try:
23
+ response = client.models.generate_content(
24
+ model=current_model,
25
+ contents=user_input,
26
+ )
27
+ reply = response.candidates[0].content.parts[0].text
28
+ return reply, ""
29
+ except Exception as e:
30
+ return f"Đã xảy ra lỗi: {str(e)}", ""
31
+
32
+ # Hàm chuyển đổi model
33
+ def set_model(selected_model):
34
+ global current_model
35
+ current_model = selected_model
36
+ return f"Model hiện tại: {current_model}"
37
+
38
+ # Giao diện Gradio
39
+ with gr.Blocks() as demo:
40
+ gr.Markdown("## Gemini 2.0 Flash Chatbot")
41
+
42
+ chatbot = gr.Chatbot(label="Chatbot")
43
+ user_input = gr.Textbox(label="Nhập câu hỏi của bạn", placeholder="Hỏi bất kỳ điều gì...")
44
+ submit_btn = gr.Button("Gửi")
45
+
46
+ model_dropdown = gr.Dropdown(
47
+ choices=["gemini-2.0-flash-exp", "gemini-2.0-flash-thinking-exp"],
48
+ label="Chọn Model",
49
+ value="gemini-2.0-flash-exp"
50
+ )
51
+ model_status = gr.Textbox(label="Model hiện tại", value=f"Model hiện tại: {current_model}", interactive=False)
52
+
53
+ model_dropdown.change(
54
+ fn=set_model,
55
+ inputs=model_dropdown,
56
+ outputs=model_status
57
+ )
58
+
59
+ submit_btn.click(
60
+ fn=lambda user_input: chatbot_gemini(user_input),
61
+ inputs=user_input,
62
+ outputs=[chatbot, user_input]
63
+ )
64
+
65
+ if __name__ == "__main__":
66
+ demo.launch()