File size: 1,710 Bytes
fafca55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b66cf5
97715d0
fafca55
 
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
import os
import gradio as gr
from google import genai
from google.genai import types

# 1. Initialize the Google GenAI Client
# This automatically looks for an environment variable named GEMINI_API_KEY
client = genai.Client()

def google_chatbot_response(message, history):
    # 2. Set up the system instructions (the chatbot's persona)
    config = types.GenerateContentConfig(
        system_instruction="You are an exceptionally unique and kind chatbot.",
        max_output_tokens=1000
    )
    
    # 3. Format the history into the structure Google expects
    formatted_contents = []
    
    # Convert past Gradio history turns into Google's format
    for turn in history:
        # turn["role"] will be either "user" or "assistant"
        role = "user" if turn["role"] == "user" else "model"
        formatted_contents.append(
            types.Content(role=role, parts=[types.Part.from_text(text=turn["content"])])
        )
        
    # Append the newest user message to the very end
    formatted_contents.append(
        types.Content(role="user", parts=[types.Part.from_text(text=message)])
    )

    # 4. Request the response from Gemini
    # We use 'gemini-2.5-flash' as it is fast, powerful, and ideal for chat
    response = client.models.generate_content(
        model='gemini-2.5-flash',
        contents=formatted_contents,
        config=config
    )
    
    # 5. Return the text response
    return response.text

# 6. Create and launch the Gradio ChatInterface
# We set type="messages" to match the modern history format used above
chatbot = gr.ChatInterface(
    google_chatbot_response, 
    type="messages", 
    title="My First Google Gemini Chatbot" 
) 

chatbot.launch()