# π Blog Expert β Multi-Agent AI Blog Generation & Optimization Engine
[](https://www.python.org/)
[](https://langchain.com/)
[](https://langchain-ai.github.io/langgraph/)
[](https://streamlit.io/)
[](https://groq.com/)
[](https://deepmind.google/technologies/gemini/)
[](https://openai.com/)
[](https://www.pinecone.io/)
**An autonomous, multi-agent AI editorial system that crafts, scores, and refines high-authority, publication-ready long-form articles with strict E-E-A-T, SEO, and GEO standards.**
---
## π€ Developer Profile
| Field | Details |
| :--- | :--- |
| **π€ Lead Developer** | **Abhinav Gupta** |
| **πΌ Role** | AI Developer |
| **π’ Organization** | **AI India Innovations** |
| **π§ Email** | [abhinavg.aiindia@gmail.com](mailto:abhinavg.aiindia@gmail.com) |
| **π Repository** | [https://gitea.aiindia.ai/Abhinav_Gupta/Blog-_Expert.git](https://gitea.aiindia.ai/Abhinav_Gupta/Blog-_Expert.git) |
---
## π Table of Contents
- [π What is Blog Expert?](#-what-is-blog-expert)
- [β¨ Key Features & Innovations](#-key-features--innovations)
- [π Architectural Flowsheet](#-architectural-flowsheet)
- [Flowchart Diagram](#flowchart-diagram)
- [Pipeline Breakdown](#pipeline-breakdown)
- [π€ Specialized Agent Swarm](#-specialized-agent-swarm)
- [π 6-Dimension Quality Rubric](#-6-dimension-quality-rubric)
- [β‘ Speed Generation Profiles](#-speed-generation-profiles)
- [πΌοΈ Image Intelligence & Deduplication](#-image-intelligence--deduplication)
- [π οΈ Tech Stack & Frameworks](#-tech-stack--frameworks)
- [π Project Directory Structure](#-project-directory-structure)
- [π Getting Started & Execution Guide](#-getting-started--execution-guide)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Environment Configuration](#environment-configuration)
- [Running the Application](#running-the-application)
- [π₯ Export Capabilities](#-export-capabilities)
- [π History & Failure Diagnostics](#-history--failure-diagnostics)
- [π License & Credits](#-license--credits)
---
## π What is Blog Expert?
**Blog Expert** is a production-grade multi-agent autonomous content pipeline. Unlike naive one-shot LLM generators that produce repetitive, generic, or hallucinated articles, Blog Expert replicates the workflow of a **world-class digital newsroom and content marketing agency**:
1. **Strategic Planning & Research:** A supervisor agent coordinates live web queries (via Tavily & Firecrawl) to collect real-time data, benchmark facts, and citation sources.
2. **Specialist Fan-Out:** Parallel expert agents inspect language tone, factual depth, structural flow, search engine optimization (SEO), generative engine optimization (GEO), and visual asset selection.
3. **Rigorous Quality Scoring:** Drafts are graded against a strict 6-dimensional rubric (0β100 scale).
4. **Autonomous Self-Refinement:** An iterative Optimizer Agent rewrites deficient sections until the draft satisfies specified quality thresholds.
5. **Clean Multi-Format Export:** Directly produces clean Word (`.docx`), PDF (`.pdf`), and Markdown (`.md`) documents without internal evaluation noise.
---
## β¨ Key Features & Innovations
- π― **Dual Operational Pathways:**
- **Generate Mode:** Create comprehensive, high-ranking blog articles from a raw prompt or topic idea with standalone quality metrics.
- **Enhance Mode:** Ingest any existing live web URL, perform a baseline 6-dimension evaluation, and generate a modernized, SEO/GEO-boosted version with delta score tracking.
- β‘ **Parallel Specialist Fan-Out:** 6 domain-specific agents run concurrently to craft in-depth briefs across linguistic tone, E-E-A-T facts, structural hierarchy, SEO keywords, GEO prompt-readiness, and visual media.
- π **Supervisor Research Architecture:** Live search queries prevent token bloat by distilling raw web scrapes into modular, domain-specific briefs before writing commences.
- πΌοΈ **MD5 Content-Hash Image Deduplication:** Binary image verification guarantees zero duplicate graphics, exact target image counts, and contextual paragraph-level placement with attribution.
- π **Self-Healing Refinement Loop:** LangGraph state machine routes drafts below threshold back to the Optimizer Agent for targeted rewriting.
- π **Delta Score Visualization:** Interactive Streamlit interface displays side-by-side metric improvements for URL enhancement runs.
- π‘οΈ **Failure Diagnostics:** Root-cause error handling with actionable remediation advice and debug logs.
---
## π Architectural Flowsheet
### Flowchart Diagram
```mermaid
flowchart TD
%% Styling & Theme
classDef input fill:#0f172a,stroke:#38bdf8,stroke-width:2px,color:#fff;
classDef prep fill:#1e293b,stroke:#818cf8,stroke-width:2px,color:#fff;
classDef supervisor fill:#312e81,stroke:#a855f7,stroke-width:2px,color:#fff;
classDef parallel fill:#064e3b,stroke:#10b981,stroke-width:2px,color:#fff;
classDef writer fill:#701a75,stroke:#ec4899,stroke-width:2px,color:#fff;
classDef eval fill:#7c2d12,stroke:#f97316,stroke-width:2px,color:#fff;
classDef export fill:#0f172a,stroke:#22c55e,stroke-width:2px,color:#fff;
Start([π¬ User Input: URL or Topic Idea]):::input --> Pathway{Pathway Mode?}:::input
%% Enhance Pathway
Pathway -- "Enhance Existing URL" --> Scrape[β‘ Fast Web Scraper / Firecrawl]:::prep
Scrape --> Pinecone[π² Background Vector Indexing: Pinecone RAG]:::prep
Scrape --> BaseEval[π Baseline Evaluator: 6 Quality Dimensions]:::eval
BaseEval --> Learner[π§ Learner: Intent & Target Keyword Extraction]:::prep
%% Generate Pathway
Pathway -- "Generate From Topic" --> PromptGen[π‘ Prompt Generator: Topic Scaffolding]:::prep
PromptGen --> Learner
%% Planning & Research
Learner --> Planner[π Planner: Content Strategy & Section Outline]:::prep
Planner --> Supervisor[π Supervisor: Focused Research Briefs via Tavily]:::supervisor
%% Parallel Fan-Out
subgraph Phase_Specialists [β‘ Phase 2: Parallel Specialist Fan-Out]
Supervisor --> S_Lang[βοΈ Language Specialist]:::parallel
Supervisor --> S_Facts[π Facts & E-E-A-T Specialist]:::parallel
Supervisor --> S_Struct[ποΈ Structure Specialist]:::parallel
Supervisor --> S_SEO[π― SEO Keyword Analyst]:::parallel
Supervisor --> S_GEO[π GEO / AI-Search Engine Specialist]:::parallel
Supervisor --> S_Img[πΌοΈ Image & Visual Asset Selector]:::parallel
end
%% Aggregation
S_Lang & S_Facts & S_Struct & S_SEO & S_GEO & S_Img --> Aggregator[π Aggregator: Long-Form Synthesis & Formatting]:::writer
%% Quality Evaluation & Optimizer Loop
Aggregator --> Evaluator[βοΈ Evaluator: Standardized 0-100 Scoring]:::eval
Evaluator --> RouterCheck{Speed Mode & Quality Floor?}:::eval
RouterCheck -- "β‘ Turbo (Score >= 70 or 1 pass)" --> Finalize[π Article Finalization]:::writer
RouterCheck -- "βοΈ Balanced (Score >= 80 or 3 passes)" --> Finalize
RouterCheck -- "π¬ Deep Analysis (Score >= 95 or max passes)" --> Finalize
RouterCheck -- "Scores Below Threshold" --> Optimizer[π Optimizer Agent: Targeted Section Rewriting]:::writer
Optimizer --> Evaluator
%% Outputs & Exports
Finalize --> UI[π₯οΈ Streamlit Interactive Dashboard]:::export
Finalize --> ExDOCX[π₯ Export Microsoft Word .docx]:::export
Finalize --> ExPDF[π Export Adobe PDF .pdf]:::export
Finalize --> ExMD[π Export Clean Markdown .md]:::export
```
### Pipeline Breakdown
| Stage | Component | Functionality |
| :--- | :--- | :--- |
| **1. Ingestion** | `Scraper` / `PromptGen` | Scrapes target URL via Firecrawl/BeautifulSoup or generates topic scaffolding. |
| **2. Analysis** | `Learner` & `BaseEval` | Extracts target audience, user intent, keyword entities, and scores baseline URL. |
| **3. Strategy** | `Planner` & `Supervisor` | Structures section-by-section outline and conducts web research via Tavily API. |
| **4. Synthesis** | `Aggregator` | Fuses 6 specialist inputs into a cohesive, structured, citation-backed long-form blog. |
| **5. Validation** | `Evaluator` | Rigorously grades draft against 6 dimensions (Language, Facts, Structure, SEO, GEO, Freshness). |
| **6. Refinement**| `Optimizer` | Surgical rewriting of underperforming sections based on evaluation feedback. |
| **7. Export** | `Exporter` | Strips evaluation metadata and delivers production-ready `.docx`, `.pdf`, and `.md`. |
---
## π€ Specialized Agent Swarm
Each agent in Blog Expert specializes in a specific editorial responsibility:
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β AGENT SPECIALIZATIONS β
βββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β βοΈ Language Agent β Readability rhythm, conversational authority, β
β β active voice, zero AI clichΓ© buzzwords. β
βββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β π Facts & E-E-A-T β Ingestion of verified statistics, entity mapping, β
β β primary source citations, domain credibility. β
βββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β ποΈ Structure Agent β Logical heading hierarchy (H1 -> H2 -> H3), key β
β β takeaways, executive summaries, and FAQ sections. β
βββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β π― SEO Agent β Target keyword placement, search snippet prep, β
β β optimal heading densities, contextual internal anchors.β
βββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β π GEO Agent β Generative Engine Optimization for Perplexity, β
β β ChatGPT, and Gemini Search answer extraction. β
βββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β πΌοΈ Image Agent β Binary MD5 deduplication, relevance scoring, and β
β β natural paragraph-level anchor placement. β
βββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β βοΈ Evaluator Agent β Independent multi-rubric judge assessing the articleβ
β β against industry publication standards. β
βββββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β π Optimizer Agent β Closed-loop re-writer addressing specific weaknessesβ
β β identified during the evaluation phase. β
βββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
---
## π 6-Dimension Quality Rubric
Every generated or enhanced article is scored from **0 to 100** across six vital content dimensions:
| Dimension | Icon | Evaluation Focus |
| :--- | :---: | :--- |
| **Language & Readability** | βοΈ | Human-like flow, active voice, varied sentence lengths, zero AI fluff. |
| **Facts & Authority (E-E-A-T)** | π | Credible statistics, named sources, real-world data points, high E-E-A-T. |
| **Structural Architecture** | ποΈ | Clear H1/H2/H3 hierarchy, TL;DR executive summary, bullet points, FAQ schema. |
| **Search Engine Optimization** | π― | Keyword density in H1, first 50 words, 2+ H2s, metadata snippets. |
| **Generative Engine Optimization**| π | Direct, quote-ready definitions, structured comparisons for LLM citation. |
| **Content Freshness** | π | Up-to-date benchmarks, recent industry developments, contemporary citations. |
---
## β‘ Speed Generation Profiles
Choose the ideal balance between generation speed and editorial rigor:
- β‘ **Turbo Mode:**
- Parallel specialist analysis with single-pass synthesis.
- Enforces a quality floor of **70+**. Triggers a targeted single-pass polish if any metric is below 70.
- *Best for: Rapid draft generation and fast turnarounds.*
- βοΈ **Balanced Mode:**
- Performs multi-pass iterative optimization until all dimensions reach **80+** or up to 3 refinement passes.
- *Best for: Standard production publishing and content marketing.*
- π¬ **Deep Analysis Mode:**
- Exhaustive multi-agent refinement enforcing a strict **95+** quality floor across all dimensions.
- *Best for: Flagship cornerstone content, authoritative whitepapers, and mission-critical articles.*
---
## πΌοΈ Image Intelligence & Deduplication
- **Binary Content-Hashing:** Downloads images and calculates binary MD5 hashes (`image["content_hash"]`), eliminating duplicate images across CDNs and mirror sites.
- **Exact Count Fulfillment:** If $N$ images are requested, the engine guarantees exactly $N$ distinct images are positioned across relevant sections.
- **Contextual Alignment:** Images are placed immediately after the paragraph discussing the corresponding subject with proper alt text and source attributions.
---
## π οΈ Tech Stack & Frameworks
| Layer | Technologies |
| :--- | :--- |
| **Agent Orchestration** | [LangChain](https://langchain.com/), [LangGraph](https://langchain-ai.github.io/langgraph/) |
| **Inference Engines** | [Groq](https://groq.com/) (Llama-3.3 70B), [Google Gemini](https://deepmind.google/technologies/gemini/) (Gemini 2.5 Flash), [OpenAI](https://openai.com/) (GPT-4o) |
| **Vector Search & RAG** | [Pinecone Serverless](https://www.pinecone.io/), Sentence-Transformers |
| **Web Research & Scraping** | [Tavily AI Search](https://tavily.com/), [Firecrawl](https://www.firecrawl.dev/), BeautifulSoup4, Crawl4AI |
| **Interactive UI** | [Streamlit](https://streamlit.io/), Pandas, Pillow |
| **Document Export** | `python-docx` (Microsoft Word), `reportlab` (Adobe PDF) |
| **Database & State** | SQLite (`database.py`) with Pydantic v2 schemas |
---
## π Project Directory Structure
```
Blog-_Expert/
βββ agents/ # Multi-Agent Domain Implementations
β βββ aggregator.py # Long-form article synthesizer
β βββ evaluator.py # 6-dimension evaluation engine
β βββ facts_agent.py # E-E-A-T & data verifier
β βββ geo_agent.py # Generative engine optimizer
β βββ image_agent.py # Image search, filter & deduplication
β βββ language_agent.py # Tone & readability editor
β βββ learner.py # Intent & keyword extractor
β βββ optimizer.py # Targeted section rewriting engine
β βββ planner.py # Strategic outline architect
β βββ seo_agent.py # Keyword density & snippet analyst
β βββ structure_agent.py # Heading hierarchy specialist
β βββ supervisor.py # Research orchestrator
βββ config/ # Configuration & API Integrations
β βββ config.py # Central settings & credential loading
β βββ firecrawl_manager.py # Web scraping manager
β βββ llm_registry.py # Multi-provider routing (Groq, Gemini, OpenAI)
β βββ nemotron_image_selector.py # Image downloading & vision ranking
β βββ tavily_search.py # Live web search agent
βββ db/ # SQLite Database & State Persistence
β βββ database.py # Run metadata, scores & article storage
β βββ models.py # Data persistence schemas
βββ graph/ # LangGraph State Machine
β βββ graph.py # Graph compilation & node wiring
β βββ router.py # Dynamic speed & quality routers
β βββ state.py # Shared BlogState data model
βββ prompts/ # System Prompts & Rubrics
β βββ aggregator.txt # Full synthesis instructions
β βββ evaluator.txt # Scoring rubrics & guidelines
β βββ images.txt # Image placement rules
β βββ optimizer.txt # Self-refinement instructions
βββ utilis/ # Formatters & Helpers
β βββ exporter.py # DOCX & PDF generation without scores
β βββ image_formatter.py # Markdown image embedding & deduplication
β βββ prompt_loader.py # Safe prompt template loader
β βββ retry.py # Exponential backoff network retry wrapper
β βββ scraper.py # Fast HTTP & Crawl4AI scrapers
βββ streamlit_app.py # Streamlit Web Application
βββ app.py # Minimal CLI invocation entrypoint
βββ requirements.txt # Python dependencies
βββ .env_copy # Environment variable template with portal links
βββ .gitignore # Git ignore specifications
βββ README.md # Comprehensive documentation
```
---
## π Getting Started & Execution Guide
### Prerequisites
- **Python:** 3.10 or higher
- **Package Manager:** `pip`
### Installation
1. **Clone the repository:**
```bash
git clone https://gitea.aiindia.ai/Abhinav_Gupta/Blog-_Expert.git
cd Blog-_Expert
```
2. **Create and activate a virtual environment:**
```bash
# Windows (PowerShell)
python -m venv env
.\env\Scripts\Activate.ps1
# Linux / macOS
python3 -m venv env
source env/bin/activate
```
3. **Install dependencies:**
```bash
pip install --upgrade pip
pip install -r requirements.txt
```
4. *(Optional)* Install Playwright browser binaries for enhanced web scraping:
```bash
playwright install chromium
```
### Environment Configuration
Copy the `.env_copy` template into your local `.env`:
```bash
# Windows
Copy-Item .env_copy .env
# Linux / macOS
cp .env_copy .env
```
Open `.env` and configure your API keys:
| Environment Variable | Provider / Purpose | Portal Link |
| :--- | :--- | :--- |
| `GROQ_API_KEY` | Fast LLM inference (*Llama 3.3 70B*) | [Groq Console](https://console.groq.com/keys) |
| `GEMINI_API_KEY` | High-token writing & embeddings (*Gemini 2.5 Flash*) | [Google AI Studio](https://aistudio.google.com/app/apikey) |
| `OPENAI_API_KEY` | Premium model access (*GPT-4o / GPT-4.1*) | [OpenAI Platform](https://platform.openai.com/api-keys) |
| `TAVILY_API_KEY` | Live web research & fact gathering | [Tavily Search](https://app.tavily.com/) |
| `FIRECRAWL_API_KEY` | Deep web scraping & markdown conversion | [Firecrawl Portal](https://www.firecrawl.dev/) |
| `PINECONE_API_KEY` | Vector database for RAG context storage | [Pinecone Console](https://app.pinecone.io/) |
| `PINECONE_INDEX_NAME` | Pinecone index name (e.g. `blog-enhancer`) | [Pinecone Console](https://app.pinecone.io/) |
| `NEMOTRON_API_KEY` | Multi-modal image analysis & scoring | [OpenRouter Keys](https://openrouter.ai/keys) |
### Running the Application
Launch the interactive Streamlit interface:
```bash
streamlit run streamlit_app.py
```
The application will open automatically at `http://localhost:8501`.
---
## π₯ Export Capabilities
Once generation completes, export your publication-ready article with **1 click**:
- π **Microsoft Word (`.docx`):** Cleanly styled typography with embedded images, headers, callouts, and bullet points.
- π **Adobe PDF (`.pdf`):** Formatted publication document ready for distribution.
- π **Markdown (`.md`):** Portable, GitHub-flavored markdown with clean heading hierarchies and contextual image tags.
> **Note:** Exported files automatically exclude internal debug logs, agent reasoning traces, and evaluator scorecards for clean client delivery.
---
## π History & Failure Diagnostics
- π **Run History Dashboard:** Browse past generation runs, review before-and-after scores, view elapsed execution times, and re-download generated assets at any time.
- π οΈ **Failure Intelligence:** If an API rate limit, invalid URL, or network timeout occurs, Blog Expert provides:
- **Failed Step Indicator:** Pinpoints the exact agent node that failed.
- **Plain-English Explanation:** What went wrong and why.
- **Actionable Fix:** Clear instructions on how to resolve the issue.
- **Traceback View:** Expandable Python stack trace for debugging.
---
## π License & Credits
Developed with β€οΈ by **Abhinav Gupta** at **AI India Innovations**.
Distributed under the MIT License. See `LICENSE` for details.