akhaliq HF staff commited on
Commit
94edfc6
·
verified ·
1 Parent(s): 4b4c47f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -22
app.py CHANGED
@@ -2,25 +2,35 @@ import gradio as gr
2
  import google.generativeai as genai
3
  import os
4
 
5
- # Configure the Gemini API with your API key
6
- genai.configure(api_key=os.environ["YOUR_API_KEY"])
7
-
8
- # Initialize the Gemini Generative Model
9
- model = genai.GenerativeModel("gemini-1.5-flash")
10
-
11
- def chat_with_gemini(user_input, history):
12
  """
13
- Generates a response from the Gemini API based on user input and conversation history.
 
14
 
15
  Args:
 
16
  user_input (str): The latest message from the user.
17
  history (list): The conversation history as a list of tuples.
18
 
19
  Returns:
20
- tuple: The chatbot's reply and the updated history.
21
  """
 
 
 
 
 
 
 
 
22
  try:
23
- # Send the latest message to the Gemini API
 
 
 
 
 
 
24
  response = model.generate_content(
25
  user_input,
26
  generation_config=genai.GenerationConfig(
@@ -32,47 +42,71 @@ def chat_with_gemini(user_input, history):
32
  chatbot_reply = response.text.strip()
33
 
34
  # Append the user input and chatbot reply to the history
35
- history.append((user_input, chatbot_reply))
 
36
 
37
  return history, history
38
  except Exception as e:
39
  error_message = f"An error occurred: {e}"
40
- history.append((user_input, error_message))
41
  return history, history
42
 
43
  with gr.Blocks() as iface:
44
- gr.Markdown("# Google Gemini 1.5 Flash Chatbot")
 
 
 
 
 
 
 
45
 
46
- chatbot = gr.Chatbot()
 
47
 
48
- with gr.Row():
49
- with gr.Column(scale=0.85):
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  user_input = gr.Textbox(
51
  placeholder="Type your message here...",
52
  show_label=False
53
  )
54
- with gr.Column(scale=0.15):
55
  send_button = gr.Button("Send")
56
 
57
  # State to hold the conversation history
58
  history = gr.State([])
59
 
60
- def respond(message, history_state):
61
  """
62
- Handles the user message, generates a response, and updates the conversation history.
 
63
 
64
  Args:
 
65
  message (str): The user's message.
66
  history_state (list): The current conversation history.
67
 
68
  Returns:
69
  tuple: Updated conversation history for display.
70
  """
71
- updated_history, new_history = chat_with_gemini(message, history_state)
72
  return updated_history, new_history
73
 
74
- send_button.click(respond, inputs=[user_input, history], outputs=[chatbot, history])
75
- user_input.submit(respond, inputs=[user_input, history], outputs=[chatbot, history])
 
76
 
77
  if __name__ == "__main__":
78
  iface.launch()
 
2
  import google.generativeai as genai
3
  import os
4
 
5
+ def chat_with_gemini(user_api_key, user_input, history):
 
 
 
 
 
 
6
  """
7
+ Generates a response from the Gemini API based on user input and conversation history,
8
+ using the provided user API key or falling back on a default API key.
9
 
10
  Args:
11
+ user_api_key (str): The user's Google Gemini API key (optional).
12
  user_input (str): The latest message from the user.
13
  history (list): The conversation history as a list of tuples.
14
 
15
  Returns:
16
+ tuple: The updated conversation history with the chatbot's reply.
17
  """
18
+ # Determine which API key to use
19
+ api_key = user_api_key.strip() if user_api_key else os.getenv("DEFAULT_API_KEY")
20
+
21
+ if not api_key:
22
+ # If no API key is available, prompt the user
23
+ history.append(("Bot", "Please enter your Google Gemini API key to start the conversation."))
24
+ return history, history
25
+
26
  try:
27
+ # Configure the Gemini API with the selected API key
28
+ genai.configure(api_key=api_key)
29
+
30
+ # Initialize the Gemini Generative Model
31
+ model = genai.GenerativeModel("gemini-1.5-flash")
32
+
33
+ # Generate a response from the Gemini API
34
  response = model.generate_content(
35
  user_input,
36
  generation_config=genai.GenerationConfig(
 
42
  chatbot_reply = response.text.strip()
43
 
44
  # Append the user input and chatbot reply to the history
45
+ history.append(("User", user_input))
46
+ history.append(("Bot", chatbot_reply))
47
 
48
  return history, history
49
  except Exception as e:
50
  error_message = f"An error occurred: {e}"
51
+ history.append(("Bot", error_message))
52
  return history, history
53
 
54
  with gr.Blocks() as iface:
55
+ gr.Markdown("""
56
+ # Google Gemini Flash 1.5 Chatbot
57
+
58
+ Welcome to the Google Gemini-powered chatbot! You can interact with the bot by typing your messages below.
59
+
60
+ **API Key Setup:**
61
+ - **Option 1:** Enter your own Google Gemini API key in the input field below.
62
+ - **Option 2:** If you leave the API key field empty, the chatbot will use a default API key.
63
 
64
+ > **Note:** Ensure that your API key is kept secure and do not share it publicly.
65
+ """)
66
 
67
+ with gr.Column():
68
+ # API Key Input Section
69
+ with gr.Row():
70
+ api_key_input = gr.Textbox(
71
+ label="Google Gemini API Key (Optional)",
72
+ placeholder="Enter your API key here...",
73
+ type="password",
74
+ lines=1
75
+ )
76
+
77
+ # Chatbot Display
78
+ chatbot = gr.Chatbot()
79
+
80
+ # User Input Row
81
+ with gr.Row():
82
  user_input = gr.Textbox(
83
  placeholder="Type your message here...",
84
  show_label=False
85
  )
 
86
  send_button = gr.Button("Send")
87
 
88
  # State to hold the conversation history
89
  history = gr.State([])
90
 
91
+ def respond(user_api_key, message, history_state):
92
  """
93
+ Handles the user message, generates a response using the provided or default API key,
94
+ and updates the conversation history.
95
 
96
  Args:
97
+ user_api_key (str): The user's API key (optional).
98
  message (str): The user's message.
99
  history_state (list): The current conversation history.
100
 
101
  Returns:
102
  tuple: Updated conversation history for display.
103
  """
104
+ updated_history, new_history = chat_with_gemini(user_api_key, message, history_state)
105
  return updated_history, new_history
106
 
107
+ # Connect the send button and textbox submission to the respond function
108
+ send_button.click(respond, inputs=[api_key_input, user_input, history], outputs=[chatbot, history])
109
+ user_input.submit(respond, inputs=[api_key_input, user_input, history], outputs=[chatbot, history])
110
 
111
  if __name__ == "__main__":
112
  iface.launch()