import os
import textwrap
import google.generativeai as genai
from flask import Flask, request, jsonify, render_template_string
# ==========================================
# CONFIGURATION & SETUP
# ==========================================
app = Flask(__name__)
# Configure the Google Gemini API
# It looks for the GEMINI_API_KEY environment variable
API_KEY = os.getenv("GEMINI_API_KEY")
if not API_KEY:
print("Warning: GEMINI_API_KEY environment variable not set.")
print("Please set it in your Hugging Face Space secrets or Docker environment.")
genai.configure(api_key=API_KEY)
# ==========================================
# FRONTEND TEMPLATE (HTML/CSS/JS)
# ==========================================
HTML_TEMPLATE = """
Deep Research with Google Gemini
"""
# ==========================================
# BACKEND LOGIC
# ==========================================
def get_gemini_response(topic):
"""
Interacts with Google Gemini API to generate a deep research report.
"""
try:
model = genai.GenerativeModel('gemini-pro')
prompt = textwrap.dedent(f"""
Act as an expert researcher. Conduct a deep dive into the following topic: "{topic}".
Your report should follow this structure:
1. **Executive Summary**: A brief overview of the topic.
2. **Key Concepts**: Define the most important terms and ideas.
3. **Historical Context**: How did we get here? (if applicable).
4. **Current State of Affairs**: What is happening right now?
5. **Challenges & Controversies**: What are the debated points?
6. **Future Outlook**: Predictions and trends.
Use Markdown formatting (headers, bolding, lists) to make the report readable.
Be thorough, objective, and detailed.
""")
response = model.generate_content(prompt)
return response.text
except Exception as e:
print(f"Error calling Gemini API: {e}")
raise Exception(f"AI Error: {str(e)}")
# ==========================================
# FLASK ROUTES
# ==========================================
@app.route('/')
def home():
"""Serves the frontend HTML."""
return render_template_string(HTML_TEMPLATE)
@app.route('/api/research', methods=['POST'])
def research():
"""API endpoint to handle research requests."""
data = request.get_json()
if not data or 'topic' not in data:
return jsonify({"error": "No topic provided"}), 400
if not API_KEY:
return jsonify({"error": "Server misconfiguration: GEMINI_API_KEY is missing."}), 500
topic = data['topic']
try:
report = get_gemini_response(topic)
return jsonify({"report": report})
except Exception as e:
return jsonify({"error": str(e)}), 500
# ==========================================
# MAIN ENTRY POINT
# ==========================================
if __name__ == '__main__':
# Run the app on 0.0.0.0 so it is accessible externally in Docker
port = int(os.environ.get('PORT', 7860))
app.run(host='0.0.0.0', port=port)