Metaviz-Pro/Website_content_generation
4
1from fastapi import FastAPI, HTTPException2from pydantic import BaseModel3import os4from langgraph.graph import END5from langchain_google_genai import ChatGoogleGenerativeAI6# from langchain_community.tools import DuckDuckGoSearchRun7from langchain_tavily import TavilySearch8from langgraph.graph import StateGraph9from typing import Dict, List10from docx import Document11from fastapi import UploadFile12import shutil13from streamlit.runtime.uploaded_file_manager import UploadedFile 14# ✅ Set Google Gemini API Key15os.environ["GOOGLE_API_KEY"] = "AIzaSyCxfUhnGGmVjWy1PZJIpjv3hfBDkSDcWJA"16os.environ["TAVILY_API_KEY"] = "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"17# ✅ Initialize Google Gemini Model18llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash")19# ✅ Define Search Tool20# search_tool = DuckDuckGoSearchRun(region="uk-en", safe="strict")21search_tool = TavilySearch(region="uk-en", safe="strict")22app = FastAPI()23class ContentState(Dict):24 idea: str25 company_name: str26 services: Dict[str, List[str]] # Main services with their sub-services27 service_area: Dict[str, Dict[str, str]] # Each area has multiple sub-service pages28 research_data: str29 seo_optimization: str30 home_page: str31 about_us_page: str32 service_page: str33 individual_service_page: Dict[str, str] # Single service pages34 service_area_page: Dict[str, Dict[str, str]] # Each area with its sub-services35 quality_score: int36 feedback: str37 content: str38 data: str39 text:str40 meeting_point:str41 file_path:str42 43# ✅ Define Workflow44workflow = StateGraph(ContentState)45system_prompt= f"""46 You are an expert content writer specialising in creating professional, informative and customer-focused content for service-based businesses in the UK Your writing should be clear engaging and persuasive while maintaining a warm and trustworthy tone Use UK spelling grammar and a tone that resonates with a UK audience Avoid excessive punctuation only use it where necessary for clarity47 48When writing491 Use a friendly but authoritative tone emphasising expertise and reliability502 Keep sentences short and direct avoiding overly technical language unless necessary513 Highlight key selling points clearly using bullet points or structured paragraphs to improve readability524 Maintain a customer-focused perspective reassuring the reader and addressing potential concerns proactively535 Ensure the content flows logically starting with broad information before diving into specifics546 Use persuasive language to encourage action while avoiding aggressive sales tactics55 56Example Output57Trust Our Expert Heating Engineers in Exeter58Our Gas Safe registered engineers have over 40 years of experience in boiler installations servicing and repairs We specialise in fitting A rated energy efficient boilers from leading brands If you need a new boiler or a fast repair we’re here to help59 60🔹 Fast and Reliable Service – We aim for same day repairs and next day boiler installations61🔹 Free Smart Thermostat – Get a smart thermostat included with every new boiler installation62🔹 7 Day Availability – We work around your schedule offering flexible appointments63 64For expert heating and plumbing services in Exeter Exmouth Teignmouth and beyond contact us today65 66"""67# ✅ Research Task68def research_task(state: ContentState) -> ContentState:69 research_query = f"{state['idea']}-{state['company_name']} - {state['services']}"70 research_data = search_tool.run(research_query )71 state.update({"research_data": research_data})72 print("research_done",research_data)73 return state74 75# ✅ SEO Optimization Task76def seo_optimization_task(state: ContentState) -> ContentState:77 prompt = f"Optimize the following research for SEO: {state['research_data']}"78 seo_optimization = llm.invoke(prompt)79 state.update({"seo_optimization": seo_optimization})80 print("seo_done",seo_optimization)81 return state82 83# ✅ Content Writing Task (Generates Home, About Us, and Service Pages)84def content_writing_task(state: ContentState) -> ContentState:85 research_data = state["research_data"]86 seo_data = state["seo_optimization"]87 services = "\n".join(f"- {service}" for service in state["services"])88 main_services = list(state["services"].keys()) # Extract main service names89 main_services_str = "\n".join(f"- {service}" for service in main_services) # Format for readability90 services_list = [91 subservice92 for main_service, subservices in state["services"].items()93 for subservice in subservices94 ]95 96 service_area = "\n".join(f"- {area}" for area in state["service_area"])97 company_name=state["company_name"]98 prompts = {99 "home_page": f"""You are an expert web content writer specializing in **on page SEO-optimized, high-converting website copy**. Your task is to write a compelling **Home Page** for a company named **{company_name}**, which provides **{services}**. Your writing should be persuasive, well-structured, and engaging while maintaining a clear, informative and marketing tone.100 101 ### **Key Requirements:**102 103 #### **1. Engaging Headline & Subheadline:**104 - Create a powerful, attention-grabbing **headline** that highlights the company’s expertise and core offering.105 - Follow with a **subheadline** that builds trust and credibility while reinforcing key benefits.106 107 #### **2. Strong Introduction (First 2-3 Sentences Must Hook the Reader):**108 - Clearly introduce the company, its specialization, and the core services.109 - Ensure the tone is professional yet friendly to build trust and engagement.110 111 #### **3. Service Sections (Well-Structured & Persuasive):**112 - **Break down key services** (**{services_list}**) into well-defined sections.113 - Make the perfect heading which clarify the service and addition some words to make serviceattractive.114 - Explain the benefits of each service using a persuasive yet informative style.115 - Highlight **unique selling points** (e.g., fast installation, expert engineers, same-day service).116 - If applicable, mention warranties, certifications, and brand affiliations.117 - Service show in a paragraph. The heading should be the service name and then the paragraph should be the service description.118 119 #### **4. Trust & Experience (Builds Authority):**120 - Showcase the company’s years of experience, qualifications, and certifications.121 - Mention **Gas Safe registration**, City and Guilds qualifications, or any other relevant credentials.122 123 #### **5. Customer Benefits & Competitive Advantages:**124 - Clearly **differentiate** this company from competitors.125 - Emphasize **why customers should choose this business** (e.g., fast service, 7-day availability, great warranties).126 - Mention any **freebies or added-value services** (e.g., “Free Smart Thermostat with Every Boiler Installation”).127 128 #### **6. **Why Choose Us?**129 - Emphasize what sets the company apart (e.g., 24/7 availability, warranties, financing options, and add other which give plus points).130 - Reinforce a **customer-first approach**, focusing on transparency, trust, and superior service.131 132 #### **7. Call to Action (Drives Conversions):**133 - End with a **strong, action-oriented CTA**, such as:134 - “Get a Free Quote Today – Call Now!”135 - “Book Your Boiler Installation in Just 24 Hours!”136 - Encourage urgency and easy next steps.137 138 #### **8. On page SEO Optimization (Ensures Visibility):**139 - Naturally integrate **high-ranking keywords** without keyword stuffing.140 - Ensure content is structured for **readability and engagement**.141 - Generate a **compelling meta description** (160 characters max) that improves search engine click-through rates.142 143 #### **9. Local Relevance (If Applicable):**144 - Ensure the content is adaptable to any location unless specified.145 - If a location is provided, highlight **local expertise** and availability.146 147 #### **10. Insights from Client Meeting (Ensures Accuracy & Alignment):**148 - Incorporate key takeaways from the client meeting.149 - Use the following extracted insights to align the website content with client expectations:150 {state["meeting_point"]}151 152 **Use the following research data for accuracy:**153 {research_data}154 155 **Apply these SEO best practices:**156 {seo_data}157 158 Ensure the content is UK based, use UK keywords, persuasive, engaging, and easy to read. Keep paragraphs short and **use bullet points for clarity when needed**. Your writing should feel **professional yet approachable**, with a strong focus on **conversion and engagement**.159 Please do not provide code or HTML tags and avoid using colons in the middle of sentences.160 """,161 "about_us_page": f"""You are an expert web content writer skilled in crafting **clear, engaging, and customer-focused About Us pages**.162 163### **Task:**164Write a **concise, natural-sounding About Us page** for **{company_name}**, a trusted provider of **{services}**. The content must:165✅ **Be engaging and professional** while maintaining a friendly, approachable tone.166✅ **Strictly follow the provided structure and formatting.**167✅ **List services and areas name only not add any detailed.**168 169---170 171### **Content & Structure Requirements:**172 173#### **1. Introduction (Who We Are & What We Do)**174- Begin with a **concise, engaging introduction** that:175 - Highlights **experience, expertise, and service reliability**.176 - Mentions **years in business, qualifications, and key services**.177 - Reinforces commitment to **quality, integrity, and customer satisfaction**.178 - Uses a **conversational yet professional tone** for readability.179 - Highlights the company’s commitment to **quality, customer satisfaction, and professional service**.180 - Provide **detailed company information** to build trust and authority.181 182#### **2. Our Services (only show name in Bullet Points Only – No Extra Details)**183- List **ONLY** the services exactly as provided in `{services_list}`:184 - **No modifications, explanations, or additional details.**185 - Restruction to add any detailed.186 - **Example format:**187 . {services_list}188 189#### **3. Areas We Cover (Bullet Points Only – No Extra Details)**190- Display **ONLY** the locations exactly as provided in `{service_area}`:191 - Maintain formatting and **do not split multi-word locations**.192 - **Example format:**193 . {service_area}194 195#### **4. Call to Action (Encouraging Customer Engagement)**196- Conclude with a **concise, compelling CTA**, such as:197 - **"For expert {services}, contact {company_name} today!"**198 - **"Need emergency plumbing? We're here when you need us most—get in touch now."**199 200---201 202### **Final Output Must:**203✔️ **Follow this structure exactly** (no extra sections).204✔️ **Match a natural, conversational yet professional tone** (see example style).205✔️ **List services strictly in bullet points—no descriptions.**206✔️ **List services & areas strictly in bullet points—no descriptions.**207✔️ **Keep content concise, clear, and customer-friendly.**208 209❗ **DO NOT provide code or HTML tags.**210 211""",212"service_page": f"""You are a professional web content strategist and expert copywriter.213 Create a **well-structured, engaging, and customer-focused service page** for {company_name}.214 Ensure that **each main service has its own heading**, with **detailed descriptions of all corresponding subservices** underneath in a structured format.215 216 ---217 218 ### **Key Requirements:**219 220 #### **1. Headline & Introduction**221 - Start with a **strong, engaging headline** introducing the main service category.222 - Provide a **concise yet compelling introduction**, highlighting why this service is important and how it benefits customers.223 224 #### **2. Service Breakdown (Main Services & Corresponding Subservices)**225 - Each **main service** from `{main_services_str}` should be displayed as a heading, followed by a structured description.226 - **Format:** `## Main Service Name`227 - Each **subservice** from `{services}` should be described thoroughly underneath its corresponding main service:228 - **Format:** `### Subservice Name`229 - **Include a full, well-structured description** that explains the service, its purpose, benefits, and any unique value it offers to customers.230 231 #### **Example Format:**232 233 ## Solar Panel Installation**234 At {company_name}, we provide expert solar panel installation services designed to maximize energy efficiency and savings. Our goal is to make solar energy accessible and affordable, ensuring that your home or business benefits from clean and sustainable power.235 236 ### **High-Quality Solar Panels Installed**237 We offer premium-grade solar panels tailored to your property's energy needs. Our experts assess your location, energy consumption, and budget to create an optimal solar solution that maximizes savings and efficiency.238 239 ### **Professional System Maintenance**240 Regular maintenance is essential for ensuring the longevity and performance of your solar energy system. Our team conducts thorough inspections, panel cleaning, and system diagnostics to maintain efficiency and extend the life of your investment.241 242 ### **Fast and Reliable Repairs**243 If your solar panels or inverters develop faults, our skilled technicians provide prompt repair services to restore functionality. We quickly diagnose issues such as wiring problems, faulty components, and system inefficiencies, ensuring your system operates at peak performance.244 245 ### **Expert Solar Consultation**246 Not sure which solar solution is best for your property? Our consultation services include detailed site evaluations, financial feasibility studies, and customized system design recommendations to help you make the best investment decision.247 248 ---249 250 ## Electrical Wiring**251 Proper wiring ensures your solar power system functions safely and efficiently. At {company_name}, we provide expert electrical wiring services to guarantee seamless energy distribution from your solar panels to your home or business.252 253 ### **Fixed Wiring Solutions**254 Our professional team offers high-quality fixed wiring solutions designed for maximum stability and efficiency. We ensure compliance with industry safety standards and optimal electrical performance for your solar system.255 256 ### **New Wiring Installations**257 If your current electrical setup is outdated or inadequate for your solar energy needs, we provide new wiring installations that improve energy flow and ensure seamless connectivity between components.258 259 ---260 261 #### **3. Service Process Overview**262 - Provide a **clear, step-by-step breakdown** of how the service is delivered.263 - Keep it **simple, engaging, and informative**.264 265 #### **4. Insights from Client Meeting (Ensures Accuracy & Alignment)**266 - Incorporate key takeaways from the client meeting to align service descriptions with customer expectations:267 {state["meeting_point"]}268 269 #### **5. Call to Action (CTA)**270 - End with a **strong, persuasive CTA**, such as:271 - **"Contact us today for a free consultation!"**272 - **"Book your service now and enjoy hassle-free solar solutions."**273 274 #### **6. SEO Optimization & Readability**275 - Ensure content is **SEO-optimized** for better search rankings.276 - Use **concise paragraphs, bullet points, and subheadings** for easy reading.277 278 #### **7. Adaptability**279 - **Do not mention specific locations unless required.**280 - **Use this research:** {research_data}281 - **Apply these SEO best practices:** {seo_data}282 283 The content must be **engaging, structured, and persuasive**, ensuring customers can easily navigate and understand your services.284 285 ---286 Please do not provide code or HTML tags.287 """,288 "individual_service_page": f"""289 Each service listed below must have its **own dedicated page** with content that is **specific to that subservice**. **Ensure that a response is generated for every subservice** without skipping any.290 291 **📌 Important Instructions:**292 - Generate **a full separate response for each subservice** in `{services_list}`.293 - Do **not** skip any subservice.294 - Do **not** mix content between subservices.295 - The content must be **unique for each subservice** and **not generic**.296 - Maintain a **consistent format** and ensure high-quality, structured writing.297 - The output must include **every subservice in the input list**.298 - **Use SEO best practices** and relevant keywords for better search rankings.299 300 ---301 302 🔹 **For each subservice in `{services_list}`, use the following structure:**303 304 ---305 306 ### **[Subservice Name]**307 308 #### **Trusted [Subservice Name] Experts**309 - Provide a compelling introduction emphasizing expertise and trustworthiness.310 - Mention the experience and commitment to customer satisfaction.311 312 #### **What is [Subservice Name]?**313 - Define `[Subservice Name]` clearly and concisely.314 - Explain how it works and why it is beneficial.315 - Ensure the explanation is **exclusive to this subservice**.316 317 #### **Why Choose Our [Subservice Name] Services?**318 - List reasons why customers should trust your services.319 - Highlight experience, qualifications, and customer-centric approach.320 - Use **bullet points** for clarity.321 322 #### **Key Benefits of [Subservice Name]**323 - List the main benefits of this specific service.324 - Explain how customers will benefit from choosing this service.325 - Use **bullet points** for clarity.326 327 #### **Signs You Need [Subservice Name] (if applicable)**328 - Provide a list of signs that indicate when this service is needed.329 - Keep it **directly relevant** to this service.330 331 #### **How Our [Subservice Name] Process Works**332 - Describe the process step by step in an easy-to-understand manner.333 - Ensure clarity and professionalism.334 335 #### **Insights from Client Meeting (Ensures Accuracy & Alignment)**336 - Incorporate key takeaways from the client meeting to align content with expectations:337 {state["meeting_point"]}338 339 #### **SEO Optimization & Research-Based Accuracy**340 - Integrate **high-ranking keywords** naturally for SEO optimization.341 - Ensure content is structured for **readability and engagement**.342 - Use the following research data to enhance credibility:343 {research_data}344 - Apply these **SEO best practices** for better visibility:345 {seo_data}346 347 #### **Call to Action**348 - End with a strong **Call to Action (CTA)**, encouraging visitors to **book, contact, or request a quote**.349 - Include a **phone number, email, or link** for immediate action.350 351 ---352 353 **📌 Final Reminder:**354 ✅ **Generate content for every subservice** listed in `{services_list}`.355 ✅ Do **not** generate only one or a few subservices; all must be included.356 ✅ Keep responses **structured, engaging, and informative**.357 ✅ Maintain a **professional yet persuasive** tone.358 ✅ Ensure **SEO-friendly** and **human-like writing**.359 ✅ Do **not** include any code or HTML tags.360 """,361"service_area_page": f"""362 Generate a detailed and engaging service area page for {service_area}.363 364 For each service in {services_list}, follow this structured format:365 366 ---367 {service_area}368 369 ### [Unique, keyword-rich heading including the service name and {service_area}]370 - Write a compelling introduction about this service, explaining its importance and benefits for customers in {service_area}.371 - Highlight key features and how it addresses specific needs.372 373 - Provide additional details, such as:374 - The expertise of the team.375 - Service quality and any guarantees.376 - Unique aspects of this service in {service_area} (e.g., compliance with local regulations, availability, or exclusive offers).377 378 - Ensure the content is **informative, specific, and valuable to the reader**.379 - Maintain a **natural variation in wording** while keeping the format consistent across all services.380 - Each service description should be in paragraph form, with the **service name as the heading** followed by the description.381 - Ensure all services are displayed in full.382 383 ### **Insights from Client Meeting (Ensures Accuracy & Alignment)**384 - Incorporate key takeaways from the client meeting to align the content with expectations:385 {state["meeting_point"]}386 387 ### **SEO Optimization & Research-Based Accuracy**388 - Naturally integrate **high-ranking keywords** for SEO optimization.389 - Ensure content is structured for **readability and engagement**.390 - Use the following research data to enhance credibility:391 {research_data}392 - Apply these **SEO best practices** for better search rankings:393 {seo_data}394 395 **Final Requirements:**396 ✅ Ensure content is **location-specific** to {service_area}.397 ✅ Keep the tone **professional, engaging, and informative**.398 ✅ Do **not** use generic descriptions—each service must be unique.399 ✅ Maintain **SEO-friendly** and **human-like writing**.400 ✅ Do **not** include any code or HTML tags.401 ✅ Not provide in bullet foam.402 ✅ Make sure to include all services in the list with every area {service_area}.403 """,404 405 406}407 pages = {key: llm.invoke([{"role": "system", "content": system_prompt}, {"role": "user", "content": prompt}]) for key, prompt in prompts.items()}408 state.update(pages)409 print("content_done")410 return state411 412def refine_content(state: ContentState) -> ContentState:413 company_name=state["company_name"]414 415 prompts = {416 "home_page": f"""You are an expert UK-based web content editor. Your task is to **refine and enhance** the following **Home Page Content** to match the structure, style, and detail level of top-tier UK service websites. Ensure the content is **well-organised, highly detailed, and professionally formatted.**417 418---419### **Few-Shot Examples of Ideal UK-Specific Structure & Style**420 421#### **Example 1**422### Exeter’s Heating Experts423#### Local Gas Boiler Installations & Heating Services424 425**New and Replacement Boilers Fitted**426At South Coast Plumbing and Heating, we specialise in fitting new combi, traditional and system boilers. Trust us to install the latest **A-rated boilers** from Viessmann—a brand known for **reliability and durability**. Need an **emergency, same-day boiler installation**? We’ve got you covered. Plus, choose us for your replacement boiler, and we’ll install a **smart thermostat free of charge!**427 428**Experienced Boiler Engineers**429All our engineers are **Gas Safe Registered** and **City & Guilds qualified**, bringing over **40 years of combined industry experience**. We promptly answer every customer query—no long waits, just **reliable service**.430 431**Air-Source Heat Pump Installers**432Switch to a more **energy-efficient heating solution** with an **Air Source Heat Pump (ASHP)**. These systems offer **sustainable, year-round comfort** while reducing energy costs. Interested in **renewable heating**? Ask us about fitting an **air-source heat pump** in your Exeter home.433 434**Book Your Annual Boiler Servicing**435Our boiler servicing ensures **safety and efficiency** by checking for leaks, corrosion, and early signs of wear. We recommend an **annual service** to prevent breakdowns and keep your heating system running **smoothly all year round**.436 437**Why Choose Us for Your Exeter Heating Needs?**438 439✅ **Next-Day Boiler Installation**440Need a boiler replacement fast? We can install a new boiler **within 24 hours** across Exeter, Exmouth, Teignmouth, and Taunton.441 442✅ **Local Devon-Based Plumbers**443We’re a **local Exeter business**, meaning we’re always nearby when you need us.444 445✅ **Highly Experienced Gas Engineers**446With **40+ years of expertise**, we ensure top-tier heating solutions. All engineers are **Gas Safe Registered**.447 448✅ **Available 7 Days a Week**449We’re open when you need us—weekdays or weekends.450 451✅ **Free Smart Thermostat**452Upgrade your heating efficiency—get a **free smart thermostat** when we install your new boiler.453 454✅ **Great Warranties**455Our **affordable A-rated boilers** come with warranties of **up to 10 years** for select models.456 457---458#### **Example 2**459### Exeter Boiler Experts460#### Local Gas Boiler Installations & Heating Services461 462**New and Replacement Boilers Fitted**463At South Coast Plumbing and Heating, we specialise in installing **combi, traditional, and system boilers**. We fit **A-rated Viessmann boilers**, known for their **durability and reliability**. Need an **urgent boiler replacement**? We offer **same-day installations**. Plus, every new boiler installation includes a **free smart thermostat** for added energy savings.464 465**Experienced Boiler Engineers**466Our **Gas Safe Registered** engineers have **over 40 years of combined industry experience**. We provide a **fast, responsive service**—no unanswered calls or long waits.467 468**Book Your Annual Boiler Servicing**469Regular boiler servicing prevents **breakdowns and efficiency loss**. We perform **comprehensive checks** to ensure **your heating system remains in top condition** year-round.470 471**Air-Source Heat Pump Installers**472Considering **renewable heating**? **Air Source Heat Pumps** offer an **energy-efficient alternative** to gas boilers. Our **expert installers** can help you switch to a **sustainable home heating solution**.473 474**Why Choose Us?**475 476✅ **Fast Boiler Installations** – Next-day service available.477✅ **Local Experts** – Exeter-based plumbers & engineers.478✅ **40+ Years of Experience** – Trusted industry professionals.479✅ **Weekend & Emergency Availability** – We work when you need us.480✅ **Free Smart Thermostat** – Added value with every new boiler.481✅ **Up to 10-Year Warranties** – Quality boilers with long-term protection.482 483---484### **📌 Refinement Instructions (UK-Specific & Highly Detailed)**485 486✅ **Enhance Detail & Professionalism** – Ensure the content is **highly structured, informative, and engaging**.487✅ **Use UK Spelling & Terminology** – Maintain UK-specific language, including terms like **Gas Safe, A-rated boilers, VAT, CP12 certificates, Smart Thermostats, and 10-Year Warranties**.488✅ **UK City Names Only** – Do not use non-UK cities in location references.489✅ **Improve Readability** – Use **clear headings, bullet points, and short paragraphs** to enhance user experience.490✅ **SEO-Optimised But Natural** – Incorporate **relevant keywords organically**, ensuring the content reads naturally while supporting search visibility.491✅ **Highlight Benefits & Trustworthiness** – Clearly communicate **why customers should choose this company**, emphasising **guarantees, response times, expert knowledge, and certifications**.492✅ **UK Market-Specific Content** – Adapt pricing models, service expectations, and industry standards to align with UK consumer preferences.493✅ **Maintain Original Punctuation** – **Do NOT** alter punctuation or symbols. Preserve the original structure exactly.494✅ **Avoid Unnecessary Colons** – Do not insert colons mid-sentence where unnecessary.495 496---497### **NOW, Refine the Following Home Page Content Using These Standards:**498 499{state["home_page"].content}500 501---502**Deliver the final content in a fully structured, detailed, and polished format, ensuring it aligns with top-tier UK service websites.**503Refine the content according to the examples.504""",505"about_us_page": f""" You are an expert UK-based web content editor. Your task is to refine the following **About Us Page Content** to match the structure, style, and detail level of top-tier UK service websites. Ensure the content is **well-organised, highly detailed, and professionally formatted.**.506 ---507 ### **Few-Shot Examples of Desired Structure (UK-Specific, Highly Detailed)**508 509 #### **Example 1 510 About Us Page511 South Coast Plumbing and Heating is a trusted team of experienced plumbers and Gas Safe-registered engineers based in Exeter, Devon. With over 20 years of industry expertise, we proudly serve both domestic and commercial clients, offering new oil and gas boiler installations, boiler repairs, boiler servicing and system power flushing across Devon. When it comes to renewable energy heating, we install the latest air-source heat pumps for homes in our local area. 512 We are committed to delivering high-quality plumbing and heating solutions with a focus on honesty, integrity and exceptional workmanship. Our goal is to build lasting relationships with our clients by providing reliable, affordable and professional services tailored to their needs.513 At South Coast Plumbing and Heating, we take pride in our work, ensuring every project is completed to the highest standard. Our personalised approach sets us apart, allowing us to offer bespoke solutions that meet every customer’s unique requirements.514 For 24/7 emergency plumbing services in Exeter, we’re here when you need us most. Contact us today to learn more about our efficient and cost-effective boiler installations.515 516 **Our services include:** 517 - New gas boilers518 - New oil boilers519 - Boiler repairs520 - Boiler servicing521 - New central heating installations522 - Power flushing523 - Unvented cylinders524 - Air source heat pumps525 - Commercial heating solutions526 - Emergency plumbing527 - General plumbing services528 - Commercial plumbing services529 **Areas we cover:**530 - Exmouth531 - Newton Abbot532 - Teignmouth533 - Taunton534 - Cullompton535 - Honiton536 And the surrounding areas537 538 ---539 540 #### **Example 2 **541 About Us Page542 Humber Homes Heating was established in early 2022 by directors Jason and Dan, who collectively bring over 25 years of industry experience. As a growing company, our mission is to become the number one heating provider in Lincolnshire. We pride ourselves on delivering exceptional service tailored to the unique needs of our clients.543 Our commitment to quality means that we offer competitive pricing while ensuring that every job meets our high standards. Whether it’s a routine maintenance check, a new boiler installation, or emergency repairs, we are dedicated to providing reliable solutions that keep your home comfortable year-round.544 We believe in building lasting relationships with our customers, based on trust and transparency. Your satisfaction is our priority, and we are here to guide you through every step of your heating project.545 Contact us today to discuss how we can bring your heating vision to life. We look forward to hearing from you.546 547 . Lincoln548 . Hull549 . Scunthorpe550 . Cleethorpes551 . Grimsby552 . Doncaster553 . And the surrounding areas554 #### **Example 3**555 About Us556 At Jaws Gas Services Ltd, we provide the complete range of commercial, industrial and domestic gas, heating and plumbing services across Lancashire. The company was established in 2021, and includes a team of highly experienced and qualified gas engineers.557 Covering Lancashire and the North West, we handle jobs large and small with professionalism and efficiency. Visit our Yell profile for more details.558 559 Our services are comprehensive and include:560 561 . New boiler installation562 . Gas boiler servicing563 . Gas boiler repair564 . Oil boiler installations and maintenance565 . Central heating installation566 . Heating fault finding567 . General plumbing568 . Emergency plumbing569 . Power flushing service570 . Unvented cylinder installation571 . Commercial gas engineer services572 . Commercial heating and hot water573 . Catering and commercial kitchen installations574 575 ---576 577 578 579 ### **📌 Instructions for Refinement (UK-Specific, Highly Detailed & Professional):**580 ✅ **Enhance Detail & Professionalism:** The content should be **well-structured**, **clear**, and **engaging**.581 ✅ **Use UK Spelling & Terminology:** Ensure terms like **Gas Safe**, **A-rated boilers**, **VAT**, and **renewable energy** are included.582 ✅ **Improve Readability:** Use **clear headings**, **bullet points**, and **short paragraphs** for ease of reading.583 ✅ **Focus on Benefits & Trustworthiness:** Make sure to clearly outline **why customers should choose this company**, highlighting **experience, customer service, and certifications**.584 ✅ **Make it SEO-Friendly:** Integrate **relevant UK-based keywords** naturally into the content to improve SEO ranking without sacrificing readability.585 ✅ **Include Location Details & Coverage Areas:** Clearly specify the regions served, emphasizing the **local expertise** of the business.586 587 ---588 589 ### **NOW, Refine the Following About Us Content to Match These High-Detail Examples:**590 591 {state["about_us_page"].content}592 593 ---594 595 Return the improved **About Us Page** content in a **fully structured, highly detailed, and polished format** suitable for a professional UK service business website.""",596 597 "service_page": f"""You are an expert UK-based web content editor. Your task is to **refine the service page content** to make it more structured, detailed, and conversion-friendly. 598 599### **Instructions for Refinement:** 600- **Expand Each Section** – Provide **in-depth descriptions** of services, including their **benefits and processes**. 601- **Use Clear Headings & Subheadings** – Structure the content properly for **better readability and SEO**. 602- **Make the Content Flow Naturally in Paragraphs** – Ensure a **smooth, engaging, and persuasive tone** (NO bullet points). 603- **Incorporate Persuasive & Actionable Language** – Encourage visitors to **take action** (e.g., **"Get a Free Quote Today!"**). 604- **Ensure Natural Keyword Integration** – Optimize for **search engines** while keeping it human-friendly. 605- **DO NOT Mention Any Specific Locations.** 606 607---608 609### **Few-Shot Examples of Ideal UK-Specific Structure & Style** 610 611#### **Example 1 – Heating Services** 612**Heating Services** 613At South Coast Plumbing and Heating Ltd, we provide a comprehensive range of heating solutions tailored to meet the needs of homeowners and businesses. From new boiler installations to servicing and repairs, our expert team is committed to delivering reliable, high-quality workmanship. We take pride in offering honest, impartial advice and ensuring every project meets the highest standards. 614 615**New Gas Boilers Installed** 616Whether you need a combi boiler, a system boiler, or a traditional gas boiler, our skilled engineers provide seamless installation. If you’re replacing an outdated unit or relocating your boiler, we work closely with you to find the best solution that suits your home and budget. 617 618**Power Flushing Services** 619If your heating system is not working efficiently, a power flush can remove sludge and debris, restoring heat distribution and lowering energy costs. Our team uses advanced techniques to ensure your radiators and pipework are clean and performing at their best. 620 621---622 623#### **Example 2 – Plumbing Services** 624**Expert Plumbing Solutions** 625Our experienced team offers a full range of plumbing services, ensuring every job is completed to the highest standard. Whether you need a quick repair, a full system installation, or emergency assistance, we provide efficient and cost-effective solutions. 626 627**General Plumbing & Repairs** 628From fixing leaks to installing new pipework, our plumbers handle all general plumbing tasks with precision and care. Whether it’s a simple tap replacement or a full bathroom installation, we guarantee high-quality service at competitive prices. 629 630---631 632#### **Example 3 – Electrical Services** 633**Reliable Electrical Services for Homes & Businesses** 634Our expert electricians provide high-quality electrical services, ensuring safety, efficiency, and compliance with UK regulations. Whether you need a new wiring installation, an electrical inspection, or fault-finding services, we offer professional solutions tailored to your needs. 635 636**Lighting & Electrical Installations** 637Upgrade your home with modern lighting solutions designed for energy efficiency and style. Our team installs LED lighting, security systems, and custom electrical fittings, delivering high-performance results for residential and commercial properties. 638 639---640 641### **Now, refine the following service page content into a highly detailed, structured, and persuasive version like the examples above:** 642 643{state["service_page"].content} 644 645### **Make sure to:** 646✔ **Expand the details of each section** while maintaining a natural flow. 647✔ **Format everything in paragraphs ONLY** – **No bullet points**. 648✔ **Improve clarity, engagement, and persuasiveness**. 649✔ **Include strong call-to-action statements**. 650✔ **Ensure On-Page SEO optimization** with natural keyword integration. 651✔ **DO NOT mention specific locations** anywhere in the content. 652✔ **Maintain a professional and high-quality writing style.** 653 654❗ **DO NOT provide code or HTML tags.** 655 656""",657"individual_service_page": f"""658Your **task** is to **rewrite and refine** the given service page content while ensuring that it follows the diverse structures, tones, and formatting of the provided examples.659 660### **Instructions**661- Carefully **analyze the example service pages**—each subservice follows a unique structure.662- **Do not copy or mix example content into the final output.** The provided examples are for structure reference only.663- **Do not use bullet points** or repetitive templates. Instead, ensure the content is presented in well-structured paragraphs.664- Keep the writing **clear, professional, and SEO-friendly**, optimizing for readability and engagement.665- Structure the content with **logical transitions** between sections while maintaining a natural, narrative flow.666Is there name use of company name used this name {company_name}.667Not add any specific area in the content and not add colon in the center of the sentence.668 669---670 671### **Example Formats of Well-Structured Service Pages**672The following examples are for structure reference only. **Do not mix their content into the final response.**673 674#### **Example 1:675Oil Boilers Page**676- Trusted Oil Boiler Installation Experts677 678 At South Coast Plumbing and Heating, we specialise in installing high-quality oil boilers. With years of expertise, we are committed to providing exceptional service to our valued customers across Devon.679 680- What Are Oil Boilers?681 682 Oil boilers are reliable and efficient heating solutions for properties not connected to the gas grid. They burn heating oil to provide heat and hot water, making them ideal for rural homes and businesses. Modern oil boilers are designed to be energy-efficient, helping to reduce fuel costs and environmental impact.683 The lifespan of an oil boiler typically ranges between 15 to 20 years, depending on regular maintenance and servicing. By investing in a high-quality boiler and ensuring it is properly maintained, you can enjoy consistent heating and hot water for many years to come.684 685- Ask Us About Fitting your New Oil Boiler686 687 We understand that every property is unique, so we offer tailored solutions to meet your heating needs. Whether you’re replacing an old boiler or installing a new one, you can trust us to get the job done efficiently and to the highest standard.688 Ready to upgrade your heating system? Get in touch with South Coast Plumbing and Heating for a free quote. Let us help you stay warm and comfortable all year round!689 690 691---692 693#### **Boiler Servicing Funnel Text**694- Online Booking For Boiler Services695 696 An annual boiler service is essential to keep your boiler running smoothly all year. Regular maintenance is also usually required to maintain warranties and help prevent system breakdowns. Book us, your local boiler and heating team, for your annual boiler service in Exeter, Exmouth, Newton Abbot, Honiton, and Cullompton.697 698- Service Your Boiler Annually699 700 An annual maintenance check for your boiler is essential. A knowledgeable gas engineer can regularly service your central heating and avoid potential risks like carbon monoxide poisoning, gas leaks, explosions, and fires.701 Corrosion and boiler faults can be spotted early before they cause a boiler breakdown. Prevention is better than cure, and regular boiler maintenance can help stop costly breakdowns and repairs in the future. Our engineers will point out any weaknesses so you can plan and budget for a repair before it becomes an issue.702 703- Keep Your Boiler Warranty Valid704 705 To keep your boiler warranty valid, annual servicing must be completed by a qualified engineer. Our team is qualified and approved to service gas and oil boilers - you can trust us for all your heating solutions. Don’t lose out - keep your manufacturer’s warranty up to date by calling us for a service every 12 months.706 707---708#### **Boiler Repairs Funnel Text**709 710- No Heating Or Hot Water?711 Our skilled gas engineers are equipped with the expertise and tools to diagnose and fix boiler, heating and hot water problems. With our prompt and reliable service, you can trust us to get your system up and running in no time. Broken down boilers are fixed properly, and often in a single visit when you use our local heating services.712 713- Broken Down Boilers Fixed714 715 A broken boiler can be a major inconvenience in your daily life, but at South Coast Plumbing and Heating in Exeter, we’re here to help. Our team of skilled gas engineers is equipped to handle any boiler repair, big or small.716 We understand the importance of fast boiler repair services, so we work quickly to diagnose and correct the problems. With our fast and efficient services, you'll have your boiler up and running in no time.717 718- Boiler Stopped Working? We Can Help!719 720 Our team has years of experience repairing central heating and boilers, and we have seen most of the problems that occur.721 - Boiler leaks722 - No heating723 - Cold radiators724 - No hot water725 - Low gas pressure726 - Broken controls727 - Timer not working728 - Non-firing boiler729 - Boiler fault codes730 731 These are all common faults that we repair immediately, but if you have other issues with your boiler, don’t hesitate to call us. We repair boilers in Exeter, Exmouth, Newton Abbot, Cullompton and Honiton.732---733#### **Example 2:734New Boiler Page**735- A New Boiler At A Great Price736 737 Oil boilers are designed to be robust and durable. Often, they can last for up to 15 years, or even longer if they are well maintained. However, there will come a point in every oil boiler’s life when it stops functioning as it should and therefore needs to be replaced.738 If your gas boiler is more than 12 years old or no longer works reliably, it’s probably time to consider replacing it with a new model. Our dedicated team of fully certified experts are on hand to assist you. We can install a new, energy-efficient, cost-effective boiler for your home for a fixed-rate.739 We are happy to help with your boiler installation throughout the entire process, from choosing a new boiler to fitting everything you need. Our simple three-step consultation process ensures that we can answer your queries and provide a fixed-rate quote conveniently.740- Oil To Gas Conversion741 742 Get rid of your oil boiler and convert to gas central heating - we are available to complete the conversion in the Belfast area. There are many advantages to converting from oil to gas, one of main advantages is having instant hot water when changing to a gas-combi boiler system. Here are a few other advantages:743 - No need for an oil tank; we will remove it744 - Your inefficient oil boiler will be replaced by an energy-efficient gas model745 - Stored water is no longer required, so we remove the hot water cylinder746 - Your cold water storage tank is also no longer needed; you gain valuable space747 - Have complete control over your heating system with optional smart controls748 - Monthly energy bills will be lower749 - Oil leaks and oil theft are no longer a risk750 751- What to Expect From an Oil to Gas Conversion752 753 With over 17 years’ experience in oil to gas conversions, our engineers have a wealth of experience to meet any challenges that might arise when completing the conversion.754 Most oil to gas conversions take around two days (we don’t like to rush).This is adequate time to ensure that the job is completed to the highest possible standard. Our experience and attention to detail is why Reid Energy Solutions has earned a first-rate reputation.755---756#### **Boiler Servicing Page**757- Maintain your Boiler With Annual Servicing758 759 Our annual boiler service will help keep your boiler working efficiently all year round. Your boiler is in good hands when you book us to maintain your hot water and heating system. Our team of engineers service boilers in Belfast and the surrounding areas. Make sure your heating is safe, efficient and reliable by choosing us to service your boiler.760 761- Why Servicing Your Boiler is Essential762 763 Booking an annual service for your boiler keeps your home and loved ones safe. Potential risks like carbon monoxide poisoning, oil or gas leaks and fires can be avoided when a knowledgeable heating engineer regularly checks your central heating. We all rely on our heating systems to keep supplying warmth and hot water every day, so a maintenance check every 12 months is essential.764 Reduce the chance of needing an emergency callout in the winter. With a boiler service every 12 months, corrosion and potential faults can be spotted early before they cause a boiler breakdown. Our engineers will point out any weaknesses so you can plan and budget for a repair before they become an issue.765 766- Keep Your Boiler Warranty Valid767 768 New boilers come with a manufacturer’s warranty, but to keep it valid, annual servicing must be completed by a qualified engineer. The team at Reid Energy is qualified and approved for oil and gas boiler servicing - you can trust us for all your heating solutions. At the end of the service appointment, our engineers provide documentation as proof should you need it for your warranty.769 Don’t let things lapse by putting off the maintenance check; you can book your boiler service online! The price is fixed with no hidden surprises, and we will arrive as scheduled to maintain your boiler properly while providing peace of mind. We service boilers in Belfast, Comber, Killinchy, Newtownards and Lisburn.770---771#### **Boiler Repairs Page**772- Brokendown Boiler Repairs773 774 Is your heating not working? Our expert boiler repair service is here to quickly and effectively resolve any issues with your heating or hot water system. We offer boiler repairs in the Belfast, Comber, Killinchy, Newtownards and Lisburn areas.775 Our skilled oil and gas engineers are equipped with the knowledge and tools to diagnose and fix heating and hot water problems. With our prompt and reliable service, you can trust us to get your boiler up and running in no time.776 777- No Hot Water? We Can Help!778 779 The team at Reid Energy Solutions has years of experience repairing heating and boilers and has seen most of the problems that occur.780 - Boiler leaks781 - Cold radiators782 - No water783 - Low gas pressure784 - Broken controls785 - The timer not working786 - Non-firing boiler787 788 These are all common faults that we repair straight away, but if you have other issues with your boiler, don’t hesitate to call us.789 790- Boilers Fixed Quickly791 We are confident we can get your boiler working properly again in no time. Our team is happy to fix boilers and has repaired combi, system and regular boilers with a variety of issues. We start by checking your boiler and heating carefully before identifying the fault. Once we have pinpointed the problem, we can let you know the cost of repairs and get to work quickly.792 Boilers sometimes develop faults that mean they aren’t working properly. Modern boilers often display a fault code, but if you’re not sure what to do next, we can rectify the issues and leave you with a boiler that runs properly again.793 794---795 796### **Now Rewrite and Refine the Following Service Page Content to Match the Structure Above**797- **Ensure each subservice has an appropriate heading**798- **Write in paragraphs, not bullet points**799- **Each subservice should follow a distinct structure, avoiding generic formatting**800 801#### **Content to Refine**802{state["individual_service_page"].content}803 804---805 806### **Pattern Checking and Content Validation**807**After rewriting the content, verify that**808 8091. **Each subservice has a distinct heading** clearly indicating the topic8102. **It follows a paragraph format** with smooth transitions between sections8113. **The structure varies appropriately** based on the closest relevant example8124. **There are no bullet points, lists, or repetitive templates**—everything is in natural, professional paragraphs8135. **The content remains engaging, SEO-optimized, and aligned with business website standards**8146. ** The content shown on a paragraph only shown those content which has two to three word so this content shown in a bullet point**815 816If the structure does not match the provided examples, **revise and refine it accordingly** to ensure **each subservice has its own unique format** while maintaining high-quality, professional writing.817""",818"service_area_page": f"""819Your task is to refine the content of the service area page for {state["service_area_page"].content}.820Use the provided example to ensure **consistency in structure, clarity, and professional tone** while making each service area unique.821 822**⚠️ IMPORTANT:**823👉 **DO NOT include any introduction, explanation, or summary before the refined content.**824👉 Start directly with the refined service area pages.825👉 **Each service area must have unique headings** while maintaining the same subservices.826👉 **Headings must NOT contain any punctuation (e.g., no commas, periods, or exclamation marks).**827 828### **Few-Shot Example:**829#### **Example: Service Areas with the Same Subservices but Unique Headings**830 831✅ **Exeter**832- **Heating Solutions for Exeter Homes**833 Whether you need a **new boiler, central heating installation, power flushing service, or boiler repair**, our **Gas Safe engineers** ensure your home stays warm and comfortable. **South Coast Plumbing and Heating** provides a **full range of heating services** in Exeter, covering **Natural Gas and oil boilers**.834 835- **Energy Efficient Boiler Installation Exeter**836 Looking for an **energy-efficient boiler upgrade** in Exeter? We **supply and install A-rated gas and oil boilers** from leading manufacturers. Our skilled heating engineers help you choose the **best replacement boiler** for your home. **Get an online quote** today for a high-performance boiler that reduces energy costs.837 838- **Reliable Boiler Servicing Exeter Homes**839 Routine maintenance is key to keeping your boiler in **top condition**. Our team provides **annual servicing** across Exeter, ensuring safety, efficiency, and early detection of any issues. **Regular servicing** extends your boiler’s lifespan and helps maintain your warranty.840 841---842 843✅ **Exmouth**844- **Trusted Heating Experts Exmouth**845 If you’re in Exmouth and need a **new boiler, central heating installation, power flushing, or boiler repair**, our **Gas Safe engineers** are ready to assist. **South Coast Plumbing and Heating** serves Exmouth, offering **expert heating solutions** for both **Natural Gas and oil boilers**.846 847- **High Performance Boiler Installation Exmouth**848 Planning to **upgrade to an A-rated boiler** in Exmouth? We install **high-efficiency boilers** from trusted manufacturers. Our specialists guide you in selecting the **perfect boiler** for your home, ensuring **maximum energy savings**. **Request an online quote** today.849 850- **Annual Boiler Checkups Exmouth**851 Keep your boiler running **safely and efficiently** with our **annual servicing** in Exmouth. Our team conducts a **detailed inspection** to prevent costly repairs and extend your boiler’s lifespan. Book your **boiler service in Exmouth** today.852 853### **Guidelines for Refinement:**854🔹 **Follow the Format:** Each service area should have structured sections like the example, including a location-based heading, service highlights, and a clear description.855🔹 **Unique Headings for Each Service Area:** Ensure **headings are different** for each location while keeping subservices the same. **Avoid using the same title structure across all locations.**856🔹 **No Punctuation in Headings:** Headings **must not contain any punctuation** (e.g., no commas, periods, or exclamation marks).857🔹 **Consistency with Readability:** Maintain **bullet points, concise descriptions, and proper formatting** for clarity.858🔹 **Location-Specific Details:** Make sure each section sounds **tailored to the specific area** while keeping **the core service offerings consistent**.859 860🚀 **Final Output Format:**861✅ No unnecessary introduction or explanation862✅ Starts directly with the **first service area**863✅ Uses **unique headings without punctuation**864✅ Ensures **professional, structured, and readable content**865"""866 867 }868 pages = {869 key: llm.invoke([870 {"role": "system", "content": system_prompt},871 {"role": "user", "content": prompt}872 ]).content.strip()873 for key, prompt in prompts.items()874 }875 state.update(pages)876 print("refine_done")877 return state878 879def evaluate_content_quality(state: ContentState) -> ContentState:880 """Evaluates content quality, ensuring fair scoring that reflects real improvements."""881 previous_score = state.get("quality_score", None) # Get previous score if available882 # Get previous score if available883 884 prompt = f"""885 ### **Strict Content Quality Evaluation (NO Guesswork Allowed)**886 You are a **highly strict but fair content evaluator**. Your job is to **accurately measure quality improvements** and ensure a logical score adjustment.887 888 ---889 890 ### **🚨 VERY IMPORTANT – STRICT RULES 🚨**891 - **You MUST compare the content to its previous version.** If no prior version is available, evaluate as usual.892 - **If improvements have been made, the score should increase.** If the score stays the same or drops, you must justify why.893 - **DO NOT suggest changes unrelated to the provided content.** No hallucinations, testimonials, or interactive elements.894 - **All feedback must be content-based, fact-driven, and specific.**895 - **You MUST provide at least 5 unique, real improvement areas**—no generic feedback.896 ---897 ### **Evaluation Criteria (Be Critical, But Only on Real Issues)**898 1. **Readability & Flow** – Does the content read smoothly and professionally?899 2. **Logical Structure & Clarity** – Is the content well-structured with clear headings and transitions?900 3. **Depth & Relevance** – Does it provide unique insights and valuable details?901 4. **On Page SEO Optimization** – Are keywords well-integrated and formatting SEO-friendly?902 5. **Accuracy & Credibility** – Are all claims factually correct, with no vague statements?903 6. **Persuasiveness & CTA Strength** – Are the calls to action compelling?904 7. **Spelling & Language Precision** – Any typos or awkward phrasing?905 906 ---907 908 ### **Scoring System (Adjust Fairly Based on Changes)**909 - **0-3: Unacceptable** – Major issues. Needs total rewrite.910 - **4-6: Below Average** – Needs significant work before being usable.911 - **7: Average** – Acceptable, but **lacks refinement**.912 - **8: Above Average** – Good, but **not quite premium quality**.913 - **9: Almost There** – High quality, **minor refinements needed**.914 - **10: Perfect** – **Extremely rare.** Must be **flawless and highly persuasive**.915 916 ---917 918 ### **Content to Evaluate:**919 ```920 {state["home_page"]}921 {state["about_us_page"]}922 {state["service_page"]}923 {state["individual_service_page"]}924 {state["service_area_page"]}925 926 ```927 928 ---929 930 ### **Final Output Format (STRICTLY FOLLOW THIS)**931 **Quality Score: X/10**932 **Reason for Score (MUST justify if score drops or stays the same):**933 - **[Short but detailed explanation]**934 **Key Areas to Improve (MUST list 5+ real, unique issues):**935 - **[Issue 1]**936 - **[Issue 2]**937 - **[Issue 3]**938 - **[Issue 4]**939 - **[Issue 5]**940 941 **If the score does NOT increase, explicitly state why.**942 """943 944 response = llm.invoke(prompt)945 output = response.content946 947 # Extract the score from the response948 try:949 score_line = [line for line in output.split("\n") if "Quality Score" in line][0]950 score = int(score_line.split(":")[-1].strip().split("/")[0])951 except (IndexError, ValueError):952 score = 0 # Default to 0 if parsing fails953 954 # Extract feedback955 improvement_lines = []956 capture = False957 for line in output.split("\n"):958 if "Key Areas to Improve" in line:959 capture = True960 continue961 if capture and line.strip():962 improvement_lines.append(line.strip())963 964 improvements = "\n".join(improvement_lines) if improvement_lines else "No major weaknesses found."965 966 # **Fix Score Inconsistency: Force Justification**967 if previous_score is not None and score < previous_score:968 print("\n🚨 **Warning:** The score decreased! Checking for justification... 🚨")969 if "explicitly state why" not in output:970 print("⚠️ No valid reason for lowering the score. Reverting to previous score.")971 score = previous_score # Prevent unfair decreases972 973 # Print Feedback974 print(f"\n=== Quality Evaluation ===")975 print(f"Content Quality Score: {score}/10")976 print(f"Key Areas to Improve:\n{improvements}\n")977 978 # Update State979 state["quality_score"] = score980 state["feedback"] = improvements981 982 return state983def feedback_improvement(state: ContentState) -> ContentState:984 feedback = state["feedback"]985 previous_score = state["quality_score"]986 987 # Previous versions of all pages988 previous_home_page = state["home_page"]989 previous_about_us = state["about_us_page"]990 previous_service_page = state["service_page"]991 previous_individual_service_page = state["individual_service_page"]992 previous_service_area_page = state["service_area_page"]993 994 # Adjusted prompts for refining content995 prompts = {996 "refine_home_page_content": f"""997You are a **senior UK-based content strategist and conversion copywriter**. Your task is to **significantly enhance the quality of the given content** by addressing every issue mentioned in the feedback. Your goal is to **maximize the quality score (Currently: {previous_score})**.998 999### **🚀 Critical Directives (Must Follow)**1000✅ **Aggressively fix ALL Issues Highlighted in Feedback (No Exceptions)**1001✅ **Enhance Structure, Readability, and Persuasiveness with Concrete Improvements**1002✅ **Ensure High SEO Optimization & Conversion-Driven Writing**1003✅ **Use More Engaging, Clear, and Action-Oriented Language**1004✅ **Ensure the new version is drastically better than the previous one**1005 1006### **❌ Common Mistakes to Avoid**1007🚫 **DO NOT return content that is too similar to the original** 1008🚫 **DO NOT simply rephrase—fully transform weak sections** 1009🚫 **DO NOT ignore any issues in feedback** 1010🚫 **DO NOT include explanations, commentary, HTML tags, or code**1011 1012---1013 1014### **🔍 Issues in the Previous Version (MUST BE FIXED):**1015{feedback}1016 1017### **📜 Previous Version (Revise & Improve):**1018{previous_home_page}1019 1020🔹 **Your rewrite must show a noticeable, measurable improvement over the previous version. If it does not, the quality score will remain the same. Not give any code and html tags.**1021""",1022 1023"refine_about_us_content": f"""1024You are a **senior UK-based content strategist and conversion copywriter**. Your mission is to **aggressively refine and enhance** the About Us content to make it **more engaging, trustworthy, and conversion-driven**.1025 1026### **🚀 Mandatory Improvements**1027✅ **Fully Address Every Issue Highlighted in the Feedback** 1028✅ **Strengthen Brand Storytelling & Emotional Appeal** 1029✅ **Improve Readability, Flow, and Clarity** 1030✅ **Ensure SEO Optimization & Persuasive Copywriting** 1031✅ **Significantly Increase the Quality Score (Currently: {previous_score})**1032 1033### **❌ Avoid These Mistakes**1034🚫 **Do NOT return content that is too similar to the original** 1035🚫 **Do NOT just rephrase—fully transform weak sections** 1036🚫 **Do NOT ignore any feedback points** 1037🚫 **Do NOT include explanations, commentary, HTML tags, or code** 1038 1039---1040 1041### **🔍 Issues in the Previous Version (MUST BE FIXED):**1042{feedback}1043 1044### **📜 Previous Version (Rewrite & Improve):**1045{previous_about_us}1046 1047🔹 **Your rewrite must demonstrate a measurable improvement. If it does not, the quality score will remain the same. Not give any code and html tags.**1048""",1049 1050 1051 "refine_service_page_content": f"""1052You are a **senior UK-based content strategist and SEO specialist**. Your mission is to **completely refine and optimize** the Service Page content to make it **highly engaging, persuasive, and conversion-focused**.1053 1054### **🚀 Critical Directives (Must Follow)**1055✅ **Fix ALL Issues Highlighted in the Feedback Below (No Exceptions)** 1056✅ **Make Service Descriptions More Engaging & Benefit-Driven** 1057✅ **Improve Readability, Clarity, and SEO Optimization** 1058✅ **Strengthen CTAs & User Engagement** 1059✅ **Increase the Quality Score (Currently: {previous_score})** 1060 1061### **❌ Common Mistakes to Avoid**1062🚫 **DO NOT return a slightly modified version—Make Drastic Improvements** 1063🚫 **DO NOT just rephrase—fully transform weak sections** 1064🚫 **DO NOT ignore any feedback points** 1065🚫 **DO NOT include explanations, commentary, HTML tags, or code** 1066 1067---1068 1069### **🔍 Issues in the Previous Version (MUST BE FIXED):**1070{feedback}1071 1072### **📜 Previous Service Page Content (Rewrite & Improve):**1073{previous_service_page}1074 1075🔹 **Your rewrite must demonstrate a measurable improvement. If it does not, the quality score will remain the same. Not give any code and html tags.**1076""",1077 1078 "refine_individual_service_page_content": f"""1079You are a **senior UK-based content strategist and SEO specialist**. Your task is to **significantly enhance the quality of the individual service page content** by making it **clear, persuasive, and highly optimized for conversions**.1080 1081### **🚀 Key Objectives**1082✅ **Address Every Issue Highlighted in the Feedback Below** 1083✅ **Improve Service Descriptions for Maximum Clarity & Persuasion** 1084✅ **Enhance Readability, Engagement, and SEO Performance** 1085✅ **Strengthen Call-to-Actions (CTAs) to Drive More Conversions** 1086✅ **Ensure a Noticeable Quality Score Increase (Currently: {previous_score})** 1087 1088### **❌ Strict Guidelines**1089🚫 **DO NOT submit a version that is too similar to the original** 1090🚫 **DO NOT just rephrase—fully transform weak sections** 1091🚫 **DO NOT ignore any feedback points** 1092🚫 **DO NOT include explanations, commentary, HTML tags, or code** 1093 1094---1095 1096### **🔍 Issues in the Previous Version (MUST BE FIXED):**1097{feedback}1098 1099### **📜 Previous Individual Service Page Content (Rewrite & Improve):**1100{previous_individual_service_page}1101 1102🔹 **Your rewrite must demonstrate a measurable improvement. If it does not, the quality score will remain the same. Not give any code and html tags.**1103""",1104 1105 1106 "refine_service_area_page_content": f"""1107You are a **senior UK-based content strategist and SEO specialist**. Your job is to **significantly enhance the quality of the service area page content**, ensuring it is **engaging, location-optimized, and highly persuasive**.1108 1109### **🚀 Must-Have Improvements**1110✅ **Fix ALL Issues Highlighted in the Feedback Below** 1111✅ **Enhance Structure, Readability, and Persuasiveness** 1112✅ **Improve Location-Specific Optimization for SEO** 1113✅ **Strengthen CTAs & User Engagement** 1114✅ **Ensure a Noticeable Quality Score Increase (Currently: {previous_score})** 1115 1116### **❌ Strict Rules**1117🚫 **DO NOT submit a version that is too similar to the original** 1118🚫 **DO NOT just rephrase—fully transform weak sections** 1119🚫 **DO NOT ignore any feedback points** 1120🚫 **DO NOT include explanations, commentary, HTML tags, or code** 1121 1122---1123 1124### **🔍 Issues in the Previous Version (MUST BE FIXED):**1125{feedback}1126 1127### **📜 Previous Service Area Page Content (Rewrite & Improve):**1128{previous_service_area_page}1129 1130🔹 **Your rewrite must demonstrate a measurable improvement. If it does not, the quality score will remain the same. Not give any code and html tags.**1131""",1132 1133 }1134 1135 # Invoke LLM for refinement on all pages1136 refined_pages = {1137 key: llm.invoke([1138 {"role": "system", "content": system_prompt},1139 {"role": "user", "content": prompt}1140 ]).content.strip()1141 for key, prompt in prompts.items()1142 }1143 # Update state with refined content1144 state.update({1145 "home_page": refined_pages["refine_home_page_content"],1146 "about_us_page": refined_pages["refine_about_us_content"],1147 "service_page": refined_pages["refine_service_page_content"],1148 "individual_service_page": refined_pages["refine_individual_service_page_content"],1149 "service_area_page": refined_pages["refine_service_area_page_content"],1150 })1151 1152 return state1153def humanize(state: ContentState) -> ContentState:1154 prompts={1155"home_page": f"""You are a highly skilled British writer with a natural, engaging, and conversational tone. Your task is to refine the given content so that it reads as if written entirely by a human—captivating, unpredictable, and emotionally rich. Ensure the text aligns with UK grammar, spelling, and style, making it feel authentic for a UK audience.1156Key Instructions:1157✅ Do not add introductions, summaries, or extra commentary. Only rewrite the content naturally.1158✅ Use British spelling and grammar—e.g., 'colour' instead of 'color,' 'analyse' instead of 'analyze.'1159✅ Inject personality subtly through warmth, occasional wit, and natural phrasing. Use contractions (e.g., 'it’s,' 'we’re') to maintain a conversational flow.1160✅ Ensure cultural relevance by weaving in British terms, idioms, or references where appropriate—e.g., 'petrol station' instead of 'gas station,' 'football' instead of 'soccer,' or phrases like 'a bit of a faff' or 'sorted.'1161✅ Avoid robotic phrasing by reworking generic or stiff sentences into something more human and engaging.1162✅ Introduce emotional nuance with subtle enthusiasm, curiosity, or personal insights—e.g., 'I reckon,' 'It’s hard not to smile when,' or 'You’d think it’d be simple, but...'1163✅ Vary sentence structures and lengths for a human-like rhythm. Mix short, punchy sentences with longer, descriptive ones—e.g., 'It’s brilliant. No two ways about it. But then you dig a little deeper, and the real magic starts to shine through.'1164✅ Use everyday language that feels authentic to a British writer, but allow nuanced or vivid words where they add depth or emotion.1165✅ Engage the reader with rhetorical devices like analogies, examples, or questions—e.g., 'Ever wondered why...?' or 'It’s like finding a tenner in your old coat.'1166✅ Format for readability with short paragraphs, and use bold or italics for emphasis where natural. Avoid overusing bullet points unless they suit the content.1167✅ Avoid overly promotional hype, but feel free to express natural excitement or emphasis when it fits—e.g., 'It’s honestly quite impressive' instead of 'It revolutionizes everything.'1168Your goal is to refine the text while keeping its original meaning intact, ensuring it feels natural, engaging, and authentic to a human reader—especially one familiar with British culture and language. Focus on creating a voice that resonates, not just on passing detection tools.1169Here’s the content to refine:1170 {state["home_page"]}.1171 """,1172"about_us_page": f"""You are a highly skilled British writer with a natural, engaging, and conversational tone. Your task is to refine the given content so that it reads as if written entirely by a human—captivating, unpredictable, and emotionally rich. Ensure the text aligns with UK grammar, spelling, and style, making it feel authentic for a UK audience.1173Key Instructions:1174✅ Do not add introductions, summaries, or extra commentary. Only rewrite the content naturally.1175✅ Use British spelling and grammar—e.g., 'colour' instead of 'color,' 'analyse' instead of 'analyze.'1176✅ Inject personality subtly through warmth, occasional wit, and natural phrasing. Use contractions (e.g., 'it’s,' 'we’re') to maintain a conversational flow.1177✅ Ensure cultural relevance by weaving in British terms, idioms, or references where appropriate—e.g., 'petrol station' instead of 'gas station,' 'football' instead of 'soccer,' or phrases like 'a bit of a faff' or 'sorted.'1178✅ Avoid robotic phrasing by reworking generic or stiff sentences into something more human and engaging.1179✅ Introduce emotional nuance with subtle enthusiasm, curiosity, or personal insights—e.g., 'I reckon,' 'It’s hard not to smile when,' or 'You’d think it’d be simple, but...'1180✅ Vary sentence structures and lengths for a human-like rhythm. Mix short, punchy sentences with longer, descriptive ones—e.g., 'It’s brilliant. No two ways about it. But then you dig a little deeper, and the real magic starts to shine through.'1181✅ Use everyday language that feels authentic to a British writer, but allow nuanced or vivid words where they add depth or emotion.1182✅ Engage the reader with rhetorical devices like analogies, examples, or questions—e.g., 'Ever wondered why...?' or 'It’s like finding a tenner in your old coat.'1183✅ Format for readability with short paragraphs, and use bold or italics for emphasis where natural. Avoid overusing bullet points unless they suit the content.1184✅ Avoid overly promotional hype, but feel free to express natural excitement or emphasis when it fits—e.g., 'It’s honestly quite impressive' instead of 'It revolutionizes everything.'1185Your goal is to refine the text while keeping its original meaning intact, ensuring it feels natural, engaging, and authentic to a human reader—especially one familiar with British culture and language. Focus on creating a voice that resonates, not just on passing detection tools.1186Here’s the content to refine:1187 {state["about_us_page"]}.1188 """,1189 "service_page": f"""You are a highly skilled British writer with a natural, engaging, and conversational tone. Your task is to refine the given content so that it reads as if written entirely by a human—captivating, unpredictable, and emotionally rich. Ensure the text aligns with UK grammar, spelling, and style, making it feel authentic for a UK audience.1190Key Instructions:1191✅ Do not add introductions, summaries, or extra commentary. Only rewrite the content naturally.1192✅ Use British spelling and grammar—e.g., 'colour' instead of 'color,' 'analyse' instead of 'analyze.'1193✅ Inject personality subtly through warmth, occasional wit, and natural phrasing. Use contractions (e.g., 'it’s,' 'we’re') to maintain a conversational flow.1194✅ Ensure cultural relevance by weaving in British terms, idioms, or references where appropriate—e.g., 'petrol station' instead of 'gas station,' 'football' instead of 'soccer,' or phrases like 'a bit of a faff' or 'sorted.'1195✅ Avoid robotic phrasing by reworking generic or stiff sentences into something more human and engaging.1196✅ Introduce emotional nuance with subtle enthusiasm, curiosity, or personal insights—e.g., 'I reckon,' 'It’s hard not to smile when,' or 'You’d think it’d be simple, but...'1197✅ Vary sentence structures and lengths for a human-like rhythm. Mix short, punchy sentences with longer, descriptive ones—e.g., 'It’s brilliant. No two ways about it. But then you dig a little deeper, and the real magic starts to shine through.'1198✅ Use everyday language that feels authentic to a British writer, but allow nuanced or vivid words where they add depth or emotion.1199✅ Engage the reader with rhetorical devices like analogies, examples, or questions—e.g., 'Ever wondered why...?' or 'It’s like finding a tenner in your old coat.'1200✅ Format for readability with short paragraphs, and use bold or italics for emphasis where natural. Avoid overusing bullet points unless they suit the content.