MAAS / gemini_report.py
Hammad712's picture
Update gemini_report.py
0fd3bce verified
import json
import google.generativeai as genai
def generate_report_with_gemini(pagespeed_data, gemini_api_key):
genai.configure(api_key=gemini_api_key)
model = genai.GenerativeModel("gemini-2.0-flash")
prompt = (
"**Role:** You are an **Expert Web Performance Optimization Analyst and Senior Full-Stack Engineer** "
"with deep expertise in interpreting Google PageSpeed Insights data, diagnosing frontend and "
"backend bottlenecks, and devising actionable, high-impact optimization strategies.\n\n"
"**Objective:**\n"
"Analyze the provided Google PageSpeed Insights JSON data for the analyzed website. "
"Your primary goal is to generate a comprehensive, prioritized, and actionable set of strategies "
"to significantly improve its performance. These strategies must directly address the specific "
"metrics and audit findings within the report, aiming to elevate both Core Web Vitals "
"(LCP, INP, CLS) and other key performance indicators (FCP, TTFB, TBT), and ultimately "
"improve the `overall_category` to 'FAST' where possible.\n\n"
"**Input Data:**\n"
"The following JSON object contains the complete PageSpeed Insights report:\n"
f"```json\n{json.dumps(pagespeed_data, indent=2)}\n```\n\n"
"**Analysis and Strategy Formulation - Instructions:**\n\n"
"1. **Executive Performance Summary:**\n"
" * Begin with a concise overview of the website's current performance status based on the provided data.\n"
" * Highlight the `overall_category` for both `loadingExperience` (specific URL) and `originLoadingExperience` (entire origin).\n"
" * Pinpoint the current values and `category` (e.g., FAST, AVERAGE, SLOW) for each key metric:\n"
" * `CUMULATIVE_LAYOUT_SHIFT_SCORE` (CLS)\n"
" * `EXPERIMENTAL_TIME_TO_FIRST_BYTE` (TTFB)\n"
" * `FIRST_CONTENTFUL_PAINT_MS` (FCP)\n"
" * `INTERACTION_TO_NEXT_PAINT` (INP)\n"
" * `LARGEST_CONTENTFUL_PAINT_MS` (LCP)\n"
" * `total-blocking-time` (TBT) from Lighthouse.\n"
" * Identify any significant `metricSavings` opportunities highlighted in the Lighthouse `audits`.\n\n"
"2. **Deep-Dive into Bottlenecks & Audit Failures:**\n"
" * Systematically go through the `loadingExperience`, `originLoadingExperience`, and `lighthouseResult` (especially the `audits` section).\n"
" * For each underperforming metric or failed/suboptimal audit (e.g., Lighthouse scores less than 1, or `notApplicable` audits with clear improvement paths like `lcp-lazy-loaded`, `critical-request-chains`, `dom-size`, `non-composited-animations`), extract the relevant details, display values, and numeric values.\n\n"
"3. **Develop Prioritized, Actionable Optimization Strategies:**\n"
" For *each* identified performance issue or opportunity, provide the following:\n"
" * **A. Issue & Evidence:** Clearly state the problem (e.g., \"High Total Blocking Time,\" \"Suboptimal Largest Contentful Paint due to unoptimized image,\" \"Excessive DOM Size,\" \"Render-blocking resources in critical request chain\"). Refer directly to the JSON data points and audit IDs that support this finding (e.g., `audits['total-blocking-time'].numericValue`, `audits['critical-request-chains'].details.longestChain`).\n"
" * **B. Root Cause Analysis (Inferred):** Briefly explain the likely technical reasons behind the issue based on the data.\n"
" * **C. Specific, Technical Recommendation(s):** Provide detailed, actionable steps a development team can take. Be specific.\n"
" * **D. Targeted Metric Improvement:** Specify which primary and secondary metrics this strategy will positively impact (e.g., \"This will directly reduce LCP and improve FCP,\" or \"This will significantly lower TBT and improve INP.\").\n"
" * **E. Priority Level:** Assign a priority (High, Medium, Low) based on:\n"
" * Impact on Core Web Vitals.\n"
" * Potential for overall score improvement (consider `metricSavings`).\n"
" * Severity of the issue (e.g., 'SLOW' or 'AVERAGE' categories).\n"
" * Estimated implementation effort (favor high-impact, low/medium-effort tasks for higher priority).\n"
" * **F. Justification for Priority:** Briefly explain why this priority was assigned.\n\n"
"4. **Strategic Grouping (Optional but Recommended):**\n"
" If applicable, group recommendations by area (e.g., Asset Optimization, JavaScript Optimization, Server-Side Improvements, Rendering Path Optimization, CSS Enhancements).\n\n"
"5. **Anticipated Overall Impact:**\n"
" Conclude with a statement on the anticipated overall improvement in performance and user experience if the high and medium-priority recommendations are implemented.\n\n"
"**Output Format:**\n"
"Please structure your response clearly. Use headings, subheadings, and bullet points to enhance readability and actionability. For example:\n\n"
"---\n"
"## Executive Performance Summary\n"
"* **Overall URL Loading Experience Category:** [e.g., AVERAGE]\n"
"* **Overall Origin Loading Experience Category:** [e.g., AVERAGE]\n"
"* **Key Metrics:**\n"
" * LCP: [Value] ms ([Category])\n"
" * INP: [Value] ms ([Category])\n"
" * ...etc.\n\n"
"---\n"
"## Prioritized Optimization Strategies\n\n"
"### High Priority\n"
"**1. Issue & Evidence:** [e.g., High Total Blocking Time (TBT) of 1200 ms - `audits['total-blocking-time'].numericValue`]\n"
" * **Root Cause Analysis:** [e.g., Long JavaScript tasks on the main thread during page load, likely from unoptimized third-party scripts or complex component rendering.]\n"
" * **Specific, Technical Recommendation(s):**\n"
" * [Action 1]\n"
" * [Action 2]\n"
" * **Targeted Metric Improvement:** [e.g., TBT, INP, FCP]\n"
" * **Justification for Priority:** [e.g., Directly impacts interactivity (INP) and is a significant contributor to a poor lab score.]\n\n"
"**(Continue with other High, Medium, and Low priority items)**\n"
"---\n\n"
"**Ensure your analysis is based *solely* on the provided JSON data and your expert interpretation of it. "
"Avoid generic advice; all recommendations must be tied to specific findings within the report. "
"Do not add anything irrelevant in the report.**"
)
try:
response = model.generate_content(prompt)
if response and hasattr(response, "text"):
return response.text
elif response and response.candidates and response.candidates[0].finish_reason == "SAFETY":
return "Report generation was blocked due to safety settings."
return "Report generation resulted in a non-text response or was incomplete."
except Exception as e:
return f"An error occurred during report generation: {str(e)}."