|
import base64 |
|
import os |
|
import gradio as gr |
|
from google import genai |
|
from google.genai import types |
|
|
|
def generate_response(user_input): |
|
try: |
|
client = genai.Client( |
|
api_key=os.environ.get("GEMINI_API_KEY"), |
|
) |
|
|
|
model = "gemini-2.5-pro-exp-03-25" |
|
contents = [ |
|
types.Content( |
|
role="user", |
|
parts=[ |
|
types.Part.from_text(text=user_input), |
|
], |
|
), |
|
] |
|
generate_content_config = types.GenerateContentConfig( |
|
temperature=2, |
|
response_mime_type="text/plain", |
|
) |
|
|
|
full_response = "" |
|
for chunk in client.models.generate_content_stream( |
|
model=model, |
|
contents=contents, |
|
config=generate_content_config, |
|
): |
|
if chunk.text: |
|
full_response += chunk.text |
|
yield full_response |
|
|
|
return full_response |
|
except Exception as e: |
|
return f"An error occurred: {str(e)}" |
|
|
|
|
|
css = """ |
|
.gradio-container { |
|
max-width: 800px; |
|
margin: auto; |
|
} |
|
footer { |
|
visibility: hidden; |
|
} |
|
""" |
|
|
|
|
|
with gr.Blocks(css=css, title="Gemini AI Chat") as demo: |
|
gr.Markdown("# π Gemini AI Chat Interface") |
|
gr.Markdown("Enter your prompt and get AI-generated responses from Google's Gemini model") |
|
|
|
with gr.Row(): |
|
with gr.Column(scale=7): |
|
user_input = gr.Textbox( |
|
label="Your Prompt", |
|
placeholder="Type your message here...", |
|
lines=5, |
|
max_lines=10, |
|
interactive=True, |
|
container=False, |
|
) |
|
with gr.Column(scale=3): |
|
temperature = gr.Slider( |
|
minimum=0.1, |
|
maximum=2.0, |
|
value=1.0, |
|
step=0.1, |
|
label="Creativity (Temperature)", |
|
interactive=True, |
|
) |
|
|
|
submit_btn = gr.Button("Generate Response", variant="primary") |
|
clear_btn = gr.Button("Clear", variant="secondary") |
|
|
|
output = gr.Textbox( |
|
label="AI Response", |
|
placeholder="AI response will appear here...", |
|
lines=10, |
|
max_lines=20, |
|
interactive=False, |
|
) |
|
|
|
examples = gr.Examples( |
|
examples=[ |
|
["Explain quantum computing in simple terms"], |
|
["Write a short poem about artificial intelligence"], |
|
["What are the latest advancements in renewable energy?"], |
|
], |
|
inputs=user_input, |
|
label="Example Prompts", |
|
) |
|
|
|
|
|
submit_btn.click( |
|
fn=generate_response, |
|
inputs=user_input, |
|
outputs=output, |
|
api_name="generate" |
|
) |
|
|
|
clear_btn.click( |
|
fn=lambda: ("", ""), |
|
inputs=[], |
|
outputs=[user_input, output], |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
demo.queue().launch(server_port=7860, share=False) |