First code entering
Browse files
app.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from google import genai
|
| 4 |
+
from google.genai import types
|
| 5 |
+
|
| 6 |
+
# 1. Initialize the Google GenAI Client
|
| 7 |
+
# This automatically looks for an environment variable named GEMINI_API_KEY
|
| 8 |
+
client = genai.Client()
|
| 9 |
+
|
| 10 |
+
def google_chatbot_response(message, history):
|
| 11 |
+
# 2. Set up the system instructions (the chatbot's persona)
|
| 12 |
+
config = types.GenerateContentConfig(
|
| 13 |
+
system_instruction="You are an exceptionally unique and kind chatbot.",
|
| 14 |
+
max_output_tokens=1000
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
# 3. Format the history into the structure Google expects
|
| 18 |
+
formatted_contents = []
|
| 19 |
+
|
| 20 |
+
# Convert past Gradio history turns into Google's format
|
| 21 |
+
for turn in history:
|
| 22 |
+
# turn["role"] will be either "user" or "assistant"
|
| 23 |
+
role = "user" if turn["role"] == "user" else "model"
|
| 24 |
+
formatted_contents.append(
|
| 25 |
+
types.Content(role=role, parts=[types.Part.from_text(text=turn["content"])])
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
# Append the newest user message to the very end
|
| 29 |
+
formatted_contents.append(
|
| 30 |
+
types.Content(role="user", parts=[types.Part.from_text(text=message)])
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
# 4. Request the response from Gemini
|
| 34 |
+
# We use 'gemini-2.5-flash' as it is fast, powerful, and ideal for chat
|
| 35 |
+
response = client.models.generate_content(
|
| 36 |
+
model='gemini-2.5-flash',
|
| 37 |
+
contents=formatted_contents,
|
| 38 |
+
config=config
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
# 5. Return the text response
|
| 42 |
+
return response.text
|
| 43 |
+
|
| 44 |
+
# 6. Create and launch the Gradio ChatInterface
|
| 45 |
+
# We set type="messages" to match the modern history format used above
|
| 46 |
+
chatbot = gr.ChatInterface(
|
| 47 |
+
google_chatbot_response,
|
| 48 |
+
type="messages",
|
| 49 |
+
title="My First Google Gemini Chatbot"
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
chatbot.launch()
|