Base code

This commit is contained in:
Kunthawat Greethong
2026-01-08 22:39:53 +07:00
parent 697115c61a
commit c35fa52117
2169 changed files with 626670 additions and 0 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,442 @@
# Blog Writer Implementation Overview
The ALwrity Blog Writer is a comprehensive AI-powered content creation system that transforms research into high-quality, SEO-optimized blog posts through a sophisticated multi-phase workflow.
## 🏗️ Architecture Overview
The Blog Writer follows a modular, service-oriented architecture with clear separation of concerns:
```mermaid
graph TB
A[Blog Writer API Router] --> B[Task Manager]
A --> C[Cache Manager]
A --> D[Blog Writer Service]
D --> E[Research Service]
D --> F[Outline Service]
D --> G[Content Generator]
D --> H[SEO Analyzer]
D --> I[Quality Assurance]
E --> J[Google Search Grounding]
E --> K[Research Cache]
F --> L[Outline Cache]
F --> M[AI Outline Generation]
G --> N[Enhanced Content Generator]
G --> O[Medium Blog Generator]
G --> P[Blog Rewriter]
H --> Q[SEO Analysis Engine]
H --> R[Metadata Generator]
I --> S[Hallucination Detection]
I --> T[Content Optimization]
style A fill:#e1f5fe
style D fill:#f3e5f5
style E fill:#e8f5e8
style F fill:#fff3e0
style G fill:#fce4ec
style H fill:#f1f8e9
style I fill:#e0f2f1
```
## 📋 Core Components
### 1. **API Router** (`router.py`)
- **Purpose**: Main entry point for all Blog Writer operations
- **Key Features**:
- RESTful API endpoints for all blog writing phases
- Background task management with polling
- Comprehensive error handling and logging
- Cache management endpoints
### 2. **Task Manager** (`task_manager.py`)
- **Purpose**: Manages background operations and progress tracking
- **Key Features**:
- Asynchronous task execution
- Real-time progress updates
- Task status tracking and cleanup
- Memory management (1-hour task retention)
### 3. **Cache Manager** (`cache_manager.py`)
- **Purpose**: Handles research and outline caching for performance
- **Key Features**:
- Research cache statistics and management
- Outline cache operations
- Cache invalidation and clearing
- Performance optimization
### 4. **Blog Writer Service** (`blog_writer_service.py`)
- **Purpose**: Main orchestrator coordinating all blog writing operations
- **Key Features**:
- Service coordination and workflow management
- Integration with specialized services
- Progress tracking and error handling
- Task management integration
## 🔄 Blog Writing Workflow
The Blog Writer implements a sophisticated 6-phase workflow:
```mermaid
flowchart TD
Start([User Input: Keywords & Topic]) --> Phase1[Phase 1: Research & Discovery]
Phase1 --> P1A[Keyword Analysis]
Phase1 --> P1B[Google Search Grounding]
Phase1 --> P1C[Source Collection]
Phase1 --> P1D[Competitor Analysis]
Phase1 --> P1E[Research Caching]
P1A --> Phase2[Phase 2: Outline Generation]
P1B --> Phase2
P1C --> Phase2
P1D --> Phase2
P1E --> Phase2
Phase2 --> P2A[Content Structure Planning]
Phase2 --> P2B[Section Definition]
Phase2 --> P2C[Source Mapping]
Phase2 --> P2D[Word Count Distribution]
Phase2 --> P2E[Title Generation]
P2A --> Phase3[Phase 3: Content Generation]
P2B --> Phase3
P2C --> Phase3
P2D --> Phase3
P2E --> Phase3
Phase3 --> P3A[Section-by-Section Writing]
Phase3 --> P3B[Citation Integration]
Phase3 --> P3C[Continuity Maintenance]
Phase3 --> P3D[Quality Assurance]
P3A --> Phase4[Phase 4: SEO Analysis]
P3B --> Phase4
P3C --> Phase4
P3D --> Phase4
Phase4 --> P4A[Content Structure Analysis]
Phase4 --> P4B[Keyword Optimization]
Phase4 --> P4C[Readability Assessment]
Phase4 --> P4D[SEO Scoring]
Phase4 --> P4E[Recommendation Generation]
P4A --> Phase5[Phase 5: Quality Assurance]
P4B --> Phase5
P4C --> Phase5
P4D --> Phase5
P4E --> Phase5
Phase5 --> P5A[Fact Verification]
Phase5 --> P5B[Hallucination Detection]
Phase5 --> P5C[Content Validation]
Phase5 --> P5D[Quality Scoring]
P5A --> Phase6[Phase 6: Publishing]
P5B --> Phase6
P5C --> Phase6
P5D --> Phase6
Phase6 --> P6A[Platform Integration]
Phase6 --> P6B[Metadata Generation]
Phase6 --> P6C[Content Formatting]
Phase6 --> P6D[Scheduling]
P6A --> End([Published Blog Post])
P6B --> End
P6C --> End
P6D --> End
style Start fill:#e3f2fd
style Phase1 fill:#e8f5e8
style Phase2 fill:#fff3e0
style Phase3 fill:#fce4ec
style Phase4 fill:#f1f8e9
style Phase5 fill:#e0f2f1
style Phase6 fill:#f3e5f5
style End fill:#e1f5fe
```
### Phase 1: Research & Discovery
**Endpoint**: `POST /api/blog/research/start`
**Process**:
1. **Keyword Analysis**: Analyze provided keywords for search intent
2. **Google Search Grounding**: Leverage Google's search capabilities for real-time data
3. **Source Collection**: Gather credible sources and research materials
4. **Competitor Analysis**: Analyze competing content and identify gaps
5. **Research Caching**: Store research results for future use
**Key Features**:
- Real-time web search integration
- Source credibility scoring
- Research data caching
- Progress tracking with detailed messages
### Phase 2: Outline Generation
**Endpoint**: `POST /api/blog/outline/start`
**Process**:
1. **Content Structure Planning**: Create logical content flow
2. **Section Definition**: Define headings, subheadings, and key points
3. **Source Mapping**: Map research sources to specific sections
4. **Word Count Distribution**: Optimize word count across sections
5. **Title Generation**: Create multiple compelling title options
**Key Features**:
- AI-powered outline generation
- Source-to-section mapping
- Multiple title options
- Outline optimization and refinement
### Phase 3: Content Generation
**Endpoint**: `POST /api/blog/section/generate`
**Process**:
1. **Section-by-Section Writing**: Generate content for each outline section
2. **Citation Integration**: Automatically include source citations
3. **Continuity Maintenance**: Ensure content flow and consistency
4. **Quality Assurance**: Implement quality checks during generation
**Key Features**:
- Individual section generation
- Automatic citation integration
- Content continuity tracking
- Multiple generation modes (draft/polished)
### Phase 4: SEO Analysis & Optimization
**Endpoint**: `POST /api/blog/seo/analyze`
**Process**:
1. **Content Structure Analysis**: Evaluate heading structure and organization
2. **Keyword Optimization**: Analyze keyword density and placement
3. **Readability Assessment**: Check content readability and flow
4. **SEO Scoring**: Generate comprehensive SEO scores
5. **Recommendation Generation**: Provide actionable optimization suggestions
**Key Features**:
- Comprehensive SEO analysis
- Real-time progress updates
- Detailed scoring and recommendations
- Visualization data for UI integration
### Phase 5: Quality Assurance
**Endpoint**: `POST /api/blog/quality/hallucination-check`
**Process**:
1. **Fact Verification**: Check content against research sources
2. **Hallucination Detection**: Identify potential AI-generated inaccuracies
3. **Content Validation**: Ensure factual accuracy and credibility
4. **Quality Scoring**: Generate content quality metrics
**Key Features**:
- AI-powered fact-checking
- Source verification
- Quality scoring and metrics
- Improvement suggestions
### Phase 6: Publishing & Distribution
**Endpoint**: `POST /api/blog/publish`
**Process**:
1. **Platform Integration**: Support for WordPress and Wix
2. **Metadata Generation**: Create SEO metadata and social tags
3. **Content Formatting**: Format content for target platform
4. **Scheduling**: Support for scheduled publishing
**Key Features**:
- Multi-platform publishing
- SEO metadata generation
- Social media optimization
- Publishing scheduling
## 🚀 Advanced Features
### Medium Blog Generation
**Endpoint**: `POST /api/blog/generate/medium/start`
A streamlined approach for shorter content (≤1000 words):
- Single-pass content generation
- Optimized for quick turnaround
- Cached content reuse
- Simplified workflow
### Content Optimization
**Endpoint**: `POST /api/blog/section/optimize`
Advanced content improvement:
- AI-powered content enhancement
- Flow analysis and improvement
- Engagement optimization
- Performance tracking
### Blog Rewriting
**Endpoint**: `POST /api/blog/rewrite/start`
Content improvement based on feedback:
- User feedback integration
- Iterative content improvement
- Quality enhancement
- Version tracking
## 📊 Data Flow Architecture
The Blog Writer processes data through a sophisticated pipeline with caching and optimization:
```mermaid
flowchart LR
User[User Input] --> API[API Router]
API --> TaskMgr[Task Manager]
API --> CacheMgr[Cache Manager]
TaskMgr --> Research[Research Service]
Research --> GSCache[Research Cache]
Research --> GSearch[Google Search]
TaskMgr --> Outline[Outline Service]
Outline --> OCache[Outline Cache]
Outline --> AI[AI Models]
TaskMgr --> Content[Content Generator]
Content --> CCache[Content Cache]
Content --> AI
TaskMgr --> SEO[SEO Analyzer]
SEO --> SEOEngine[SEO Engine]
TaskMgr --> QA[Quality Assurance]
QA --> FactCheck[Fact Checker]
GSCache --> Research
OCache --> Outline
CCache --> Content
Research --> Outline
Outline --> Content
Content --> SEO
SEO --> QA
QA --> Publish[Publishing]
style User fill:#e3f2fd
style API fill:#e1f5fe
style TaskMgr fill:#f3e5f5
style CacheMgr fill:#f3e5f5
style Research fill:#e8f5e8
style Outline fill:#fff3e0
style Content fill:#fce4ec
style SEO fill:#f1f8e9
style QA fill:#e0f2f1
style Publish fill:#e1f5fe
```
## 📊 Data Models
### Core Request/Response Models
**BlogResearchRequest**:
```python
{
"keywords": ["list", "of", "keywords"],
"topic": "optional topic",
"industry": "optional industry",
"target_audience": "optional audience",
"tone": "optional tone",
"word_count_target": 1500,
"persona": PersonaInfo
}
```
**BlogOutlineResponse**:
```python
{
"success": true,
"title_options": ["title1", "title2", "title3"],
"outline": [BlogOutlineSection],
"source_mapping_stats": SourceMappingStats,
"grounding_insights": GroundingInsights,
"optimization_results": OptimizationResults,
"research_coverage": ResearchCoverage
}
```
**BlogSectionResponse**:
```python
{
"success": true,
"markdown": "generated content",
"citations": [ResearchSource],
"continuity_metrics": ContinuityMetrics
}
```
## 🔧 Technical Implementation
### Background Task Processing
- **Asynchronous Execution**: All long-running operations use background tasks
- **Progress Tracking**: Real-time progress updates with detailed messages
- **Error Handling**: Comprehensive error handling and graceful failures
- **Memory Management**: Automatic cleanup of old tasks
### Caching Strategy
- **Research Caching**: Cache research results by keywords
- **Outline Caching**: Cache generated outlines for reuse
- **Content Caching**: Cache generated content sections
- **Performance Optimization**: Reduce API calls and improve response times
### Integration Points
- **Google Search Grounding**: Real-time web search integration
- **AI Providers**: Support for multiple AI providers (Gemini, OpenAI, etc.)
- **Platform APIs**: Integration with WordPress and Wix APIs
- **Analytics**: Integration with SEO and performance analytics
## 🎯 Performance Characteristics
### Response Times
- **Research Phase**: 30-60 seconds (depending on complexity)
- **Outline Generation**: 15-30 seconds
- **Content Generation**: 20-40 seconds per section
- **SEO Analysis**: 10-20 seconds
- **Quality Assurance**: 15-25 seconds
### Scalability Features
- **Background Processing**: Non-blocking operations
- **Caching**: Reduced API calls and improved performance
- **Task Management**: Efficient resource utilization
- **Error Recovery**: Graceful handling of failures
## 🔒 Quality Assurance
### Content Quality
- **Fact Verification**: Source-based fact checking
- **Hallucination Detection**: AI accuracy validation
- **Continuity Tracking**: Content flow and consistency
- **Quality Scoring**: Comprehensive quality metrics
### Technical Quality
- **Error Handling**: Comprehensive error management
- **Logging**: Detailed operation logging
- **Monitoring**: Performance and usage monitoring
- **Testing**: Automated testing and validation
## 📈 Future Enhancements
### Planned Features
- **Multi-language Support**: Content generation in multiple languages
- **Advanced Analytics**: Detailed performance analytics
- **Custom Templates**: User-defined content templates
- **Collaboration Features**: Multi-user content creation
- **API Extensions**: Additional platform integrations
### Performance Improvements
- **Caching Optimization**: Enhanced caching strategies
- **Parallel Processing**: Improved concurrent operations
- **Resource Optimization**: Better resource utilization
- **Response Time Reduction**: Faster operation completion
---
*This implementation overview provides a comprehensive understanding of the Blog Writer's architecture, workflow, and technical capabilities. For detailed API documentation, see the [API Reference](api-reference.md).*

View File

@@ -0,0 +1,832 @@
# Blog Writer Implementation Specification
This technical specification document outlines the implementation details, architecture, and technical requirements for ALwrity's Blog Writer feature.
## Architecture Overview
### System Architecture
The Blog Writer is built on a microservices architecture with the following key components:
```mermaid
graph TB
subgraph "Frontend Layer"
UI[React UI Components]
State[Redux State Management]
Router[React Router]
end
subgraph "Backend Layer"
API[FastAPI Application]
Auth[Authentication Service]
Cache[Redis Cache]
Queue[Celery Task Queue]
end
subgraph "AI Services Layer"
Gemini[Google Gemini API]
Research[Research Services]
SEO[SEO Analysis Engine]
Content[Content Generation]
end
subgraph "Data Layer"
DB[(PostgreSQL Database)]
Files[File Storage]
Logs[Application Logs]
end
subgraph "External APIs"
Tavily[Tavily Research API]
Serper[Serper Search API]
GSC[Google Search Console]
end
UI --> API
State --> API
Router --> API
API --> Auth
API --> Cache
API --> Queue
API --> Gemini
API --> Research
API --> SEO
API --> Content
Research --> Tavily
Research --> Serper
SEO --> GSC
API --> DB
Content --> Files
API --> Logs
style UI fill:#e3f2fd
style API fill:#f3e5f5
style Gemini fill:#e8f5e8
style DB fill:#fff3e0
```
### Technology Stack
#### Frontend
- **Framework**: React 18+ with TypeScript
- **UI Library**: Material-UI (MUI) v5
- **State Management**: Redux Toolkit
- **Routing**: React Router v6
- **HTTP Client**: Axios
- **Form Handling**: React Hook Form
- **Rich Text Editor**: TinyMCE or Quill
#### Backend
- **Framework**: FastAPI (Python 3.10+)
- **Database**: PostgreSQL with SQLAlchemy ORM
- **Authentication**: JWT with Clerk integration
- **API Documentation**: OpenAPI/Swagger
- **Background Tasks**: Celery with Redis
- **Caching**: Redis
- **File Storage**: AWS S3 or local storage
#### AI Services
- **Primary AI**: Google Gemini API
- **Research**: Tavily, Serper, Metaphor APIs
- **SEO Analysis**: Custom algorithms + external APIs
- **Image Generation**: Stability AI
- **Content Moderation**: Custom + external services
## API Endpoints
### Core Blog Writer Endpoints
#### Content Generation
```http
POST /api/blog-writer/generate
Content-Type: application/json
Authorization: Bearer {api_key}
{
"topic": "AI in Digital Marketing",
"target_audience": "Marketing professionals",
"content_type": "how-to-guide",
"word_count": 1500,
"tone": "professional",
"keywords": ["AI", "digital marketing", "automation"],
"research_depth": "comprehensive",
"include_seo_analysis": true
}
```
#### Research Integration
```http
POST /api/blog-writer/research
Content-Type: application/json
Authorization: Bearer {api_key}
{
"topic": "Content Strategy",
"research_depth": "comprehensive",
"sources": ["web", "academic", "industry"],
"language": "en",
"date_range": "last_12_months"
}
```
#### SEO Analysis
```http
POST /api/blog-writer/seo/analyze
Content-Type: application/json
Authorization: Bearer {api_key}
{
"content": "Your blog post content here...",
"target_keywords": ["content strategy", "digital marketing"],
"competitor_urls": ["https://example.com"],
"analysis_depth": "comprehensive"
}
```
### Response Formats
#### Success Response
```json
{
"success": true,
"data": {
"content": {
"title": "AI in Digital Marketing: A Comprehensive Guide",
"body": "Generated content here...",
"word_count": 1500,
"reading_time": "6 minutes"
},
"research": {
"sources": [...],
"key_facts": [...],
"trends": [...]
},
"seo_analysis": {
"score": 85,
"recommendations": [...],
"keyword_analysis": {...}
},
"metadata": {
"generated_at": "2024-01-15T10:30:00Z",
"processing_time": "45 seconds",
"ai_model": "gemini-pro"
}
}
}
```
#### Error Response
```json
{
"success": false,
"error": {
"code": "CONTENT_GENERATION_FAILED",
"message": "Failed to generate content",
"details": {
"reason": "AI service timeout",
"suggestion": "Try again with a shorter content length"
}
}
}
```
## Database Schema
### Core Tables
#### Blog Posts
```sql
CREATE TABLE blog_posts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id),
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL,
status VARCHAR(50) DEFAULT 'draft',
word_count INTEGER,
reading_time INTEGER,
seo_score INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
published_at TIMESTAMP
);
CREATE INDEX idx_blog_posts_user_id ON blog_posts(user_id);
CREATE INDEX idx_blog_posts_status ON blog_posts(status);
CREATE INDEX idx_blog_posts_created_at ON blog_posts(created_at);
```
#### Research Data
```sql
CREATE TABLE research_data (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
blog_post_id UUID REFERENCES blog_posts(id),
source_url VARCHAR(500),
source_title VARCHAR(255),
content TEXT,
credibility_score INTEGER,
relevance_score INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_research_data_blog_post_id ON research_data(blog_post_id);
CREATE INDEX idx_research_data_credibility ON research_data(credibility_score);
```
#### SEO Analysis
```sql
CREATE TABLE seo_analysis (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
blog_post_id UUID REFERENCES blog_posts(id),
overall_score INTEGER,
keyword_score INTEGER,
content_score INTEGER,
technical_score INTEGER,
readability_score INTEGER,
recommendations JSONB,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_seo_analysis_blog_post_id ON seo_analysis(blog_post_id);
```
## AI Integration
### Google Gemini Integration
#### Configuration
```python
import google.generativeai as genai
class GeminiService:
def __init__(self, api_key: str):
genai.configure(api_key=api_key)
self.model = genai.GenerativeModel('gemini-pro')
async def generate_content(self, prompt: str, **kwargs) -> str:
try:
response = await self.model.generate_content_async(
prompt,
generation_config=genai.types.GenerationConfig(
temperature=kwargs.get('temperature', 0.7),
max_output_tokens=kwargs.get('max_tokens', 2048),
top_p=kwargs.get('top_p', 0.8),
top_k=kwargs.get('top_k', 40)
)
)
return response.text
except Exception as e:
raise ContentGenerationError(f"Gemini API error: {str(e)}")
```
#### Prompt Engineering
```python
class BlogWriterPrompts:
@staticmethod
def generate_blog_post(topic: str, audience: str, word_count: int) -> str:
return f"""
Write a comprehensive blog post about "{topic}" for {audience}.
Requirements:
- Word count: {word_count} words
- Tone: Professional and engaging
- Structure: Introduction, main sections, conclusion
- Include actionable insights and examples
- Use subheadings for better readability
- Include a compelling call-to-action
Please ensure the content is:
- Well-researched and factual
- SEO-friendly
- Engaging and valuable to readers
- Free from plagiarism
"""
@staticmethod
def generate_outline(topic: str, audience: str) -> str:
return f"""
Create a detailed outline for a blog post about "{topic}" for {audience}.
Include:
- Compelling headline
- Introduction hook
- 3-5 main sections with sub-points
- Conclusion with call-to-action
- Suggested word count for each section
"""
```
### Research Service Integration
#### Multi-Source Research
```python
class ResearchService:
def __init__(self):
self.tavily_client = TavilyClient(api_key=settings.TAVILY_API_KEY)
self.serper_client = SerperClient(api_key=settings.SERPER_API_KEY)
self.metaphor_client = MetaphorClient(api_key=settings.METAPHOR_API_KEY)
async def comprehensive_research(self, topic: str, depth: str = "comprehensive") -> Dict:
research_results = {
"web_sources": await self._web_research(topic),
"academic_sources": await self._academic_research(topic),
"industry_sources": await self._industry_research(topic),
"news_sources": await self._news_research(topic)
}
return self._process_research_results(research_results)
async def _web_research(self, topic: str) -> List[Dict]:
# Tavily web search
tavily_results = await self.tavily_client.search(
query=topic,
search_depth="advanced",
max_results=10
)
# Serper Google search
serper_results = await self.serper_client.search(
query=topic,
num_results=10
)
return self._merge_search_results(tavily_results, serper_results)
```
## Frontend Components
### React Components Structure
```
src/
├── components/
│ ├── BlogWriter/
│ │ ├── BlogWriterContainer.tsx
│ │ ├── TopicInput.tsx
│ │ ├── ContentEditor.tsx
│ │ ├── ResearchPanel.tsx
│ │ ├── SEOAnalysis.tsx
│ │ └── ContentPreview.tsx
│ ├── shared/
│ │ ├── LoadingSpinner.tsx
│ │ ├── ErrorBoundary.tsx
│ │ └── ProgressBar.tsx
│ └── ui/
│ ├── Button.tsx
│ ├── Input.tsx
│ └── Modal.tsx
```
### Main Blog Writer Component
```typescript
import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { BlogWriterContainer } from './BlogWriterContainer';
import { ResearchPanel } from './ResearchPanel';
import { SEOAnalysis } from './SEOAnalysis';
import { ContentEditor } from './ContentEditor';
interface BlogWriterProps {
initialTopic?: string;
onContentGenerated?: (content: BlogContent) => void;
}
export const BlogWriter: React.FC<BlogWriterProps> = ({
initialTopic,
onContentGenerated
}) => {
const [currentStep, setCurrentStep] = useState<'input' | 'research' | 'generation' | 'editing' | 'analysis'>('input');
const [blogData, setBlogData] = useState<BlogData>({
topic: initialTopic || '',
audience: '',
wordCount: 1000,
tone: 'professional',
keywords: []
});
const dispatch = useDispatch();
const { content, research, seoAnalysis, loading, error } = useSelector(
(state: RootState) => state.blogWriter
);
const handleGenerateContent = async () => {
setCurrentStep('generation');
dispatch(generateBlogContent(blogData));
};
const handleResearchComplete = (researchData: ResearchData) => {
setBlogData(prev => ({ ...prev, research: researchData }));
setCurrentStep('generation');
};
return (
<div className="blog-writer">
<BlogWriterContainer
currentStep={currentStep}
blogData={blogData}
onDataChange={setBlogData}
onGenerate={handleGenerateContent}
/>
{currentStep === 'research' && (
<ResearchPanel
topic={blogData.topic}
onComplete={handleResearchComplete}
/>
)}
{currentStep === 'editing' && content && (
<ContentEditor
content={content}
onContentChange={(newContent) => setBlogData(prev => ({ ...prev, content: newContent }))}
/>
)}
{currentStep === 'analysis' && (
<SEOAnalysis
content={content}
targetKeywords={blogData.keywords}
onAnalysisComplete={(analysis) => setBlogData(prev => ({ ...prev, seoAnalysis: analysis }))}
/>
)}
</div>
);
};
```
## State Management
### Redux Store Structure
```typescript
interface BlogWriterState {
// Input data
topic: string;
audience: string;
wordCount: number;
tone: string;
keywords: string[];
// Generated content
content: BlogContent | null;
research: ResearchData | null;
seoAnalysis: SEOAnalysis | null;
// UI state
currentStep: 'input' | 'research' | 'generation' | 'editing' | 'analysis';
loading: boolean;
error: string | null;
// Progress tracking
generationProgress: number;
researchProgress: number;
}
// Actions
export const blogWriterSlice = createSlice({
name: 'blogWriter',
initialState,
reducers: {
setTopic: (state, action) => {
state.topic = action.payload;
},
setAudience: (state, action) => {
state.audience = action.payload;
},
setWordCount: (state, action) => {
state.wordCount = action.payload;
},
setTone: (state, action) => {
state.tone = action.payload;
},
setKeywords: (state, action) => {
state.keywords = action.payload;
},
setCurrentStep: (state, action) => {
state.currentStep = action.payload;
},
setLoading: (state, action) => {
state.loading = action.payload;
},
setError: (state, action) => {
state.error = action.payload;
},
setContent: (state, action) => {
state.content = action.payload;
},
setResearch: (state, action) => {
state.research = action.payload;
},
setSEOAnalysis: (state, action) => {
state.seoAnalysis = action.payload;
}
}
});
```
## Error Handling
### Error Types
```python
class BlogWriterError(Exception):
"""Base exception for Blog Writer errors"""
pass
class ContentGenerationError(BlogWriterError):
"""Error during content generation"""
pass
class ResearchError(BlogWriterError):
"""Error during research process"""
pass
class SEOAnalysisError(BlogWriterError):
"""Error during SEO analysis"""
pass
class ValidationError(BlogWriterError):
"""Input validation error"""
pass
```
### Error Handling Middleware
```python
from fastapi import HTTPException, Request
from fastapi.responses import JSONResponse
@app.exception_handler(BlogWriterError)
async def blog_writer_error_handler(request: Request, exc: BlogWriterError):
return JSONResponse(
status_code=400,
content={
"success": False,
"error": {
"code": exc.__class__.__name__,
"message": str(exc),
"details": getattr(exc, 'details', {})
}
}
)
@app.exception_handler(ValidationError)
async def validation_error_handler(request: Request, exc: ValidationError):
return JSONResponse(
status_code=422,
content={
"success": False,
"error": {
"code": "VALIDATION_ERROR",
"message": "Request validation failed",
"details": {
"field": exc.field,
"message": str(exc)
}
}
}
)
```
## Performance Optimization
### Caching Strategy
```python
from functools import lru_cache
import redis
class CacheService:
def __init__(self):
self.redis_client = redis.Redis(host='localhost', port=6379, db=0)
@lru_cache(maxsize=1000)
def get_research_cache(self, topic: str, depth: str) -> Dict:
cache_key = f"research:{topic}:{depth}"
cached_data = self.redis_client.get(cache_key)
if cached_data:
return json.loads(cached_data)
return None
def set_research_cache(self, topic: str, depth: str, data: Dict, ttl: int = 3600):
cache_key = f"research:{topic}:{depth}"
self.redis_client.setex(
cache_key,
ttl,
json.dumps(data)
)
```
### Background Processing
```python
from celery import Celery
celery_app = Celery('blog_writer')
@celery_app.task
def generate_blog_content_async(topic: str, audience: str, word_count: int):
"""Generate blog content asynchronously"""
try:
# Generate content
content = generate_content(topic, audience, word_count)
# Perform research
research = perform_research(topic)
# SEO analysis
seo_analysis = perform_seo_analysis(content)
return {
"content": content,
"research": research,
"seo_analysis": seo_analysis
}
except Exception as e:
raise ContentGenerationError(f"Async generation failed: {str(e)}")
```
## Security Considerations
### Input Validation
```python
from pydantic import BaseModel, validator
import re
class BlogGenerationRequest(BaseModel):
topic: str
audience: str
word_count: int
tone: str
keywords: List[str]
@validator('topic')
def validate_topic(cls, v):
if len(v) < 3 or len(v) > 200:
raise ValueError('Topic must be between 3 and 200 characters')
return v.strip()
@validator('word_count')
def validate_word_count(cls, v):
if v < 100 or v > 10000:
raise ValueError('Word count must be between 100 and 10,000')
return v
@validator('tone')
def validate_tone(cls, v):
allowed_tones = ['professional', 'casual', 'friendly', 'authoritative', 'conversational']
if v not in allowed_tones:
raise ValueError(f'Tone must be one of: {", ".join(allowed_tones)}')
return v
```
### Rate Limiting
```python
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
@app.post("/api/blog-writer/generate")
@limiter.limit("10/minute")
async def generate_blog_content(request: Request, data: BlogGenerationRequest):
# Implementation
pass
```
## Testing Strategy
### Unit Tests
```python
import pytest
from unittest.mock import Mock, patch
from blog_writer.services import BlogWriterService
class TestBlogWriterService:
@pytest.fixture
def blog_writer_service(self):
return BlogWriterService()
@patch('blog_writer.services.GeminiService')
def test_generate_content_success(self, mock_gemini, blog_writer_service):
# Mock Gemini response
mock_gemini.return_value.generate_content.return_value = "Generated content"
# Test content generation
result = blog_writer_service.generate_content(
topic="AI in Marketing",
audience="Marketing professionals",
word_count=1000
)
assert result["content"] == "Generated content"
assert result["word_count"] == 1000
def test_validate_input_data(self, blog_writer_service):
# Test input validation
with pytest.raises(ValidationError):
blog_writer_service.validate_input({
"topic": "", # Empty topic
"word_count": 50 # Too short
})
```
### Integration Tests
```python
import pytest
from fastapi.testclient import TestClient
from app import app
client = TestClient(app)
def test_blog_generation_endpoint():
response = client.post(
"/api/blog-writer/generate",
json={
"topic": "AI in Digital Marketing",
"audience": "Marketing professionals",
"word_count": 1000,
"tone": "professional"
},
headers={"Authorization": "Bearer test_token"}
)
assert response.status_code == 200
data = response.json()
assert data["success"] is True
assert "content" in data["data"]
```
## Deployment Configuration
### Docker Configuration
```dockerfile
# Dockerfile
FROM python:3.10-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
```
### Environment Variables
```bash
# .env
DATABASE_URL=postgresql://user:password@localhost/alwrity
REDIS_URL=redis://localhost:6379
GEMINI_API_KEY=your_gemini_api_key
TAVILY_API_KEY=your_tavily_api_key
SERPER_API_KEY=your_serper_api_key
METAPHOR_API_KEY=your_metaphor_api_key
STABILITY_API_KEY=your_stability_api_key
SECRET_KEY=your_secret_key
CORS_ORIGINS=http://localhost:3000
```
### Kubernetes Deployment
```yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: blog-writer-api
spec:
replicas: 3
selector:
matchLabels:
app: blog-writer-api
template:
metadata:
labels:
app: blog-writer-api
spec:
containers:
- name: blog-writer-api
image: alwrity/blog-writer-api:latest
ports:
- containerPort: 8000
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: alwrity-secrets
key: database-url
- name: GEMINI_API_KEY
valueFrom:
secretKeyRef:
name: alwrity-secrets
key: gemini-api-key
```
---
*This implementation specification provides the technical foundation for building a robust, scalable Blog Writer feature. For more details on specific components, refer to the individual feature documentation.*

View File

@@ -0,0 +1,334 @@
# Blog Writer Overview
The ALwrity Blog Writer is a powerful AI-driven content creation tool that helps you generate high-quality, SEO-optimized blog posts with minimal effort. It's designed for users with medium to low technical knowledge, making professional content creation accessible to everyone.
## Key Features
### 🤖 AI-Powered Content Generation
- **Research Integration**: Automated web research with source verification
- **Smart Outlines**: AI-generated content outlines that you can customize
- **Section-by-Section Writing**: Generate content one section at a time
- **Multiple Writing Styles**: Choose from different tones and styles
### 📊 Research & Analysis
- **Web Research**: Real-time research with source citations
- **Fact Checking**: Built-in hallucination detection and verification
- **Content Optimization**: AI-powered content improvement suggestions
- **SEO Integration**: Built-in SEO analysis and recommendations
### 🎯 User-Friendly Features
- **Visual Editor**: Easy-to-use WYSIWYG editor with markdown support
- **Progress Tracking**: Real-time progress monitoring for long tasks
- **Title Suggestions**: AI-generated title options to choose from
- **Publishing Tools**: Direct publishing to various platforms
## How It Works
### Complete 6-Phase Workflow
ALwrity Blog Writer transforms your ideas into publish-ready content through a sophisticated, AI-powered workflow that ensures quality, accuracy, and SEO optimization at every step.
```mermaid
flowchart TD
A[Start: Keywords & Topic] --> B[Phase 1: Research & Strategy]
B --> C[Phase 2: Intelligent Outline]
C --> D[Phase 3: Content Generation]
D --> E[Phase 4: SEO Analysis]
E --> F[Phase 5: SEO Metadata]
F --> G[Phase 6: Publish & Distribute]
B --> B1[Google Search Grounding]
B --> B2[Competitor Analysis]
B --> B3[Keyword Intelligence]
C --> C1[AI Outline Generation]
C --> C2[Source Mapping]
C --> C3[Title Generation]
D --> D1[Section-by-Section Writing]
D --> D2[Context Memory]
D --> D3[Flow Analysis]
E --> E1[SEO Scoring]
E --> E2[Actionable Recommendations]
E --> E3[AI-Powered Refinement]
F --> F1[Comprehensive Metadata]
F --> F2[Open Graph & Twitter Cards]
F --> F3[Schema.org Markup]
G --> G1[Multi-Platform Publishing]
G --> G2[Scheduling]
G --> G3[Version Management]
style A fill:#e3f2fd
style B fill:#e8f5e8
style C fill:#fff3e0
style D fill:#fce4ec
style E fill:#f1f8e9
style F fill:#e0f2f1
style G fill:#f3e5f5
```
#### Phase 1: Research & Strategy
AI-powered comprehensive research with Google Search grounding, competitor analysis, and keyword intelligence.
#### Phase 2: Intelligent Outline
AI-generated outlines with source mapping, grounding insights, and optimization recommendations.
#### Phase 3: Content Generation
Section-by-section content generation with SEO optimization, context memory, and engagement improvements.
#### Phase 4: SEO Analysis
Advanced SEO analysis with actionable recommendations and AI-powered optimization.
#### Phase 5: SEO Metadata
Optimized metadata generation for titles, descriptions, Open Graph, Twitter Cards, and structured data.
#### Phase 6: Publish & Distribute
Direct publishing to WordPress, Wix, Medium, and other platforms with scheduling capabilities.
### Phase Features At a Glance
| Phase | Key Features | Target Benefits | Best For |
|-------|-------------|-----------------|----------|
| **Phase 1: Research** | Google Search grounding, Competitor analysis, Keyword intelligence, Content angles | Comprehensive data, Time savings, Market insights | All content creators |
| **Phase 2: Outline** | AI generation, Source mapping, Interactive refinement, Title suggestions | Structured content, SEO foundation, Editorial flexibility | Professional writers |
| **Phase 3: Content** | Context-aware writing, Flow analysis, Source integration, Medium mode | High quality, Consistency, Citation accuracy | Content teams |
| **Phase 4: SEO** | Multi-dimensional scoring, Actionable recommendations, AI refinement | Search visibility, Competitive edge, Performance tracking | SEO professionals |
| **Phase 5: Metadata** | Comprehensive SEO tags, Social optimization, Schema markup, Multi-format export | Complete optimization, Rich snippets, Cross-platform readiness | Digital marketers |
| **Phase 6: Publish** | Multi-platform support, Scheduling, Version management, Analytics integration | Efficiency, Strategic timing, Quality control | Solopreneurs & teams |
### What Happens Behind the Scenes
The Blog Writer leverages sophisticated AI orchestration to ensure quality at every stage:
- **Research Phase**: AI searches the web using Gemini's native Google Search integration for current, credible information and sources
- **Outline Generation**: Creates logical structure with headings, key points, and source mapping using parallel processing
- **Content Writing**: Generates engaging, context-aware content for each section with continuity tracking and flow analysis
- **SEO Optimization**: Runs comprehensive analysis with parallel non-AI analyzers plus AI insights for actionable recommendations
- **Metadata Generation**: Creates complete SEO metadata package with social media optimization in 2 AI calls maximum
- **Publishing**: Formats content for your chosen platform with scheduling and version management
### User-Friendly Features
- **Progress Tracking**: See real-time progress for all long-running tasks with detailed status updates
- **Visual Editor**: Easy-to-use WYSIWYG interface with markdown support and live preview
- **Title Suggestions**: Multiple AI-generated, SEO-scored title options to choose from
- **SEO Integration**: Comprehensive analysis with one-click "Apply Recommendations" for instant optimization
- **Context Memory**: Intelligent continuity tracking across sections for consistent, flowing content
- **Source Attribution**: Automatic citation integration with research source mapping
## Content Types
### Blog Posts
- **How-to Guides**: Step-by-step tutorials
- **Listicles**: Numbered list articles
- **Case Studies**: Real-world examples
- **Opinion Pieces**: Thought leadership content
### Long-form Content
- **Comprehensive Guides**: In-depth resources
- **White Papers**: Professional documents
- **E-books**: Extended content pieces
- **Research Reports**: Data-driven content
## SEO Features
### Keyword Optimization
- **Primary Keywords**: Main topic keywords
- **Secondary Keywords**: Supporting terms
- **Long-tail Keywords**: Specific phrases
- **LSI Keywords**: Semantically related terms
### Content Structure
- **Headings**: H1, H2, H3 hierarchy
- **Paragraphs**: Optimal length and structure
- **Lists**: Bulleted and numbered lists
- **Images**: Alt text and captions
### Meta Optimization
- **Title Tags**: SEO-optimized titles
- **Meta Descriptions**: Compelling descriptions
- **URL Structure**: Clean, readable URLs
- **Schema Markup**: Structured data
## Writing Styles
### Professional
- **Business Content**: Corporate communications
- **Technical Writing**: Industry-specific content
- **Academic Style**: Research-based content
- **Formal Tone**: Professional language
### Conversational
- **Blog Style**: Casual, engaging tone
- **Social Media**: Platform-optimized content
- **Personal Brand**: Authentic voice
- **Community Content**: Community-focused writing
## Integration Features
### Google Search Console
- **Performance Data**: Real search performance
- **Keyword Insights**: Actual search queries
- **Click-through Rates**: CTR optimization
- **Search Rankings**: Position tracking
### Analytics Integration
- **Google Analytics**: Traffic analysis
- **Content Performance**: Engagement metrics
- **User Behavior**: Reader interaction data
- **Conversion Tracking**: Goal completion
## Best Practices
### Content Quality
1. **Research Thoroughly**: Use multiple sources
2. **Original Content**: Avoid plagiarism
3. **Fact-checking**: Verify all information
4. **Regular Updates**: Keep content current
### SEO Optimization
1. **Keyword Density**: Natural keyword usage
2. **Content Length**: Optimal word count
3. **Internal Linking**: Strategic link placement
4. **External Links**: Authoritative sources
### User Experience
1. **Readable Format**: Clear structure
2. **Visual Elements**: Images and graphics
3. **Mobile Optimization**: Responsive design
4. **Loading Speed**: Fast page loads
## Advanced Features
### ✨ Assistive Writing & Quick Edits
- **Continue Writing**: AI-powered contextual suggestions as you type
- **Smart Typing Assist**: Automatic suggestions after 20+ words
- **Quick Edit Options**: Improve, expand, shorten, professionalize, add transitions, add data
- **Real-time Assistance**: Instant writing help without interrupting your flow
- **Cost-Optimized**: First suggestion automatic, then manual "Continue Writing" for efficiency
- **One-Click Improvements**: Select text and apply quick edits instantly
### 🔍 Fact-Checking & Quality Assurance
- **Hallucination Detection**: AI-powered verification of claims and facts
- **Source Verification**: Automatic cross-checking against research sources
- **Claim Analysis**: Detailed assessment of each verifiable statement
- **Evidence Support**: Links to supporting or refuting sources
- **Quality Scoring**: Overall confidence metrics for content accuracy
### 🖼️ Image Generation
- **Section-Specific Images**: Generate images per blog section from the outline
- **AI-Powered Prompts**: Auto-suggest images based on section content
- **Advanced Options**: Stability AI, Hugging Face, Gemini
- **Blog Optimization**: Sizes and formats for platform publishing
- **Integrated Workflow**: Generate inside the outline editor
### 📝 SEO Metadata Generation
- **Comprehensive Package**: Title, description, tags, categories, hashtags in 2 AI calls
- **Social Optimization**: Open Graph & Twitter Cards
- **Structured Data**: Schema.org JSON-LD for rich snippets
- **Multi-Format Export**: WordPress, Wix, HTML, JSON-LD
- **Live Preview**: Google, Facebook, Twitter
### Automation & Integration
- **Multi-Platform Publishing**: One-click to WordPress, Wix, Medium
- **Version Management**: Track changes and revisions
- **Scheduled Publishing**: Set future publish dates
- **Google Analytics Integration**: Track content performance
- **Search Console**: Monitor search visibility
## Who Benefits Most
### For Technical Content Writers
- **Research Automation**: Save hours of manual research with AI-powered Google Search grounding
- **Source Attribution**: Automatic citation management and credibility scoring
- **Quality Assurance**: Built-in fact-checking and hallucination detection
- **Citation Integration**: Seamless source references throughout content
### For Solopreneurs
- **Time Efficiency**: Complete blog creation workflow in minutes instead of hours
- **SEO Expertise**: Professional-grade optimization without hiring specialists
- **Multi-Platform Publishing**: One workflow, multiple destinations (WordPress, Wix, Medium)
- **Scheduling & Automation**: Strategic content distribution and timing optimization
### For Digital Marketing & SEO Professionals
- **Comprehensive SEO**: Multi-dimensional scoring with actionable insights
- **Competitive Intelligence**: AI-powered competitor analysis and content gap identification
- **Performance Tracking**: Integration with Google Analytics and Search Console
- **ROI Optimization**: Data-driven content strategy and performance analytics
## How to Use Advanced Features
### Using Assistive Writing (Continue Writing)
```mermaid
flowchart LR
A[Start Typing] -->|20+ words| B[Auto Suggestion]
B --> C{Accept or Reject?}
C -->|Accept| D[Suggestion Inserted]
C -->|Reject| E[Dismiss Suggestion]
D --> F[Continue Writing Button]
E --> F
F -->|Click| G[Manual Suggestion]
style A fill:#e3f2fd
style B fill:#e8f5e8
style G fill:#fff3e0
```
**Quick Steps - Continue Writing:**
1. Type 20+ words in any blog section
2. First suggestion appears automatically below your text
3. Click **"Accept"** to insert or **"Dismiss"** to skip
4. Use **"✍️ Continue Writing"** for more suggestions
5. Suggestions include source citations for fact-checking
**Quick Steps - Text Selection Edits:**
1. Select any text in your content
2. Context menu appears automatically
3. Choose quick edit: **Improve**, **Expand**, **Shorten**, **Professionalize**, **Add Transition**, or **Add Data**
4. Text updates instantly with your selected improvement
### Using Fact-Checking
1. Select a paragraph or claim in your blog content
2. Right-click to open context menu
3. Click **"🔍 Fact Check"**
4. Wait 15-30 seconds for analysis
5. Review results: claims, confidence, supporting/refuting sources
6. Click **"Apply Fix"** to insert source links
### Using Image Generation
1. In **Phase 2: Intelligent Outline**, click **"🖼️ Generate Image"** on any section
2. Modal opens with auto-generated prompt (editable)
3. Click **"Suggest Prompt"** for AI-optimized suggestions
4. Optionally open **"Advanced Image Options"**
5. Generate image (Stability AI, Hugging Face, or Gemini)
6. Image auto-inserts into outline and metadata
### Using SEO Metadata Generation
1. In **Phase 5: SEO Metadata**, open the modal
2. Click **"Generate All Metadata"** (max 2 AI calls)
3. Review tabs: Preview, Core, Social, Structured Data
4. Edit any field; previews update live
5. Copy formats for WordPress, Wix, or custom
6. Images from Phase 2 auto-fill Open Graph
## Getting Started
1. **[Research Integration](research.md)** - Comprehensive Phase 1 research capabilities
2. **[Workflow Guide](workflow-guide.md)** - Step-by-step 6-phase workflow walkthrough
3. **[SEO Analysis](seo-analysis.md)** - Phase 4 & 5 optimization strategies
4. **[Implementation Spec](implementation-spec.md)** - Technical architecture and API details
5. **[Best Practices](../../guides/best-practices.md)** - Advanced optimization tips
## Related Features
- **[SEO Dashboard](../seo-dashboard/overview.md)** - Comprehensive SEO tools
- **[Content Strategy](../content-strategy/overview.md)** - Strategic planning
- **[LinkedIn Writer](../linkedin-writer/overview.md)** - Social content
- **[AI Features](../ai/assistive-writing.md)** - Advanced AI capabilities
---
*Ready to create amazing blog content? Check out our [Research Integration Guide](research.md) to get started!*

View File

@@ -0,0 +1,386 @@
# Phase 1: Research & Strategy
ALwrity's Blog Writer Phase 1 provides powerful AI-powered research capabilities that automatically gather, analyze, and verify information to create well-researched, accurate, and comprehensive blog content. This foundation phase sets the stage for all subsequent content creation.
## Overview
Phase 1: Research & Strategy leverages Gemini's native Google Search grounding to conduct comprehensive topic research in a single API call, delivering competitor intelligence, keyword analysis, and content angles to inform your entire blog creation process.
### Key Benefits
- **Comprehensive Research**: Gather information from multiple reliable sources with Google Search grounding
- **Competitive Intelligence**: Identify content gaps and opportunities through competitor analysis
- **Keyword Intelligence**: Discover primary, secondary, and long-tail keyword opportunities
- **Content Angles**: AI-generated unique content angles for maximum engagement
- **Time Efficiency**: Complete research in 30-60 seconds with intelligent caching
## Research Data Flow
```mermaid
flowchart LR
A[User Input:<br/>Keywords + Topic] --> B[Phase 1: Research]
B --> C{Cache Check}
C -->|Hit| D[Return Cached<br/>Research]
C -->|Miss| E[Google Search<br/>Grounding]
E --> F[Source Extraction]
F --> G[Keyword Analysis]
F --> H[Competitor Analysis]
F --> I[Content Angle<br/>Generation]
G --> J[Research Output]
H --> J
I --> J
D --> J
J --> K[Cache Storage]
J --> L[Phase 2: Outline]
style B fill:#e8f5e8
style E fill:#fff3e0
style J fill:#e3f2fd
style L fill:#fff3e0
```
## Research Process
### 1. Topic Analysis
#### Initial Research Setup
- **Topic Understanding**: AI analyzes your topic and identifies key aspects
- **Research Scope**: Determines the breadth and depth of research needed
- **Source Selection**: Identifies relevant and authoritative sources
- **Research Strategy**: Develops a comprehensive research approach
#### Research Parameters
```json
{
"topic": "AI in Digital Marketing",
"research_depth": "comprehensive",
"sources": ["web", "academic", "industry"],
"language": "en",
"date_range": "last_12_months",
"fact_checking": true
}
```
### 2. Google Search Grounding (Gemini Integration)
Phase 1 leverages Gemini's native Google Search grounding to access real-time web data with a single API call, eliminating the need for complex multi-source integrations.
#### Single API Call Efficiency
- **One Request**: Comprehensive research in a single Gemini API call with Google Search grounding
- **Live Web Data**: Real-time access to current information from the web
- **No Multi-Source Setup**: Eliminates need for multiple API integrations
- **Cost Effective**: Optimized token usage with focused research prompts
- **Caching Intelligence**: Automatic cache storage for repeat keyword research
#### Research Sources (via Google Search)
The research prompt instructs Gemini to gather information from:
- **Current News**: Latest industry news and developments (2024-2025)
- **Industry Reports**: Market research and industry analysis
- **Expert Articles**: Authoritative blogs and professional content
- **Academic Sources**: Research papers and studies
- **Case Studies**: Real-world examples and implementations
- **Statistics**: Key data points and numerical insights
- **Trends**: Current market trends and forecasts
#### Google Search Grounding Example
```python
research_prompt = """
Research the topic "AI in Digital Marketing" in the technology industry for digital marketers.
Provide comprehensive analysis including:
1. Current trends and insights (2024-2025)
2. Key statistics and data points with sources
3. Industry expert opinions and quotes
4. Recent developments and news
5. Market analysis and forecasts
6. Best practices and case studies
7. Keyword analysis: primary, secondary, and long-tail opportunities
8. Competitor analysis: top players and content gaps
9. Content angle suggestions: 5 compelling angles for blog posts
Focus on factual, up-to-date information from credible sources.
"""
```
### 3. Competitor Analysis
The research phase automatically identifies competing content and discovers content gaps where your blog can stand out.
#### Content Gap Identification
- **Top Competitors**: Identifies the most authoritative content on your topic
- **Coverage Analysis**: Maps what competitors have covered thoroughly vs. superficially
- **Gap Opportunities**: Highlights underexplored angles and missing information
- **Unique Positioning**: Suggests how to differentiate your content
- **Competitive Advantages**: Identifies areas where you can exceed competitor quality
#### Competitive Intelligence
- **Content Depth**: Analyzes how thoroughly competitors cover topics
- **Keyword Usage**: Identifies keyword strategies in competitor content
- **Content Structure**: Evaluates how competitors organize information
- **Engagement Patterns**: Notes what formats and angles work best
- **Market Positioning**: Understands where competitors sit in the market
### 4. Keyword Intelligence
Phase 1 provides comprehensive keyword analysis to optimize your content for search engines.
#### Primary, Secondary & Long-Tail Keywords
- **Primary Keywords**: Main topic keywords with highest search volume
- **Secondary Keywords**: Supporting terms that reinforce the main topic
- **Long-Tail Keywords**: Specific, less competitive phrases with high intent
- **Semantic Keywords**: Related terms that search engines associate with your topic
- **Search Intent**: Categorizes keywords by intent (informational, transactional, navigational)
#### Keyword Clustering & Grouping
- **Topic Clusters**: Groups related keywords for comprehensive coverage
- **Thematic Organization**: Organizes keywords by content themes
- **Density Recommendations**: Suggests optimal keyword usage throughout content
- **Priority Ranking**: Identifies which keywords to prioritize
- **Competition Analysis**: Assesses difficulty for ranking on each keyword
### 5. Content Angle Generation
AI generates unique content angles that make your blog stand out and engage your audience.
#### AI-Generated Angle Suggestions
- **5 Unique Angles**: Provides multiple distinct approaches to your topic
- **Trending Topics**: Identifies currently popular angles and discussions
- **Audience Pain Points**: Maps audience challenges to content angles
- **Viral Potential**: Assesses which angles have high shareability
- **Expert Opinions**: Synthesizes industry expert viewpoints into angles
#### Content Angle Example
For a topic like "AI in Marketing," research might suggest:
1. **Case Study Angle**: "10 Marketing Agencies Using AI to Double ROI"
2. **Practical Guide Angle**: "Implementing AI Marketing Tools in 2025: A Step-by-Step Roadmap"
3. **Trend Analysis Angle**: "The Future of AI Marketing: What Industry Leaders Predict"
4. **Problem-Solution Angle**: "Common AI Marketing Failures and How to Avoid Them"
5. **Debunking Angle**: "AI Marketing Myths Debunked: What Actually Works in 2025"
### 6. Information Processing
#### Data Collection & Extraction
- **Source Extraction**: Automatically extracts 10-20 credible sources from Google Search
- **Fact Identification**: Identifies key facts, statistics, and claims with citations
- **Quote Collection**: Gathers relevant expert quotes with attribution
- **Trend Identification**: Highlights current trends and patterns
- **Search Query Tracking**: Tracks AI-generated search queries for transparency
#### Source Credibility & Verification
- **Automatic Citation**: Extracts source URLs, titles, and metadata for proper attribution
- **Grounding Metadata**: Includes detailed grounding support scores and chunks
- **Source Diversity**: Ensures mix of authoritative sources (academic, industry, news)
- **Credibility Scoring**: Evaluates source authority and reliability
- **Cross-Reference**: Cross-references key facts across multiple sources
## Research Output Structure
### Comprehensive Research Results
Phase 1 returns a complete research package that feeds into all subsequent phases:
#### Structured Data Package
- **Sources**: 10-20 credible research sources with full metadata
- **Keyword Analysis**: Primary, secondary, long-tail, and semantic keywords
- **Competitor Analysis**: Top competing content and identified gaps
- **Content Angles**: 5 unique, AI-generated content approaches
- **Search Queries**: AI-generated search terms for transparency
- **Grounding Metadata**: Detailed grounding support scores and chunks
#### Research Summary Example
```json
{
"success": true,
"sources": [
{
"url": "https://example.com/research",
"title": "AI Marketing Trends 2025",
"credibility_score": 0.92
}
],
"keyword_analysis": {
"primary": ["AI marketing", "artificial intelligence digital marketing"],
"secondary": ["machine learning marketing", "automated advertising"],
"long_tail": ["how to implement AI marketing tools"],
"search_intent": "informational"
},
"competitor_analysis": {
"top_competitors": [...],
"content_gaps": ["practical implementation guides", "cost-benefit analysis"]
},
"suggested_angles": [
"10 Marketing Agencies Using AI to Double ROI",
"Implementing AI Marketing Tools: A Step-by-Step Roadmap"
]
}
```
## Use Cases for Different Audiences
### For Technical Content Writers
**Scenario**: Writing a technical deep-dive on "React Performance Optimization"
**Phase 1 Delivers**:
- Latest React documentation updates and best practices
- GitHub discussions and Stack Overflow solutions for optimization challenges
- Academic research on frontend performance optimization
- Real-world case studies from major tech companies
- Technical keyword opportunities: "React performance hooks", "memoization strategies"
**Value**: Eliminates hours of manual research across GitHub, documentation, and forums
### For Solopreneurs
**Scenario**: Creating content on "Starting an E-commerce Business in 2025"
**Phase 1 Delivers**:
- Current e-commerce market trends and statistics
- Competitor analysis of top e-commerce success stories
- Content gap: most content focuses on "how to start" but lacks "common pitfalls"
- Unique angle: "The 5 Mistakes That Kill 90% of New E-commerce Businesses"
- Long-tail keywords: "start ecommerce business 2025", "ecommerce business ideas"
**Value**: Provides business intelligence without expensive consultants
### For Digital Marketing & SEO Professionals
**Scenario**: Content strategy for "Local SEO Best Practices"
**Phase 1 Delivers**:
- Competitor analysis of top-ranking local SEO content
- Keyword gaps: competitors missing "Google Business Profile optimization"
- Trending angles: "Voice search local optimization" and "AI-powered local listings"
- Data-backed insights: "73% of local searches result in store visits"
- Content opportunity: "Local SEO Audit Template" (high search, low competition)
**Value**: Delivers competitive intelligence and keyword strategy in one research pass
## Performance & Caching
### Intelligent Caching System
Phase 1 implements a dual-layer caching strategy to optimize performance and reduce costs.
#### Cache Storage
- **Persistent Cache**: SQLite database stores research results for exact keyword matches
- **Memory Cache**: In-process cache for faster repeated access within a session
- **Cache Key**: Based on exact keyword match, industry, and target audience
- **Cache Duration**: Results stored indefinitely until invalidated
#### Cache Benefits
- **Cost Reduction**: Avoids redundant API calls for same topics
- **Speed**: Instant results for cached research (0-5 seconds vs. 30-60 seconds)
- **Consistency**: Ensures reproducible research results for same queries
- **Transparency**: Progress messages indicate cache hits: "✅ Using cached research"
### Performance Metrics
**Typical Research Timing**:
- **Cache Hit**: 0-5 seconds (instant return)
- **Fresh Research**: 30-60 seconds (Google Search + AI processing)
- **Sources Found**: 10-20 credible sources per research
- **Search Queries**: 5-10 AI-generated search terms tracked
## Best Practices
### Effective Research Setup
#### Keyword Strategy
1. **Be Specific**: Use 3-5 focused keywords rather than broad topics
2. **Industry Context**: Always specify industry for better context
3. **Audience Definition**: Define target audience clearly for tailored research
4. **Topic Clarity**: Provide a clear, concise topic description
5. **Word Count Target**: Set realistic word count goals (1000-3000 words optimal)
#### Research Quality Optimization
1. **Review Sources**: Always review the returned sources for credibility
2. **Use Content Angles**: Leverage AI-generated angles for unique positioning
3. **Explore Competitor Gaps**: Focus on content gaps for competitive advantage
4. **Keyword Variety**: Review all keyword types (primary, secondary, long-tail)
5. **Leverage Caching**: Reuse research for related topics to save time and cost
### Research-to-Content Pipeline
#### Phase 1 to Phase 2 Transition
1. **Validate Research**: Ensure research has 10+ credible sources before proceeding
2. **Review Angles**: Select compelling content angles for outline inspiration
3. **Check Keywords**: Verify keyword analysis aligns with your SEO goals
4. **Analyze Gaps**: Use competitor analysis to inform unique content positioning
5. **Source Quality**: Confirm grounding metadata shows high credibility scores (0.8+)
#### Research Output Utilization
1. **Source Mapping**: Use sources strategically across different sections
2. **Keyword Integration**: Naturally integrate primary and secondary keywords
3. **Angles to Sections**: Transform content angles into distinct content sections
4. **Gaps to Value**: Convert content gaps into unique selling propositions
5. **Trend Integration**: Weave current trends naturally throughout content
## Troubleshooting
### Common Issues & Solutions
#### Low-Quality Research Results
**Problem**: Research returns fewer than 10 sources or low credibility scores
**Solutions**:
- **Refine Keywords**: Use more specific, focused keywords
- **Expand Topic**: Broaden topic slightly to increase source pool
- **Adjust Industry**: Ensure industry classification is accurate
- **Check Cache**: Clear cache if you're getting stale results
- **Retry Research**: Google Search grounding may need a second attempt
#### Insufficient Keyword Analysis
**Problem**: Limited keyword variety or missing long-tail opportunities
**Solutions**:
- **Add Topic Context**: Provide more detailed topic description
- **Specify Audience**: Better audience definition improves keyword targeting
- **Increase Word Count**: Target 2000+ words for richer keyword analysis
- **Review Persona Settings**: Industry and audience persona affects keyword discovery
#### Missing Competitor Data
**Problem**: Competitor analysis lacks depth or opportunities
**Solutions**:
- **Use Specific Keywords**: More targeted keywords reveal better competitors
- **Expand Industry Context**: Broad industry understanding improves competitive mapping
- **Review Content Angles**: Angles often highlight what competitors are NOT doing
- **Manual Review**: Top sources list shows main competitors worth reviewing
#### Cache Not Working
**Problem**: Research taking full time even for duplicate keywords
**Solutions**:
- **Check Exact Match**: Keywords, industry, and audience must match exactly
- **Verify Cache**: Check if persistent cache is enabled
- **Clear and Retry**: Sometimes clearing cache helps if data is corrupted
- **Check Logs**: Look for cache hit/miss messages in progress updates
### Getting Help
#### Support Resources
- **Workflow Guide**: [Complete 6-phase walkthrough](workflow-guide.md)
- **API Reference**: [Research API endpoints](api-reference.md)
- **Implementation Spec**: [Technical architecture](implementation-spec.md)
- **Best Practices**: [Advanced optimization tips](../../guides/best-practices.md)
#### Performance Optimization
- **Use Caching**: Leverage intelligent caching for repeat research
- **Keyword Precision**: More specific keywords yield better results
- **Industry Context**: Always provide industry for better data quality
- **Monitor Progress**: Review progress messages for efficiency insights
- **Batch Research**: Plan multiple blogs to maximize cache benefits
---
## Next Steps
Now that you understand Phase 1: Research & Strategy, move to the next phase:
- **[Phase 2: Intelligent Outline](workflow-guide.md#phase-2-intelligent-outline)** - Transform research into structured content plans
- **[Complete Workflow Guide](workflow-guide.md)** - End-to-end 6-phase walkthrough
- **[Blog Writer Overview](overview.md)** - Overview of all 6 phases
- **[Getting Started Guide](../../getting-started/quick-start.md)** - Quick start for new users
---
*Ready to leverage Phase 1 research capabilities? Check out the [Workflow Guide](workflow-guide.md) to see how research flows into outline generation and beyond!*

View File

@@ -0,0 +1,478 @@
# SEO Analysis & Optimization (Phase 4 & 5)
ALwrity's Blog Writer includes comprehensive SEO analysis and metadata generation capabilities across Phases 4 and 5, automatically optimizing your content for search engines and preparing it for publication across platforms.
## Overview
SEO optimization in the Blog Writer happens in two complementary phases:
- **Phase 4: SEO Analysis** - Comprehensive scoring, recommendations, and AI-powered content refinement
- **Phase 5: SEO Metadata** - Complete metadata generation including Open Graph, Twitter Cards, and Schema.org markup
### Key Benefits
#### Phase 4: SEO Analysis
- **Multi-Dimensional Scoring**: Comprehensive SEO evaluation across 5 key categories
- **Actionable Recommendations**: Priority-ranked improvement suggestions with specific fixes
- **AI-Powered Refinement**: One-click "Apply Recommendations" for instant optimization
- **Parallel Processing**: Fast analysis using parallel non-AI analyzers plus AI insights
- **Performance Tracking**: Track SEO improvements and measure impact
#### Phase 5: SEO Metadata
- **Comprehensive Metadata**: Complete SEO metadata package in 2 AI calls maximum
- **Social Optimization**: Open Graph and Twitter Cards for rich social previews
- **Structured Data**: Schema.org markup for enhanced search results and rich snippets
- **Multi-Format Export**: Ready-to-use formats for WordPress, Wix, and custom platforms
- **Platform Integration**: One-click copy and direct platform publishing support
## Phase 4: SEO Analysis
Phase 4 provides comprehensive SEO evaluation with actionable recommendations and AI-powered content refinement.
### Parallel Processing Architecture
Phase 4 uses a sophisticated parallel processing approach for speed and accuracy:
```mermaid
flowchart TD
A[Blog Content] --> B[Phase 4: SEO Analysis]
B --> C[Parallel Non-AI Analyzers]
C --> D[Content Structure]
C --> E[Keyword Usage]
C --> F[Readability]
C --> G[Content Quality]
C --> H[Heading Structure]
D --> I[SEO Results]
E --> I
F --> I
G --> I
H --> I
I --> J[Single AI Analysis]
J --> K[Actionable Recommendations]
K --> L[Apply Recommendations]
L --> M[Refined Content]
style A fill:#e3f2fd
style B fill:#f1f8e9
style C fill:#fff3e0
style I fill:#e8f5e8
style L fill:#fce4ec
style M fill:#e1f5fe
```
### Multi-Dimensional SEO Scoring
Phase 4 evaluates your content across 5 key categories:
#### Overall SEO Score
- **Composite Rating**: Overall score (0-100) based on weighted category scores
- **Grade Assignment**: Automatically assigns grades (Excellent/Good/Needs Improvement)
- **Trend Tracking**: Compares to previous analysis to track improvements
- **Visual Feedback**: Color-coded UI provides instant visual assessment
#### Category Breakdown
- **Structure Score**: Heading hierarchy, content organization, section balance
- **Keywords Score**: Keyword density, placement, variation, long-tail usage
- **Readability Score**: Reading level, sentence complexity, clarity assessment
- **Quality Score**: Content depth, engagement potential, value delivery
- **Headings Score**: H1-H3 distribution, keyword integration in headings
### Actionable Recommendations
Phase 4 generates specific, priority-ranked recommendations for improvement.
#### Recommendation Categories
- **High Priority**: Critical SEO issues impacting search visibility
- **Medium Priority**: Significant improvements that boost rankings
- **Low Priority**: Nice-to-have optimizations for fine-tuning
#### Example Recommendations
1. **Structure**: "Add more H2 subheadings to improve content scannability and keyword distribution"
2. **Keywords**: "Increase primary keyword density from 0.8% to 1.5% for optimal SEO performance"
3. **Readability**: "Simplify complex sentences; aim for average 15-20 words per sentence"
4. **Content**: "Add more specific examples and case studies to support key arguments"
5. **Meta**: "Reduce meta description to 155 characters for better search result display"
### AI-Powered Content Refinement
The "Apply Recommendations" feature uses AI to automatically improve your content based on SEO analysis.
#### Intelligent Rewriting
- **Smart Application**: Applies recommendations while preserving your original intent
- **Natural Integration**: Optimizes keywords and structure without sounding forced
- **Context Preservation**: Maintains research accuracy and source alignment
- **Quality Maintenance**: Ensures readability while improving SEO metrics
#### Application Process
```mermaid
flowchart LR
A[Current Content] --> B[SEO Recommendations]
B --> C[AI Prompt Construction]
C --> D[LLM Text Generation]
D --> E[Normalization & Validation]
E --> F[Optimized Content]
style A fill:#e3f2fd
style B fill:#fff3e0
style D fill:#f1f8e9
style F fill:#e8f5e8
```
### Content Analysis Process
#### Initial Assessment
- **Content Structure**: Analyzes heading hierarchy, paragraph distribution, list usage
- **Keyword Distribution**: Maps keyword density and placement across sections
- **Readability Metrics**: Calculates Flesch Reading Ease, sentence length, complexity
- **Quality Indicators**: Evaluates depth, engagement potential, value delivery
- **Technical Elements**: Checks heading structure, meta elements, content length
#### Parallel Analysis Details
Each analyzer processes content independently:
- **ContentAnalyzer**: Structure, organization, section balance
- **KeywordAnalyzer**: Density, placement, variation, semantic coverage
- **ReadabilityAnalyzer**: Reading level, sentence complexity, word choice
- **QualityAnalyzer**: Depth, engagement, value, completeness
- **HeadingAnalyzer**: Hierarchy, distribution, keyword integration
Results are combined with AI insights for comprehensive recommendations.
## Phase 5: SEO Metadata Generation
Phase 5 generates comprehensive SEO metadata in maximum 2 AI calls, creating a complete optimization package ready for publication.
### Efficient Two-Call Architecture
Phase 5 minimizes AI calls for cost efficiency while delivering comprehensive metadata:
```mermaid
flowchart TD
A[Blog Content + SEO Analysis] --> B[Phase 5: Metadata Generation]
B --> C{Call 1: Core Metadata}
C --> D[SEO Title]
C --> E[Meta Description]
C --> F[URL Slug]
C --> G[Tags & Categories]
C --> H[Reading Time]
D --> I{Call 2: Social Metadata}
E --> I
F --> I
G --> I
H --> I
I --> J[Open Graph Tags]
I --> K[Twitter Cards]
I --> L[Schema.org JSON-LD]
J --> M[Complete Metadata Package]
K --> M
L --> M
style A fill:#e3f2fd
style B fill:#e0f2f1
style C fill:#fff3e0
style I fill:#fce4ec
style M fill:#e8f5e8
```
### Core Metadata Generation
#### SEO-Optimized Elements
- **SEO Title** (50-60 chars): Front-loaded primary keyword, compelling, click-worthy
- **Meta Description** (150-160 chars): Keyword-rich with strong CTA in first 120 chars
- **URL Slug**: Clean, hyphenated, 3-5 words with primary keyword
- **Blog Tags** (5-8): Mix of primary, semantic, and long-tail keywords
- **Blog Categories** (2-3): Industry-standard classification
- **Social Hashtags** (5-10): Industry-specific with trending terms
- **Reading Time**: Calculated from word count (200 words/minute)
- **Focus Keyword**: Main SEO keyword selection
#### Metadata Personalization
Metadata is dynamically tailored based on:
- Research keywords and search intent
- Target audience and industry
- SEO analysis recommendations
- Blog content structure and outline
- Tone and writing style preferences
### Social Media Optimization
#### Open Graph Tags
- **og:title**: Optimized for social sharing
- **og:description**: Compelling social preview text
- **og:image**: Recommended image dimensions and sources
- **og:type**: Article/blog classification
- **og:url**: Canonical URL reference
#### Twitter Cards
- **twitter:card**: Summary card with large image support
- **twitter:title**: Concise, engaging headline
- **twitter:description**: Twitter-optimized summary
- **twitter:image**: Twitter-specific image optimization
- **twitter:site**: Website Twitter handle integration
### Structured Data (Schema.org)
#### Article Schema
```json
{
"@context": "https://schema.org",
"@type": "BlogPosting",
"headline": "SEO-optimized title",
"description": "Meta description",
"author": {
"@type": "Organization",
"name": "Your Brand"
},
"datePublished": "2025-01-20",
"dateModified": "2025-01-20",
"mainEntityOfPage": {
"@type": "WebPage"
}
}
```
#### Additional Schema Types
- **Organization Markup**: Brand and publisher information
- **Breadcrumb Schema**: Navigation structure for rich snippets
- **FAQ Schema**: Q&A structured data for featured snippets
- **Review Schema**: Ratings and review markup
### Multi-Format Export
Phase 5 outputs metadata in multiple formats for different platforms:
#### HTML Meta Tags
```html
<meta property="og:title" content="AI in Medical Diagnosis: Transforming Healthcare">
<meta name="description" content="Discover how AI is revolutionizing medical diagnosis...">
<meta name="keywords" content="AI healthcare, medical diagnosis, healthcare technology">
```
#### JSON-LD Structured Data
Ready-to-paste structured data for search engines
#### WordPress Export
WordPress-specific format with Yoast SEO compatibility
#### Wix Integration
Direct Wix blog API format for seamless publishing
## Analysis Results
### Phase 4 Output Structure
Phase 4 returns comprehensive analysis results:
```json
{
"overall_score": 82,
"grade": "Good",
"category_scores": {
"structure": 85,
"keywords": 88,
"readability": 78,
"quality": 80,
"headings": 84
},
"actionable_recommendations": [
{
"category": "Structure",
"priority": "High",
"recommendation": "Add H2 subheadings to improve scannability",
"impact": "Better keyword distribution and user experience"
},
{
"category": "Readability",
"priority": "Medium",
"recommendation": "Simplify complex sentences (average 20 words)",
"impact": "Improved readability score and engagement"
}
],
"keyword_analysis": {
"primary_keyword_density": 1.2,
"semantic_keyword_count": 15,
"long_tail_usage": 8,
"optimization_status": "Good"
}
}
```
## Use Cases for Different Audiences
### For Technical Content Writers
**Scenario**: Creating a technical deep-dive on "React Server Components"
**Phase 4 Delivers**:
- Structure score analysis: Identifies need for more code examples in H3 sections
- Readability assessment: Detects overly complex technical jargon
- Keyword optimization: Suggests semantic keywords like "React SSR" and "Next.js 13"
- Actionable fix: "Add 'why it matters' explanations for React Server Component concepts"
**Phase 5 Delivers**:
- SEO title: "React Server Components Explained: Complete 2025 Guide"
- Meta description: Includes CTA like "Master RSC implementation with practical examples"
- JSON-LD: Code schema markup for search engine code indexing
- Social tags: #React #WebDevelopment #Programming
**Value**: Technical content optimized for both search engines and developer audiences
### For Solopreneurs
**Scenario**: Blog on "Starting an Online Course Business"
**Phase 4 Delivers**:
- Quality score: Identifies missing CTA elements in conclusion
- Readability: Highlights need to simplify business jargon
- Keyword gaps: Discovers missing long-tail "online course pricing strategy"
- High-priority fix: "Add specific revenue examples to build credibility"
**Phase 5 Delivers**:
- SEO title: "Start Online Course Business: Ultimate 2025 Guide" (56 chars)
- Social hashtags: #OnlineCourses #PassiveIncome #Entrepreneurship
- Schema.org: EducationalCourse schema for course-related rich snippets
- Reading time: "15 minutes" for appropriate audience expectation
**Value**: Professional SEO without hiring expensive consultants
### For Digital Marketing & SEO Professionals
**Scenario**: Strategy content on "Local SEO for Small Businesses"
**Phase 4 Delivers**:
- Comprehensive scoring across all 5 categories with detailed breakdown
- Competitor analysis integration from Phase 1 research
- High-priority recommendations: "Missing Google Business Profile optimization section"
- Metrics: Keyword density at 0.9%, target 1.5-2% for competitive keywords
**Phase 5 Delivers**:
- Complete metadata package with local SEO schema markup
- Location-based Open Graph tags for local business visibility
- Multi-format export for WordPress with Yoast compatibility
- Structured data including LocalBusiness schema for local SERP features
**Value**: Enterprise-grade SEO optimization with detailed analytics
## Best Practices
### Phase 4: SEO Analysis Best Practices
#### Pre-Analysis Preparation
1. **Complete Content**: Ensure all sections are finalized before analysis
2. **Research Integration**: Verify Phase 1 research data includes keywords
3. **Word Count**: Target 1000-3000 words for optimal SEO analysis
4. **Structure Review**: Confirm proper heading hierarchy (H1, H2, H3)
5. **Content Quality**: Ensure content is factually accurate and complete
#### Using "Apply Recommendations"
1. **Review First**: Always review recommendations before applying
2. **Selective Application**: Consider applying high-priority fixes first
3. **Edit After**: Manually refine AI-applied changes for your voice
4. **Preserve Intent**: Verify AI preserved your original meaning
5. **Re-Analyze**: Run Phase 4 again after applying to track improvement
### Phase 5: Metadata Generation Best Practices
#### Metadata Optimization
1. **Title Length**: Keep SEO titles to 50-60 characters for SERP display
2. **Meta Descriptions**: Write 150-160 character descriptions with CTA in first 120 chars
3. **Keyword Placement**: Front-load primary keyword in title and first 120 chars of description
4. **Uniqueness**: Ensure metadata is unique for each blog post
5. **Brand Consistency**: Include brand name where appropriate without exceeding length limits
#### Social Media Optimization
1. **Image Planning**: Prepare 1200x630px images for Open Graph sharing
2. **Twitter Cards**: Ensure Twitter Card images are 1200x600px minimum
3. **Hashtag Strategy**: Mix industry-specific, trending, and branded hashtags
4. **Platform-Specific**: Review Open Graph vs Twitter Card differences
5. **Testing**: Use Facebook Debugger and Twitter Card Validator before publishing
### SEO Workflow Integration
#### Phase 4 to Phase 5 Flow
1. **Score First**: Always complete Phase 4 analysis before metadata generation
2. **Apply Fixes**: Use "Apply Recommendations" to improve scores to 80+
3. **Generate Metadata**: Run Phase 5 with optimized content
4. **Review Metadata**: Verify metadata reflects SEO improvements
5. **Export & Publish**: Copy metadata formats for your platform
#### Performance Optimization
1. **Cache Utilization**: Leverage research caching from Phase 1 for related topics
2. **Batch Analysis**: Analyze multiple blog drafts in one session to improve learning
3. **Score Tracking**: Monitor SEO score trends across multiple posts
4. **A/B Testing**: Test different metadata variations for CTR optimization
5. **Analytics Integration**: Connect to Google Analytics/Search Console post-publish
## Troubleshooting
### Common Issues & Solutions
#### Low SEO Scores (< 70)
**Problem**: Overall SEO score below 70 or grade showing "Needs Improvement"
**Solutions**:
- **Check Category Scores**: Review individual category breakdowns to identify weak areas
- **Apply High-Priority Recommendations**: Focus on critical fixes first
- **Verify Content Length**: Ensure 1000+ words for comprehensive analysis
- **Review Heading Structure**: Confirm proper H1/H2/H3 hierarchy
- **Re-run Analysis**: After fixing issues, re-analyze to track improvements
#### Keyword Analysis Issues
**Problem**: Low keyword scores or missing keyword recommendations
**Solutions**:
- **Verify Phase 1 Research**: Ensure Phase 1 keyword analysis completed successfully
- **Check Keyword Density**: Primary keyword should be 1-2% of total content
- **Review Placement**: Ensure keywords appear in title, first paragraph, and subheadings
- **Add Semantic Keywords**: Integrate related terms naturally throughout content
- **Consider Long-Tail**: Include 3-5 long-tail keyword variations
#### "Apply Recommendations" Not Working
**Problem**: Content doesn't update or changes seem minimal
**Solutions**:
- **Check Recommendations**: Verify actionable recommendations are actually present
- **Review Normalization**: Check if AI properly matched section IDs
- **Refresh UI**: Try closing and reopening the SEO Analysis modal
- **Manual Review**: Compare original vs. updated sections for subtle changes
- **Re-Analyze**: Run Phase 4 again to see if scores improved
#### Metadata Generation Issues
**Problem**: Phase 5 generates incomplete or low-quality metadata
**Solutions**:
- **Content Completeness**: Ensure blog content is finalized before metadata generation
- **Title/Slug Issues**: Generate metadata after choosing final blog title
- **Length Constraints**: Verify SEO titles (50-60) and descriptions (150-160) are respected
- **Re-run Phase 5**: If results are suboptimal, regenerate with clearer content
- **Manual Refinement**: Edit generated metadata for brand voice consistency
### Getting Help
#### Support Resources
- **[Workflow Guide](workflow-guide.md)**: Complete 6-phase walkthrough
- **[Blog Writer Overview](overview.md)**: Overview of all phases
- **[API Reference](api-reference.md)**: Technical API documentation
- **[Best Practices](../../guides/best-practices.md)**: Advanced optimization tips
#### Performance Tips
- **Batch Processing**: Analyze multiple drafts in one session for efficiency
- **Cache Benefits**: Reuse research from Phase 1 to speed up workflow
- **Score Tracking**: Monitor SEO improvements across multiple blog posts
- **Metadata Testing**: Use Facebook Debugger and Twitter Card Validator
- **Analytics Setup**: Connect Google Analytics/Search Console for post-publish tracking
---
## Next Steps
Now that you understand Phase 4 & 5, explore the complete workflow:
- **[Phase 1: Research](research.md)** - Comprehensive research capabilities
- **[Complete Workflow Guide](workflow-guide.md)** - End-to-end 6-phase walkthrough
- **[Blog Writer Overview](overview.md)** - All phases overview
- **[Getting Started Guide](../../getting-started/quick-start.md)** - Quick start for new users
---
*Ready to optimize your content for search engines? Check out the [Workflow Guide](workflow-guide.md) to see how Phase 4 & 5 integrate into the complete blog creation process!*

View File

@@ -0,0 +1,898 @@
# Blog Writer Workflow Guide
A comprehensive guide to using the ALwrity Blog Writer, from initial research to published content. This guide walks you through each phase of the blog writing process with practical examples and best practices.
## 🎯 Overview
The ALwrity Blog Writer follows a sophisticated 6-phase workflow designed to create high-quality, SEO-optimized blog content:
```mermaid
flowchart TD
A[Start: Keywords & Topic] --> B[Phase 1: Research & Strategy]
B --> C[Phase 2: Intelligent Outline]
C --> D[Phase 3: Content Generation]
D --> E[Phase 4: SEO Analysis]
E --> F[Phase 5: SEO Metadata]
F --> G[Phase 6: Publish & Distribute]
B --> B1[Google Search Grounding]
B --> B2[Competitor Analysis]
B --> B3[Research Caching]
C --> C1[AI Outline Generation]
C --> C2[Source Mapping]
C --> C3[Title Generation]
D --> D1[Section-by-Section Writing]
D --> D2[Context Memory]
D --> D3[Flow Analysis]
E --> E1[SEO Scoring]
E --> E2[Actionable Recommendations]
E --> E3[AI-Powered Refinement]
F --> F1[Comprehensive Metadata]
F --> F2[Open Graph & Twitter Cards]
F --> F3[Schema.org Markup]
G --> G1[Multi-Platform Publishing]
G --> G2[Scheduling]
G --> G3[Version Management]
style A fill:#e3f2fd
style B fill:#e8f5e8
style C fill:#fff3e0
style D fill:#fce4ec
style E fill:#f1f8e9
style F fill:#e0f2f1
style G fill:#f3e5f5
```
## ⏱️ Timeline Overview
Each phase has specific time requirements and dependencies:
```mermaid
gantt
title Blog Writing Workflow Timeline
dateFormat X
axisFormat %M:%S
section Phase 1 Research
Keyword Analysis :0, 10
Google Search :10, 40
Source Extraction :30, 50
Competitor Analysis :40, 60
Research Caching :50, 60
section Phase 2 Outline
AI Structure Planning :60, 80
Section Definition :75, 90
Source Mapping :85, 100
Title Generation :95, 110
section Phase 3 Content
Section 1 Writing :110, 140
Section 2 Writing :130, 160
Section 3 Writing :150, 180
Context Continuity :170, 200
section Phase 4 SEO
Parallel Analysis :200, 215
AI Scoring :210, 230
Recommendations :220, 235
Apply Refinement :230, 250
section Phase 5 Metadata
Core Metadata :250, 265
Social Tags :260, 275
Schema Markup :270, 285
section Phase 6 Publish
Platform Setup :285, 295
Content Publishing :290, 310
Verification :305, 320
```
## 📋 Prerequisites
Before starting, ensure you have:
- **API Access**: Valid ALwrity API key
- **Research Keywords**: 3-5 relevant keywords for your topic
- **Target Audience**: Clear understanding of your audience
- **Content Goals**: Defined objectives for your blog post
- **Word Count Target**: Desired length (typically 1000-3000 words)
## 🔍 Phase 1: Research & Strategy
### Step 1: Initiate Research
**Endpoint**: `POST /api/blog/research/start`
**Request Example**:
```json
{
"keywords": ["artificial intelligence", "healthcare", "medical diagnosis"],
"topic": "AI in Medical Diagnosis",
"industry": "Healthcare Technology",
"target_audience": "Healthcare professionals and medical researchers",
"tone": "Professional and authoritative",
"word_count_target": 2000,
"persona": {
"persona_id": "healthcare_professional",
"tone": "authoritative",
"audience": "healthcare professionals",
"industry": "healthcare"
}
}
```
**What Happens**:
1. **Keyword Analysis**: AI analyzes your keywords for search intent and relevance
2. **Web Search**: Google Search grounding finds current, credible sources
3. **Source Collection**: Gathers 10-20 high-quality research sources
4. **Competitor Analysis**: Identifies competing content and gaps
5. **Research Caching**: Stores results for future use
**Expected Duration**: 30-60 seconds
### Step 2: Monitor Research Progress
**Endpoint**: `GET /api/blog/research/status/{task_id}`
**Progress Messages**:
- "🔍 Starting research operation..."
- "📋 Checking cache for existing research..."
- "🌐 Conducting web search..."
- "📊 Analyzing sources..."
- "✅ Research completed successfully! Found 15 sources and 8 search queries."
**Success Indicators**:
- `status: "completed"`
- 10+ credible sources
- Comprehensive keyword analysis
- Identified content gaps and opportunities
### Step 3: Review Research Results
**Key Data Points**:
- **Sources**: Credible, recent research materials
- **Keyword Analysis**: Primary and secondary keywords
- **Competitor Analysis**: Top competing content
- **Suggested Angles**: Unique content opportunities
- **Search Queries**: AI-generated search terms
**Quality Checklist**:
- ✅ Sources are recent (within 2 years)
- ✅ High credibility scores (0.8+)
- ✅ Diverse source types (academic, industry, government)
- ✅ Relevant to your target audience
- ✅ Covers multiple aspects of your topic
## 📝 Phase 2: Intelligent Outline
### Step 1: Generate Outline
**Endpoint**: `POST /api/blog/outline/start`
**Request Example**:
```json
{
"research": {
"success": true,
"sources": [...],
"keyword_analysis": {...},
"competitor_analysis": {...},
"suggested_angles": [...],
"search_queries": [...],
"grounding_metadata": {...}
},
"persona": {
"persona_id": "healthcare_professional",
"tone": "authoritative",
"audience": "healthcare professionals",
"industry": "healthcare"
},
"word_count": 2000,
"custom_instructions": "Focus on practical implementation examples and case studies"
}
```
**What Happens**:
1. **Content Structure Planning**: Creates logical flow and organization
2. **Section Definition**: Defines headings, subheadings, and key points
3. **Source Mapping**: Maps research sources to specific sections
4. **Word Count Distribution**: Optimizes word count across sections
5. **Title Generation**: Creates multiple compelling title options
**Expected Duration**: 15-30 seconds
### Step 2: Review Generated Outline
**Key Components**:
- **Title Options**: 3-5 compelling, SEO-optimized titles
- **Outline Sections**: 5-8 well-structured sections
- **Source Mapping**: Research sources mapped to sections
- **Word Distribution**: Balanced word count across sections
- **Quality Metrics**: Overall outline quality score
**Quality Checklist**:
- ✅ Logical content flow and progression
- ✅ Balanced word count distribution
- ✅ Strong source coverage (80%+ sources mapped)
- ✅ SEO-optimized headings and structure
- ✅ Engaging title options
### Step 3: Refine Outline (Optional)
**Endpoint**: `POST /api/blog/outline/refine`
**Common Refinements**:
- **Enhance Flow**: Improve section transitions
- **Optimize Structure**: Better heading hierarchy
- **Rebalance Word Count**: Adjust section lengths
- **Add Sections**: Include missing content areas
- **Improve SEO**: Better keyword distribution
### 🖼️ Generate Images for Sections (Optional)
While in Phase 2, you can generate images for your outline sections.
**How It Works:**
1. Click the **"🖼️ Generate Image"** button on any section in the outline
2. Image modal opens with auto-generated prompt based on section heading
3. Click **"Suggest Prompt"** for AI-optimized suggestions
4. Optionally open **"Advanced Image Options"** for custom settings
5. Choose provider: Stability AI, Hugging Face, or Gemini
6. Generate and images auto-insert into outline and metadata
**Best Practices:**
- Generate images during outline review
- Use specific, descriptive prompts
- Match image style to your brand
- Generate multiple variations if needed
**Image Features:**
- Provider selection (Stability AI, Hugging Face, Gemini)
- Aspect ratio options (1:1, 16:9, 4:3)
- Style customization
- Auto-prompt suggestions
- Platform-optimized outputs
## ✍️ Phase 3: Content Generation
### Step 1: Generate Section Content
**Endpoint**: `POST /api/blog/section/generate`
**Request Example**:
```json
{
"section": {
"id": "intro",
"heading": "Introduction: AI Revolution in Medical Diagnosis",
"subheadings": [
"Current State of Medical Diagnosis",
"The Promise of AI Technology"
],
"key_points": [
"AI adoption rates in healthcare",
"Key benefits of AI diagnosis",
"Overview of current applications"
],
"references": [...],
"target_words": 300,
"keywords": ["AI healthcare", "medical diagnosis", "healthcare technology"]
},
"keywords": ["AI healthcare", "medical diagnosis"],
"tone": "professional",
"persona": {
"persona_id": "healthcare_professional",
"tone": "authoritative",
"audience": "healthcare professionals",
"industry": "healthcare"
},
"mode": "polished"
}
```
**What Happens**:
1. **Content Generation**: AI writes section content based on outline
2. **Citation Integration**: Automatically includes source citations
3. **Continuity Tracking**: Maintains content flow and consistency
4. **Quality Assurance**: Implements quality checks during generation
**Expected Duration**: 20-40 seconds per section
### Step 2: Review Generated Content
**Key Components**:
- **Markdown Content**: Well-formatted, engaging content
- **Citations**: Properly integrated source references
- **Continuity Metrics**: Content flow and consistency scores
- **Quality Scores**: Readability and engagement metrics
**Quality Checklist**:
- ✅ Meets target word count (±10%)
- ✅ Includes relevant citations
- ✅ Maintains professional tone
- ✅ Good readability score (70+)
- ✅ Proper keyword integration
### Step 3: Generate Remaining Sections
Repeat the process for each outline section:
1. **Introduction** (300 words)
2. **Key Applications** (500 words)
3. **Benefits and Challenges** (400 words)
4. **Implementation Strategies** (500 words)
5. **Future Outlook** (300 words)
**Pro Tips**:
- Generate sections in order for better continuity
- Review each section before proceeding
- Use continuity metrics to ensure flow
- Adjust tone and style as needed
### Advanced Features in Phase 3
#### ✨ Assistive Writing (Continue Writing)
As you write in any blog section, the AI provides contextual suggestions to help you continue.
**How It Works:**
1. Type 20+ words in any section
2. First suggestion appears automatically below your cursor
3. Click **"Accept"** to insert or **"Dismiss"** to skip
4. Click **"✍️ Continue Writing"** to request more suggestions
5. Suggestions include source citations when available
**Benefits:**
- Real-time writing assistance
- Context-aware continuations
- Source-backed suggestions
- Cost-optimized (first auto, then manual)
#### Quick Edit Options
Select text to access quick edit options in the context menu:
**Available Quick Edits:**
- **✏️ Improve**: Enhance readability and engagement
- ** Add Transition**: Insert transitional phrases (Furthermore, Additionally, Moreover)
- **📏 Shorten**: Condense while maintaining meaning
- **📝 Expand**: Add explanatory content and insights
- **💼 Professionalize**: Make more formal (convert contractions, improve tone)
- **📊 Add Data**: Insert statistical backing statements
**How It Works:**
1. Select any text in your blog content
2. Context menu appears near your cursor
3. Choose a quick edit option
4. Text updates instantly
**Best For:**
- Improving flow between sentences
- Adjusting tone and formality
- Adding supporting statements
- Professionalizing casual language
#### 🔍 Fact-Checking
Verify claims and facts in your content with AI-powered checking.
**How It Works:**
1. Select any paragraph or claim text
2. Right-click or use the context menu
3. Click **"🔍 Fact Check"**
4. Wait 15-30 seconds for analysis
5. Review detailed results with supporting/refuting sources
6. Click **"Apply Fix"** to insert source links if needed
**What Gets Analyzed:**
- Verifiable claims and statements
- Statistical data and percentages
- Dates, names, and events
- Industry-specific facts
**Results Include:**
- Claim-by-claim confidence scores
- Supporting evidence URLs
- Refuting sources (if applicable)
- Overall factual accuracy score
## 🔍 Phase 4: SEO Analysis
### Step 1: Perform SEO Analysis
**Endpoint**: `POST /api/blog/seo/analyze`
**Request Example**:
```json
{
"content": "# AI in Medical Diagnosis\n\nComplete blog content here...",
"blog_title": "AI in Medical Diagnosis: Transforming Healthcare Through Technology",
"keywords": ["AI healthcare", "medical diagnosis", "healthcare technology"],
"research_data": {
"sources": [...],
"keyword_analysis": {...},
"competitor_analysis": {...}
}
}
```
**What Happens**:
1. **Content Structure Analysis**: Evaluates heading hierarchy and organization
2. **Keyword Optimization**: Analyzes keyword density and placement
3. **Readability Assessment**: Checks content readability and flow
4. **SEO Scoring**: Generates comprehensive SEO scores
5. **Recommendation Generation**: Provides actionable optimization suggestions
**Expected Duration**: 10-20 seconds
### Step 2: Review SEO Analysis
**Key Metrics**:
- **Overall SEO Score**: 0-100 (aim for 80+)
- **Keyword Density**: Optimal range (1-3%)
- **Readability Score**: Flesch Reading Ease (aim for 70+)
- **Structure Analysis**: Heading hierarchy and organization
- **Recommendations**: Specific improvement suggestions
**Quality Checklist**:
- ✅ SEO score above 80
- ✅ Optimal keyword density
- ✅ Good readability score
- ✅ Proper heading structure
- ✅ Actionable recommendations
### Step 3: Apply SEO Recommendations (Optional)
**Endpoint**: `POST /api/blog/seo/apply-recommendations`
Use the "Apply Recommendations" button to automatically improve your content based on SEO analysis. The AI will:
- Optimize keyword density and placement
- Improve content structure and headings
- Enhance readability and flow
- Maintain your original voice and intent
**Expected Duration**: 20-40 seconds
## 📝 Phase 5: SEO Metadata
### Step 1: Generate Core Metadata
**Endpoint**: `POST /api/blog/seo/metadata`
**Request Example**:
```json
{
"content": "# AI in Medical Diagnosis\n\nComplete blog content here...",
"title": "AI in Medical Diagnosis: Transforming Healthcare Through Technology",
"keywords": ["AI healthcare", "medical diagnosis", "healthcare technology"],
"research_data": {
"sources": [...],
"keyword_analysis": {...}
}
}
```
**What Happens** (First AI Call):
1. **SEO Title**: Optimized for search engines (50-60 chars)
2. **Meta Description**: Compelling description with CTA (150-160 chars)
3. **URL Slug**: Clean, hyphenated, keyword-rich (3-5 words)
4. **Blog Tags**: Mix of primary, semantic, and long-tail keywords (5-8)
5. **Blog Categories**: Industry-standard classification (2-3)
6. **Social Hashtags**: Industry-specific with trending terms (5-10)
7. **Reading Time**: Calculated from word count
**Expected Duration**: 10-15 seconds
### Step 2: Generate Social Media & Schema Metadata
**What Happens** (Second AI Call):
1. **Open Graph Tags**: Optimized for Facebook/LinkedIn sharing
2. **Twitter Cards**: Twitter-specific optimization
3. **JSON-LD Schema**: Structured data for search engines
4. **Multi-Format Export**: WordPress, Wix, HTML, JSON-LD ready formats
**Generated Metadata Output**:
- **Core Elements**: Title, description, URL slug, tags, categories
- **Social Optimization**: Open Graph and Twitter Card tags
- **Structured Data**: Article schema with author, dates, organization
- **Platform Formats**: Copy-ready for WordPress, Wix, custom
**Expected Duration**: 10-15 seconds
### Step 3: Review & Export Metadata
**Quality Checklist**:
- ✅ SEO title is 50-60 characters with primary keyword
- ✅ Meta description includes CTA in first 120 chars
- ✅ URL slug is clean, readable, and keyword-rich
- ✅ Tags and categories are relevant and varied
- ✅ Social tags are optimized for each platform
- ✅ Schema markup is valid JSON-LD
**Export Options**:
- Copy HTML meta tags directly to your platform
- Export JSON-LD for search engines
- WordPress-ready format with Yoast compatibility
- Wix integration format
## 🚀 Phase 6: Publish & Distribute
### Step 1: Prepare for Publishing
**Endpoint**: `POST /api/blog/publish`
**Request Example**:
```json
{
"platform": "wordpress",
"html": "<h1>AI in Medical Diagnosis</h1><p>Content here...</p>",
"metadata": {
"seo_title": "AI in Medical Diagnosis: Transforming Healthcare Through Technology",
"meta_description": "Discover how AI is transforming medical diagnosis...",
"url_slug": "ai-medical-diagnosis-healthcare-technology",
"blog_tags": ["AI healthcare", "medical diagnosis", "healthcare technology"],
"blog_categories": ["Healthcare Technology", "Artificial Intelligence"],
"social_hashtags": ["#AIHealthcare", "#MedicalAI", "#HealthTech"]
},
"schedule_time": "2024-01-20T09:00:00Z"
}
```
**What Happens**:
1. **Platform Integration**: Connects to WordPress or Wix
2. **Content Formatting**: Formats content for target platform
3. **Metadata Application**: Applies SEO metadata and tags
4. **Publishing**: Publishes content or schedules for later
**Expected Duration**: 5-15 seconds
### Step 2: Verify Publication
**Success Indicators**:
- ✅ Content published successfully
- ✅ SEO metadata applied correctly
- ✅ Social media tags included
- ✅ URL generated and accessible
- ✅ Scheduled publication confirmed (if applicable)
## 🔄 Blog Rewrite Workflow
The Blog Writer includes a sophisticated rewrite system for content improvement:
```mermaid
flowchart TD
Start([User Provides Feedback]) --> Analyze[Analyze Original Content]
Analyze --> Extract[Extract Improvement Areas]
Extract --> Plan[Plan Rewrite Strategy]
Plan --> Preserve[Preserve Core Elements]
Plan --> Enhance[Enhance Identified Areas]
Plan --> Add[Add New Elements]
Preserve --> Structure[Maintain Structure]
Preserve --> Arguments[Keep Main Arguments]
Preserve --> Data[Preserve Key Data]
Enhance --> Engagement[Improve Engagement]
Enhance --> Clarity[Enhance Clarity]
Enhance --> Examples[Add Examples]
Add --> Hook[Compelling Hook]
Add --> Transitions[Better Transitions]
Add --> CTA[Strong Call-to-Action]
Structure --> Rewrite[Generate Rewritten Content]
Arguments --> Rewrite
Data --> Rewrite
Engagement --> Rewrite
Clarity --> Rewrite
Examples --> Rewrite
Hook --> Rewrite
Transitions --> Rewrite
CTA --> Rewrite
Rewrite --> Quality[Quality Assessment]
Quality --> Compare[Compare Improvements]
Compare --> Final[Final Review]
Final --> Complete([Enhanced Blog])
style Start fill:#e3f2fd
style Analyze fill:#e8f5e8
style Plan fill:#fff3e0
style Rewrite fill:#fce4ec
style Quality fill:#f1f8e9
style Complete fill:#e1f5fe
```
## 🔀 Workflow Decision Tree
The Blog Writer adapts its workflow based on your specific needs:
```mermaid
flowchart TD
Start([Start Blog Creation]) --> Input{What's your content goal?}
Input -->|Quick Content| Quick[Medium Blog Generation<br/>≤1000 words]
Input -->|Comprehensive Content| Full[Full Blog Workflow<br/>1000+ words]
Input -->|Content Improvement| Rewrite[Blog Rewriting<br/>Based on feedback]
Quick --> QuickResearch[Basic Research]
QuickResearch --> QuickOutline[Simple Outline]
QuickOutline --> QuickContent[Single-pass Generation]
QuickContent --> QuickSEO[Basic SEO]
QuickSEO --> QuickPublish[Publish]
Full --> FullResearch[Comprehensive Research]
FullResearch --> FullOutline[Detailed Outline]
FullOutline --> FullContent[Section-by-Section]
FullContent --> FullSEO[Advanced SEO]
FullSEO --> FullQA[Quality Assurance]
FullQA --> FullPublish[Publish]
Rewrite --> RewriteAnalysis[Analyze Current Content]
RewriteAnalysis --> RewriteFeedback[Apply User Feedback]
RewriteFeedback --> RewriteImprove[Improve Content]
RewriteImprove --> RewriteQA[Quality Check]
RewriteQA --> RewritePublish[Publish Updated]
style Start fill:#e3f2fd
style Quick fill:#e8f5e8
style Full fill:#fff3e0
style Rewrite fill:#fce4ec
style QuickPublish fill:#e1f5fe
style FullPublish fill:#e1f5fe
style RewritePublish fill:#e1f5fe
```
## 🔄 Blog Rewrite Workflow
### When to Use Blog Rewrite
The Blog Rewrite feature is ideal when you need to:
- **Improve Engagement**: Make content more compelling and reader-friendly
- **Add Examples**: Include specific, relevant examples and case studies
- **Enhance Clarity**: Improve readability and reduce complexity
- **Update Information**: Incorporate new data or recent developments
- **Refine Tone**: Adjust the writing style for different audiences
- **Optimize Structure**: Improve flow and logical progression
### Rewrite Process
#### Step 1: Provide Feedback
```json
{
"user_feedback": {
"improvements_needed": [
"Make the introduction more engaging",
"Add more specific examples",
"Improve the conclusion"
],
"target_audience": "healthcare professionals",
"tone": "professional",
"focus_areas": ["engagement", "examples", "clarity"]
}
}
```
#### Step 2: Configure Rewrite Options
```json
{
"rewrite_options": {
"preserve_structure": true,
"enhance_engagement": true,
"add_examples": true,
"improve_clarity": true
}
}
```
#### Step 3: Monitor Progress
- **Started**: Task initiated successfully
- **Analyzing**: Reviewing original content and feedback
- **Planning**: Developing rewrite strategy
- **Rewriting**: Generating improved content
- **Reviewing**: Final quality assessment
- **Completed**: Enhanced content ready
#### Step 4: Review Results
The rewrite system provides:
- **Original vs. Rewritten Content**: Side-by-side comparison
- **Improvements Made**: Detailed list of enhancements
- **Quality Metrics**: Before/after scores for engagement, readability, clarity
- **Preserved Elements**: What was maintained from the original
- **New Elements**: What was added or enhanced
### Rewrite Best Practices
#### Effective Feedback
- **Be Specific**: Instead of "make it better," specify "add more healthcare examples"
- **Focus Areas**: Identify 2-3 key areas for improvement
- **Target Audience**: Clearly define who will read the content
- **Tone Guidelines**: Specify the desired writing style
#### Quality Expectations
- **Engagement Score**: Target 0.85+ for compelling content
- **Readability Score**: Target 0.80+ for clear communication
- **Clarity Score**: Target 0.90+ for professional content
- **Overall Improvement**: Expect 15-25% improvement in quality metrics
#### Common Use Cases
1. **Content Refresh**: Update existing blog posts with new information
2. **Audience Adaptation**: Modify content for different reader groups
3. **Engagement Boost**: Make technical content more accessible
4. **SEO Enhancement**: Improve content for better search rankings
5. **Brand Alignment**: Adjust tone to match brand voice
## 🎯 Best Practices
### Research Phase
- **Use Specific Keywords**: Avoid overly broad terms
- **Define Clear Audience**: Be specific about target readers
- **Set Realistic Word Count**: 1000-3000 words typically optimal
- **Review Source Quality**: Ensure credible, recent sources
### Outline Phase
- **Review Title Options**: Choose the most compelling and SEO-friendly
- **Check Section Balance**: Ensure even word count distribution
- **Verify Source Mapping**: Confirm good source coverage
- **Refine as Needed**: Use refinement tools for better structure
### Content Generation
- **Generate in Order**: Maintain content flow and continuity
- **Review Each Section**: Check quality before proceeding
- **Monitor Continuity**: Use continuity metrics for consistency
- **Adjust Tone**: Ensure consistent voice throughout
### SEO Optimization
- **Aim for High Scores**: Target SEO score above 80
- **Optimize Keywords**: Ensure proper density and placement
- **Improve Readability**: Target Flesch score above 70
- **Follow Recommendations**: Implement suggested improvements
### Quality Assurance
- **Verify Facts**: Ensure high factual accuracy
- **Check Sources**: Confirm good source coverage
- **Review Quality**: Aim for quality score above 85
- **Address Issues**: Fix any identified problems
### Publishing
- **Choose Right Platform**: Select appropriate publishing platform
- **Apply Metadata**: Ensure all SEO metadata is included
- **Schedule Strategically**: Publish at optimal times
- **Verify Results**: Confirm successful publication
## 🚨 Common Issues & Solutions
### Research Issues
**Problem**: Low-quality sources
**Solution**: Refine keywords, adjust topic focus, increase word count target
**Problem**: Insufficient research data
**Solution**: Add more keywords, broaden topic scope, adjust target audience
### Outline Issues
**Problem**: Poor section structure
**Solution**: Use outline refinement, adjust custom instructions, review research data
**Problem**: Unbalanced word distribution
**Solution**: Use rebalance outline feature, adjust target word counts
### Content Issues
**Problem**: Low continuity scores
**Solution**: Generate sections in order, review continuity metrics, adjust tone
**Problem**: Poor readability
**Solution**: Use content optimization, simplify language, improve structure
### SEO Issues
**Problem**: Low SEO scores
**Solution**: Improve keyword density, enhance structure, follow recommendations
**Problem**: Poor readability scores
**Solution**: Simplify sentences, improve paragraph structure, use shorter words
### Quality Issues
**Problem**: Low factual accuracy
**Solution**: Review sources, improve citations, verify claims
**Problem**: Poor source coverage
**Solution**: Add more research sources, improve source mapping, enhance citations
## 📊 Performance Metrics
### Target Metrics Visualization
```mermaid
pie title Quality Metrics Distribution
"Research Quality (25%)" : 25
"Content Quality (30%)" : 30
"SEO Performance (20%)" : 20
"Factual Accuracy (15%)" : 15
"Readability (10%)" : 10
```
### Performance Dashboard
```mermaid
graph LR
subgraph "Research Phase"
R1[Sources: 10+]
R2[Credibility: 0.8+]
R3[Coverage: 80%+]
end
subgraph "Outline Phase"
O1[Structure: Optimal]
O2[Balance: Even]
O3[SEO: Optimized]
end
subgraph "Content Phase"
C1[Quality: 85+]
C2[Readability: 70+]
C3[Continuity: 90+]
end
subgraph "SEO Phase"
S1[Score: 80+]
S2[Keywords: Optimal]
S3[Structure: Good]
end
subgraph "Quality Phase"
Q1[Accuracy: 90+]
Q2[Sources: 80%+]
Q3[Facts: Verified]
end
R1 --> O1
R2 --> O2
R3 --> O3
O1 --> C1
O2 --> C2
O3 --> C3
C1 --> S1
C2 --> S2
C3 --> S3
S1 --> Q1
S2 --> Q2
S3 --> Q3
style R1 fill:#e8f5e8
style R2 fill:#e8f5e8
style R3 fill:#e8f5e8
style O1 fill:#fff3e0
style O2 fill:#fff3e0
style O3 fill:#fff3e0
style C1 fill:#fce4ec
style C2 fill:#fce4ec
style C3 fill:#fce4ec
style S1 fill:#f1f8e9
style S2 fill:#f1f8e9
style S3 fill:#f1f8e9
style Q1 fill:#e0f2f1
style Q2 fill:#e0f2f1
style Q3 fill:#e0f2f1
```
### Target Metrics
- **Research Quality**: 10+ credible sources, 0.8+ credibility scores
- **Outline Quality**: 80%+ source coverage, balanced word distribution
- **Content Quality**: 85+ quality score, 70+ readability score
- **SEO Performance**: 80+ SEO score, optimal keyword density
- **Factual Accuracy**: 90%+ accuracy, 80%+ source coverage
### Monitoring
- **Track Progress**: Monitor each phase completion
- **Review Metrics**: Check quality scores at each step
- **Address Issues**: Fix problems as they arise
- **Optimize Continuously**: Use feedback for improvement
---
*This workflow guide provides a comprehensive approach to using the ALwrity Blog Writer effectively. For technical details, see the [API Reference](api-reference.md) and [Implementation Overview](implementation-overview.md).*