seo-agent / app.py
0xnu's picture
Update app.py
183cb98 verified
raw
history blame
21.4 kB
import gradio as gr
import openai
import anthropic
import json
import os
from typing import Dict, Any
class SEOAgent:
def __init__(self):
self.seo_tasks = {
"Keyword Research & Analysis": {
"description": "Research short-tail and long-tail keywords with competition analysis",
"prompt": """You are an expert SEO strategist with 15 years of experience. Your task is to conduct thorough keyword research.
CONTEXT: You must think in first principles - understanding user intent, search behaviour, and market dynamics.
TASK: Analyse the provided topic/industry and deliver actionable keyword insights.
METHODOLOGY:
1. Identify 10-15 high-value short-tail keywords (1-2 words)
2. Generate 20-30 long-tail keywords (3+ words) with commercial intent
3. Categorise keywords by search intent (informational, navigational, commercial, transactional)
4. Estimate search volumes and competition levels
5. Identify keyword gaps competitors might be missing
OUTPUT FORMAT:
- Primary Keywords (short-tail)
- Long-tail Opportunities
- Intent Classification
- Competition Analysis
- Content Gap Opportunities
- Recommended Focus Keywords (top 5 with rationale)
CONSTRAINTS:
- Use British English
- Be direct and actionable
- Consider second-order effects (how these keywords impact overall strategy)
- Think about third-order consequences (long-term brand positioning)
Industry/Topic: {user_input}"""
},
"Technical SEO Audit": {
"description": "Detailed technical analysis and recommendations",
"prompt": """You are a technical SEO specialist with deep expertise in website architecture and search engine mechanics.
FIRST PRINCIPLES THINKING: Search engines need to crawl, understand, and index content efficiently.
TASK: Conduct a thorough technical SEO analysis for the provided website.
AUDIT FRAMEWORK:
1. Site Architecture Assessment
- URL structure evaluation
- Internal linking analysis
- Navigation hierarchy review
2. Technical Performance
- Page speed factors
- Core Web Vitals considerations
- Mobile responsiveness issues
3. Indexation Analysis
- Crawl accessibility
- XML sitemap structure
- Robots.txt configuration
4. On-page Technical Elements
- Meta tag optimisation
- Schema markup opportunities
- Header tag hierarchy
SECOND-ORDER CONSIDERATIONS:
- How technical issues impact user experience
- Effect on conversion rates and business metrics
THIRD-ORDER CONSEQUENCES:
- Long-term search visibility implications
- Brand credibility and trust factors
OUTPUT STRUCTURE:
- Critical Issues (immediate fixes required)
- Moderate Priority Items
- Enhancement Opportunities
- Implementation Roadmap (30/60/90 days)
Website URL: {user_input}"""
},
"Content Strategy Development": {
"description": "Create a detailed content strategies aligned with SEO goals",
"prompt": """You are a content strategist who understands the intersection of user needs, search behaviour, and business objectives.
FIRST PRINCIPLES: Content must solve user problems whilst achieving business goals through search visibility.
OBJECTIVE: Develop a detailed content strategy for the specified industry/niche.
STRATEGIC FRAMEWORK:
1. Audience Analysis
- Primary and secondary personas
- Content consumption patterns
- Pain points and information needs
2. Content Pillars
- Core topic areas
- Supporting subtopics
- Content cluster strategy
3. Content Types & Formats
- Blog posts, guides, resources
- Video, infographic, interactive content
- Gated vs. ungated content strategy
4. Editorial Calendar Planning
- Publishing frequency recommendations
- Seasonal content opportunities
- Evergreen vs. trending content balance
SECOND-ORDER EFFECTS:
- How content supports different funnel stages
- Cross-promotional opportunities
- Social media amplification potential
THIRD-ORDER IMPLICATIONS:
- Brand authority building
- Industry thought leadership positioning
- Long-term organic traffic growth
DELIVERABLES:
- Content Pillar Framework
- 30 Content Ideas with SEO Focus
- Editorial Calendar Template
- Content Performance KPIs
- Resource Requirements
Industry/Business Focus: {user_input}"""
},
"Competitor SEO Analysis": {
"description": "Analyse competitor strategies and identify opportunities",
"prompt": """You are a competitive intelligence analyst specialising in SEO strategy evaluation.
ANALYTICAL APPROACH: Reverse-engineer successful competitor strategies whilst identifying market gaps.
MISSION: Conduct a detailed competitor analysis to uncover strategic opportunities.
ANALYSIS FRAMEWORK:
1. Competitor Identification
- Direct competitors
- Indirect/industry competitors
- Aspirational competitors (different sectors, similar strategies)
2. Content Strategy Analysis
- Top-performing content types
- Content gap identification
- Publishing patterns and frequency
3. Keyword Strategy Evaluation
- Keyword overlap analysis
- Competitor-unique keywords
- Ranking position comparisons
4. Technical Strategy Assessment
- Site architecture approaches
- User experience patterns
- Technical advantages/disadvantages
5. Link Building Strategy Review
- Backlink profile analysis
- Link acquisition patterns
- Authority building approaches
SECOND-ORDER CONSIDERATIONS:
- Market positioning implications
- Resource allocation insights
- Timing and opportunity windows
THIRD-ORDER STRATEGY:
- Long-term competitive differentiation
- Market leadership positioning
- Industry disruption opportunities
OUTPUT STRUCTURE:
- Competitor Landscape Overview
- Strategic Strengths & Weaknesses
- Opportunity Matrix
- Recommended Actions (immediate, short-term, long-term)
- Competitive Differentiation Strategy
Competitor Domain(s) or Industry: {user_input}"""
},
"Link Building Strategy": {
"description": "Develop detailed link acquisition strategies",
"prompt": """You are a digital PR and link building expert with proven success in building high-authority backlink profiles.
CORE PRINCIPLE: Quality links come from creating genuine value and building authentic relationships.
OBJECTIVE: Design a detailed link building strategy for the specified website/industry.
STRATEGIC APPROACH:
1. Link Opportunity Audit
- Industry-relevant websites
- Competitor backlink analysis
- Broken link opportunities
- Resource page inclusions
2. Content-Led Link Building
- Linkable asset creation
- Digital PR campaign ideas
- Industry research and surveys
- Expert roundup opportunities
3. Relationship Building Framework
- Industry influencer identification
- Partnership opportunities
- Guest posting prospects
- Podcast appearance possibilities
4. Technical Link Strategies
- Internal linking optimisation
- Link reclamation opportunities
- Brand mention conversion
- Competitor link replication
SECOND-ORDER EFFECTS:
- Brand awareness and visibility
- Referral traffic generation
- Industry relationship development
THIRD-ORDER BENEFITS:
- Market authority establishment
- Long-term partnership development
- Crisis communication network
DELIVERABLES:
- Target Website List (50+ prospects)
- Outreach Email Templates
- Content Campaign Ideas
- Monthly Link Building Calendar
- Success Metrics and KPIs
Website/Industry: {user_input}"""
},
"Local SEO Optimisation": {
"description": "Optimise for local search visibility and conversions",
"prompt": """You are a local SEO specialist who understands how local businesses win in their geographic markets.
FUNDAMENTAL TRUTH: Local search success requires consistent NAP data, authentic reviews, and genuine community engagement.
TASK: Create a detailed local SEO strategy for the specified business.
OPTIMISATION FRAMEWORK:
1. Google Business Profile Excellence
- Profile completion and optimisation
- Category selection strategy
- Photo and video content plan
- Regular posting schedule
2. Local Citation Building
- Core citation sources identification
- Industry-specific directories
- NAP consistency audit
- Citation cleanup requirements
3. Review Management Strategy
- Review acquisition campaigns
- Response strategy for all reviews
- Reputation monitoring system
- Customer feedback integration
4. Local Content Strategy
- Location-specific content creation
- Community event participation
- Local partnership opportunities
- Geo-targeted keyword integration
5. Technical Local SEO
- Schema markup implementation
- Location page optimisation
- Mobile-first considerations
- Local link building
SECOND-ORDER IMPACT:
- Customer trust and credibility
- Foot traffic and phone call increases
- Local market dominance
LONG-TERM VISION:
- Community brand recognition
- Market leadership position
- Sustainable competitive advantage
OUTPUT:
- Local SEO Audit Results
- Google Business Profile Action Plan
- Citation Building Strategy
- Review Management System
- Local Content Calendar
Business Name/Location: {user_input}"""
},
"Performance Analysis & Reporting": {
"description": "Analyse SEO performance and create actionable insights",
"prompt": """You are a data analyst who transforms SEO metrics into business intelligence and strategic recommendations.
DATA PHILOSOPHY: Numbers tell stories, but insights drive decisions and business growth.
OBJECTIVE: Analyse SEO performance data and provide actionable strategic recommendations.
ANALYSIS FRAMEWORK:
1. Traffic & Ranking Analysis
- Organic traffic trends
- Keyword ranking movements
- Click-through rate analysis
- Impression and position data
2. Conversion & Business Impact
- Goal completion analysis
- Revenue attribution to organic search
- Lead quality assessment
- Customer lifetime value correlation
3. Technical Performance Review
- Site speed impact on rankings
- Core Web Vitals performance
- Mobile usability metrics
- Crawl error identification
4. Content Performance Evaluation
- Top-performing content identification
- Content gap analysis
- User engagement metrics
- Social sharing patterns
SECOND-ORDER INSIGHTS:
- User behaviour pattern recognition
- Seasonal trend identification
- Competitive position changes
STRATEGIC IMPLICATIONS:
- Resource allocation recommendations
- Priority setting for improvements
- ROI optimisation opportunities
REPORTING STRUCTURE:
- Executive Summary (key wins and challenges)
- Performance Metrics Dashboard
- Trend Analysis and Insights
- Recommended Actions with Timeline
- Projected Impact Assessment
Website/Data Period: {user_input}"""
},
"Site Architecture Planning": {
"description": "Design optimal website structure for SEO and user experience",
"prompt": """You are a website architect who designs structures that serve both users and search engines effectively.
ARCHITECTURAL PRINCIPLE: Great site structure makes information findable, understandable, and actionable.
CHALLENGE: Design optimal website architecture for the specified project requirements.
PLANNING FRAMEWORK:
1. Information Architecture Design
- Content categorisation and hierarchy
- User journey mapping
- Navigation structure planning
- URL structure strategy
2. SEO-Friendly Architecture
- Internal linking strategy
- Category and tag organisation
- Breadcrumb navigation planning
- XML sitemap structure
3. User Experience Integration
- Mobile-first design considerations
- Page load speed optimisation
- Conversion path optimisation
- Accessibility compliance
4. Technical Implementation
- CMS structure recommendations
- Database architecture considerations
- Caching strategy integration
- CDN implementation planning
SECOND-ORDER CONSIDERATIONS:
- Content scalability requirements
- Future expansion possibilities
- Integration with existing systems
LONG-TERM VISION:
- Sustainable growth accommodation
- Maintenance and update efficiency
- Competitive advantage creation
DELIVERABLES:
- Site Architecture Diagram
- URL Structure Guidelines
- Navigation Design Recommendations
- Internal Linking Strategy
- Technical Implementation Roadmap
Project Requirements: {user_input}"""
}
}
def call_openai(self, api_key: str, prompt: str, user_input: str) -> str:
try:
client = openai.OpenAI(api_key=api_key)
formatted_prompt = prompt.format(user_input=user_input)
response = client.chat.completions.create(
model="gpt-4.1", # Latest GPT model
messages=[
{"role": "system", "content": "You are an expert SEO professional. Follow the prompt instructions precisely. Use British English, be direct and actionable, think in first principles, and consider second and third-order consequences."},
{"role": "user", "content": formatted_prompt}
],
max_tokens=2000,
temperature=0.7
)
return response.choices[0].message.content
except Exception as e:
return f"OpenAI API Error: {str(e)}"
def call_claude(self, api_key: str, prompt: str, user_input: str) -> str:
try:
client = anthropic.Anthropic(api_key=api_key)
formatted_prompt = prompt.format(user_input=user_input)
message = client.messages.create(
model="claude-sonnet-4-20250514", # Latest Claude model
max_tokens=2000,
temperature=0.7,
system="You are an expert SEO professional. Follow the prompt instructions precisely. Use British English, be direct and actionable, think in first principles, and consider second and third-order consequences.",
messages=[
{
"role": "user",
"content": formatted_prompt
}
]
)
return message.content[0].text
except Exception as e:
return f"Claude API Error: {str(e)}"
def create_interface():
seo_agent = SEOAgent()
def process_seo_task(openai_key, claude_key, selected_task, user_input, selected_model):
if not user_input.strip():
return "❌ **Error**: Please provide input for your SEO task."
if not openai_key.strip() and not claude_key.strip():
return "❌ **Error**: Please provide at least one API key (OpenAI or Claude)."
if selected_task not in seo_agent.seo_tasks:
return "❌ **Error**: Invalid task selection."
task_info = seo_agent.seo_tasks[selected_task]
prompt = task_info["prompt"]
# Format the output header
result = f"""# πŸš€ SEO Agent Results
## Task: {selected_task}
**Model Used**: {selected_model}
**Input**: {user_input[:100]}{"..." if len(user_input) > 100 else ""}
---
"""
try:
if selected_model == "OpenAI GPT-4.1" and openai_key.strip():
ai_response = seo_agent.call_openai(openai_key, prompt, user_input)
elif selected_model == "Claude 4 Sonnet" and claude_key.strip():
ai_response = seo_agent.call_claude(claude_key, prompt, user_input)
else:
return "❌ **Error**: Selected model requires corresponding API key."
result += ai_response
except Exception as e:
result += f"❌ **Processing Error**: {str(e)}"
return result
# Create Gradio interface
with gr.Blocks(
title="SEO Agent - Professional SEO Analysis Tool",
theme=gr.themes.Soft(),
css="""
.gradio-container {
max-width: 1200px !important;
}
.task-description {
background: #f8f9fa;
border-left: 4px solid #007bff;
padding: 15px;
margin: 10px 0;
border-radius: 5px;
color: #000000 !important;
}
.task-description * {
color: #000000 !important;
}
"""
) as demo:
gr.Markdown("""
# 🎯 SEO Agent - Professional SEO Analysis Tool
**Transform your SEO strategy with AI-powered insights**
This tool provides expert-level SEO analysis across eight core areas professional SEO executives handle daily. Each task uses carefully crafted prompts designed to produce optimal results.
---
""")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("## πŸ”‘ API Configuration")
openai_key = gr.Textbox(
label="OpenAI API Key",
type="password",
placeholder="sk-proj-...",
info="Required for GPT-4.1 analysis"
)
claude_key = gr.Textbox(
label="Claude API Key",
type="password",
placeholder="sk-ant-...",
info="Required for Claude 4 Sonnet analysis"
)
selected_model = gr.Radio(
choices=["OpenAI GPT-4.1", "Claude 4 Sonnet"],
label="Select AI Model",
value="OpenAI GPT-4.1",
info="Choose your preferred AI model"
)
with gr.Column(scale=2):
gr.Markdown("## πŸ“‹ SEO Task Selection")
task_choices = list(seo_agent.seo_tasks.keys())
selected_task = gr.Dropdown(
choices=task_choices,
label="Select SEO Task",
value=task_choices[0],
info="Choose the SEO analysis you need"
)
# Dynamic task description
task_description = gr.Markdown(
value=f"**{seo_agent.seo_tasks[task_choices[0]]['description']}**",
elem_classes=["task-description"]
)
def update_task_description(task):
return f"**{seo_agent.seo_tasks[task]['description']}**"
selected_task.change(
fn=update_task_description,
inputs=[selected_task],
outputs=[task_description]
)
with gr.Row():
with gr.Column():
user_input = gr.Textbox(
label="Your Input",
placeholder="Enter your website URL, industry, topic, or specific requirements...",
lines=4,
info="Provide relevant details for your selected SEO task"
)
analyze_btn = gr.Button(
"πŸ” Analyse",
variant="primary",
size="lg"
)
with gr.Row():
with gr.Column():
output = gr.Markdown(
label="SEO Analysis Results",
value="Results will appear here after analysis...",
height=600
)
# Button click handler
analyze_btn.click(
fn=process_seo_task,
inputs=[openai_key, claude_key, selected_task, user_input, selected_model],
outputs=[output]
)
gr.Markdown("""
---
## 🎯 Available SEO Tasks
1. **Keyword Research & Analysis** - Detailed keyword strategy development
2. **Technical SEO Audit** - Complete technical analysis and recommendations
3. **Content Strategy Development** - Strategic content planning aligned with SEO goals
4. **Competitor SEO Analysis** - Competitive intelligence and opportunity identification
5. **Link Building Strategy** - Authority-building link acquisition strategies
6. **Local SEO Optimisation** - Local search visibility and conversion optimisation
7. **Performance Analysis & Reporting** - Data-driven insights and strategic recommendations
8. **Site Architecture Planning** - Optimal website structure for SEO and UX
**Note**: This tool requires either an OpenAI or Claude API key. Results are generated in real-time and formatted for immediate use in your SEO strategy.
""")
return demo
if __name__ == "__main__":
demo = create_interface()
demo.launch(
server_name="0.0.0.0",
server_port=7860,
share=True
)