Google-AI-Playground / Tabs /Gemini_Chabot_Nightly.py
NotASI's picture
Remove unused code
250b0b9
raw
history blame
2.76 kB
import os
import google.generativeai as genai
from google.generativeai.types import HarmCategory, HarmBlockThreshold
import gradio as gr
from dotenv import load_dotenv
load_dotenv()
GEMINI_API_KEY_NIGHTLY = os.getenv("GEMINI_API_KEY_NIGHTLY")
model_name = "gemini-1.5-flash"
TITLE_NIGHTLY = """<h1 align="center">๐ŸŽฎChat with Gemini 1.5๐Ÿ”ฅ -- Nightly</h1>"""
NOTICE_NIGHTLY = """
Notices ๐Ÿ“œ:
- This app is still in development (extreme unstable)
- Some features may not work as expected
- Currently the chatbot only support text and images
"""
ERROR_NIGHTLY = """
Known errors โš ๏ธ:
- Error when submit messages from uploading files. (**Fixed**)
"""
genai.configure(api_key=GEMINI_API_KEY_NIGHTLY)
model = genai.GenerativeModel(
model_name,
safety_settings={
HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_ONLY_HIGH,
HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_ONLY_HIGH,
HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_ONLY_HIGH,
HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_ONLY_HIGH,
},
generation_config={
"temperature": 1,
"top_p": 0.95,
"top_k": 64,
"max_output_tokens": 8192,
"response_mime_type": "text/plain",
}
)
chat = model.start_chat(history=[])
def clear_chat_history():
chat.history = []
def transform_history(history):
new_history = []
for user_msg, model_msg in history:
new_history.append({"role": "user", "parts": [user_msg]})
new_history.append({"role": "model", "parts": [model_msg]})
return new_history
def chatbot_nightly(message, history):
message_text = message["text"]
message_files = message["files"]
print("Message text:", message_text)
print("Message files:", message_files)
if message_files:
image_uris = [genai.upload_file(path=file_path["path"]) for file_path in message_files]
message_content = [message_text] + image_uris
else:
message_content = [message_text]
response = chat.send_message(message_content, stream=True)
response.resolve()
return response.text
gemini_chatbot_interface_nightly = gr.Chatbot(
height=400,
likeable=True,
avatar_images=(
None,
"https://media.roboflow.com/spaces/gemini-icon.png"
),
show_copy_button=True,
show_share_button=True,
render_markdown=True
)
clear_chat_button = gr.ClearButton(
components=[gemini_chatbot_interface_nightly],
value="๐Ÿ—‘๏ธ Clear"
)
gemini_chatbot_nightly = gr.ChatInterface(
fn=chatbot_nightly,
chatbot=gemini_chatbot_interface_nightly,
title="Gemini 1.5 Chatbot",
multimodal=True,
clear_btn=clear_chat_button
)