CartwrightAIproject's picture
Update app.py
82b5ed2 verified
Raw History Blame Contribute Delete
3.37 kB
import gradio as gr
import google.generativeai as genai
import os
# Configure the API key. We are using the genai module's configure function
# which is the recommended way to set the API key.
# It checks for a 'GOOGLE_API_KEY' environment variable.
genai.configure()
# If you get a ValueError, it means your API key isn't set.
# You will need to add your API key as a Hugging Face Secret in the Settings page of your Space.
# This ensures your key is kept safe and is not exposed in your code.
def get_trend_report(industry):
"""
Generates a trend report for a given industry using the Gemini API with
Google Search grounding to provide up-to-date information.
"""
try:
# Use the 'gemini-2.5-flash-preview-05-20' model which has access to Google Search grounding.
model = genai.GenerativeModel(
'gemini-2.5-flash-preview-05-20',
# This is the correct way to use the Google Search tool.
# We reference it from the genai.GenerativeTools class.
tools=[genai.GenerativeTools.GoogleSearch]
)
# The prompt asks the model to act as a trend analyst and use its tools
# to find recent trends. This prompts the model to use the Google Search tool.
prompt = (f"Act as a professional industry trend analyst. "
f"Please research the most recent and significant trends "
f"in the {industry} industry. Provide a summary of "
f"these trends, their potential impact, and key companies "
f"involved. Be sure to cite your sources.")
# The model is called with the prompt. The 'tool_config' is set to 'AUTO'
# which allows the model to decide when and how to use the Google Search tool.
response = model.generate_content(
prompt,
generation_config=genai.GenerationConfig(
tool_config={"function_calling_config": "AUTO"}
)
)
# Extract the text and any grounding sources.
text = response.text
sources = []
if response.candidates:
candidate = response.candidates[0]
if candidate.grounding_metadata and candidate.grounding_metadata.grounding_attributions:
sources = [
attr.web.uri for attr in candidate.grounding_metadata.grounding_attributions
if attr.web and attr.web.uri
]
# Format the final report with the generated text and sources.
report = f"### Trend Report for {industry}\n\n"
report += text
if sources:
report += "\n\n### Sources\n"
for i, source in enumerate(sources, 1):
report += f"{i}. {source}\n"
return report
except Exception as e:
# A more helpful error message for the user.
return f"An error occurred: {e}"
# Gradio Interface
# The interface consists of a text input for the industry and a markdown output for the report.
demo = gr.Interface(
fn=get_trend_report,
inputs=gr.Textbox(label="Enter an industry"),
outputs=gr.Markdown(label="Trend Report"),
title="AI TrendSpotter",
description="Get up-to-date reports on industry trends using the Gemini API."
)
if __name__ == "__main__":
demo.launch()