File size: 2,139 Bytes
6315267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import gradio as gr
import google.generativeai as genai
import time
import os

GOOGLE_API_KEY=os.getenv('AIzaSyCGMebr9R_p_hF2jbfXj0GlUJRtAI7sc3M')
genai.configure(api_key=GOOGLE_API_KEY)

# model = genai.GenerativeModel('gemini-pro')
# model = genai.GenerativeModel('gemini-1.5-flash-latest')
# chat = model.start_chat(history=[])

safety_settings = [
  {
    "category" : "HARM_CATEGORY_HARASSMENT",
    "threshold" : "BLOCK_MEDIUM_AND_ABOVE"
  },
  {
    "category" : "HARM_CATEGORY_HATE_SPEECH",
    "threshold" : "BLOCK_MEDIUM_AND_ABOVE"
  },  
  {
    "category" : "HARM_CATEGORY_SEXUALLY_EXPLICIT",
    "threshold" : "BLOCK_MEDIUM_AND_ABOVE"
  },  
  {
    "category" : "HARM_CATEGORY_DANGEROUS_CONTENT",
    "threshold" : "BLOCK_MEDIUM_AND_ABOVE"
  },
]

genai.configure(api_key = "AIzaSyD6j1XrvNXktCFReBWo9Z5uB88fgCu6FB0")

model = genai.GenerativeModel(model_name = "gemini-pro-vision",
                              safty_settings = safety_settings)


# Transform Gradio history to Gemini format
def transform_history(history,system_prompt):
    new_history = []
    new_history.append({"parts": [{"text": system_prompt}], "role": "user"})
    for chat in history:
        new_history.append({"parts": [{"text": chat[0]}], "role": "user"})
        new_history.append({"parts": [{"text": chat[1]}], "role": "model"})
    return new_history

def response(message, history):
    global chat
    # The history will be the same as in Gradio, the 'Undo' and 'Clear' buttons will work correctly.
    system_prompt = f"""
    Respond in style of Elon Musk always, in not more than 40 words.
    Your response should be funny and interesting just like Elon Musk.
    """
    chat.history = transform_history(history,system_prompt)
    response = chat.send_message(message)
    response.resolve()

    # Each character of the answer is displayed
    for i in range(len(response.text)):
        time.sleep(0.005)
        yield response.text[: i+20]

gr.ChatInterface(response,
                 title='Chat with Elon Musk (AI)',
                 textbox=gr.Textbox(placeholder="Ask Elon"),
                 retry_btn=None).launch(debug=True)