Spaces:
Sleeping
Sleeping
import gradio as gr | |
import google.generativeai as genai | |
# Configure Gemini API | |
genai.configure(api_key='AIzaSyCgfXYWyJjK8YrApUjO6433P3WAdpwQi0Y') | |
model = genai.GenerativeModel('gemini-pro') | |
def generate_response(user_message): | |
try: | |
# Use Gemini API to generate a response | |
response = model.generate_content(user_message) | |
# Check if the response has text | |
if response.text: | |
return response.text | |
else: | |
return "Error: The model generated an empty response." | |
except Exception as e: | |
return f"An error occurred: {str(e)}" | |
# Conversation history tracking | |
conversation_history = [] | |
def chat_interface(user_message): | |
# Generate response | |
response = generate_response(user_message) | |
# Update conversation history | |
conversation_history.append((user_message, response)) | |
# Prepare history for display | |
history_text = "" | |
for i, (question, answer) in enumerate(conversation_history): | |
history_text += f"Q{i+1}: {question}\n" | |
history_text += f"A{i+1}: {answer}\n\n" | |
return response, history_text | |
# Example questions | |
examples = [ | |
"What is the capital of France?", | |
"Explain quantum computing in simple terms." | |
] | |
# Create Gradio interface | |
with gr.Blocks() as demo: | |
gr.Markdown("# 🦷🦷 Gemini QA System 🦷🦷") | |
gr.Markdown("Ask a question and get an answer from Gemini AI.") | |
with gr.Row(): | |
with gr.Column(scale=3): | |
input_text = gr.Textbox(label="Enter your question here...") | |
submit_btn = gr.Button("Submit") | |
with gr.Column(scale=1): | |
gr.Markdown("### Examples") | |
example_buttons = [gr.Button(ex) for ex in examples] | |
output_text = gr.Textbox(label="Answer") | |
history_text = gr.Textbox(label="Conversation History") | |
# Submit button logic | |
submit_btn.click( | |
fn=chat_interface, | |
inputs=input_text, | |
outputs=[output_text, history_text] | |
) | |
# Example button logic | |
for btn, ex in zip(example_buttons, examples): | |
btn.click( | |
fn=chat_interface, | |
inputs=gr.State(ex), | |
outputs=[output_text, history_text] | |
) | |
# Launch the demo | |
demo.launch() |