feat: initial commit for Blog Expert multi-agent system

This commit is contained in:
2026-10-16 11:59:15 +05:30
commit 1f952ded52
79 changed files with 9156 additions and 0 deletions
+124
View File
@@ -0,0 +1,124 @@
# ==============================================================================
# BLOG EXPERT - ENVIRONMENT CONFIGURATION
# ==============================================================================
# Copy this file to `.env` and replace the placeholder values with your actual API keys.
# All links and step-by-step instructions on how to acquire each key are provided below.
# ==============================================================================
# ------------------------------------------------------------------------------
# 1. PRIMARY LLM PROVIDERS (Online Cloud Models)
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# OpenAI API Key
# Portal: https://platform.openai.com/api-keys
# Details:
# 1. Log in or create an OpenAI developer account.
# 2. Go to Dashboard -> API Keys -> "Create new secret key".
# 3. Requires prepaid billing credits for GPT-4o / GPT-4.1 models.
# ------------------------------------------------------------------------------
OPENAI_API_KEY=<your_openai_api_key>
# ------------------------------------------------------------------------------
# Groq API Key (Ultra-fast Cloud Inference - Free Tier Available)
# Portal: https://console.groq.com/keys
# Details:
# 1. Sign up for a free Groq Cloud account.
# 2. Navigate to "API Keys" and click "Create API Key".
# 3. Used for rapid Llama-3.3 and Llama-3.1 specialist reviews & aggregation.
# ------------------------------------------------------------------------------
GROQ_API_KEY=<your_groq_api_key>
# ------------------------------------------------------------------------------
# Google Gemini API Key (High Token Limits - Free Tier Available)
# Portal: https://aistudio.google.com/app/apikey
# Details:
# 1. Open Google AI Studio with your Google Account.
# 2. Click "Create API Key" (choose/create a Google Cloud project).
# 3. Used for Gemini Flash multi-stage writing, reasoning, and embeddings.
# ------------------------------------------------------------------------------
GEMINI_API_KEY=<your_gemini_api_key>
# ------------------------------------------------------------------------------
# 2. VECTOR DATABASE & KNOWLEDGE RETRIEVAL (RAG)
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# Pinecone API Key (Serverless Vector Database - Free Tier Available)
# Portal: https://app.pinecone.io/
# Details:
# 1. Create a free account on Pinecone.
# 2. In the dashboard, click "API Keys" to copy your default key or create one.
# 3. Supports serverless vector search for blog chunk indexing & retrieval.
# ------------------------------------------------------------------------------
PINECONE_API_KEY=<your_pinecone_api_key>
PINECONE_INDEX_NAME=blog-enhancer
# ------------------------------------------------------------------------------
# 3. WEB RESEARCH & SCRAPING AGENTS
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# Tavily Search API Key (AI-Native Live Web & Fact Research)
# Portal: https://app.tavily.com/
# Details:
# 1. Register for a free Tavily account (includes 1,000 free searches/month).
# 2. Copy the API key from your Tavily dashboard.
# 3. Powers live web research, latest facts verification, and image discovery.
# ------------------------------------------------------------------------------
TAVILY_API_KEY=<your_tavily_api_key>
# ------------------------------------------------------------------------------
# Firecrawl API Key (Web Scraping & Clean Markdown Extraction)
# Portal: https://www.firecrawl.dev/
# Details:
# 1. Sign up at Firecrawl.dev (free tier provides 500 scraped pages).
# 2. Generate and copy your API key from the dashboard.
# 3. Used for scraping source URLs, deep crawling, and extracting structured markdown.
# ------------------------------------------------------------------------------
FIRECRAWL_API_KEY=<your_firecrawl_api_key>
# ------------------------------------------------------------------------------
# 4. VISION / MULTI-MODAL & OPENROUTER (Nemotron)
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# OpenRouter / Nemotron API Key (Vision & Multi-modal Image Ranking)
# Portal: https://openrouter.ai/keys
# Details:
# 1. Create an account on OpenRouter.ai.
# 2. Go to "Keys" and generate a new API key.
# 3. Supports open weights models including free Nemotron endpoints.
# ------------------------------------------------------------------------------
NEMOTRON_MODEL=nvidia/nemotron-3-super-120b-a12b:free
NEMOTRON_API_KEY=<your_nemotron_openrouter_api_key>
# ------------------------------------------------------------------------------
# 5. HUGGING FACE TOKEN (Optional Embeddings / Open Models)
# Portal: https://huggingface.co/settings/tokens
# Details:
# 1. Create an account on Hugging Face.
# 2. Go to Settings -> Access Tokens -> "Create New Token" (Type: Read).
# ------------------------------------------------------------------------------
HUGGINGFACEHUB_API_TOKEN=<your_huggingface_api_token>
# ------------------------------------------------------------------------------
# 6. MODEL NAMES & PIPELINE HYPERPARAMETERS
# ------------------------------------------------------------------------------
OPENAI_MODEL=gpt-4.1
EMBEDDING_PROVIDER=gemini
EMBEDDING_MODEL=models/gemini-embedding-001
EMBEDDING_DIMENSION=3072
GROQ_MODEL=llama-3.3-70b-versatile
GEMINI_MODEL=gemini-2.5-flash
# Chunking & Retrieval Parameters
CHUNK_SIZE=1200
CHUNK_OVERLAP=250
TOP_K=8
+96
View File
@@ -0,0 +1,96 @@
# ==============================================================================
# BLOG EXPERT - GIT IGNORE
# ==============================================================================
# ------------------------------------------------------------------------------
# 1. Environment & Secrets
# ------------------------------------------------------------------------------
.env
.env.local
.env.*.local
*.env
# Ensure template is tracked
!.env_copy
!.env.example
# ------------------------------------------------------------------------------
# 2. Python Virtual Environments
# ------------------------------------------------------------------------------
venv/
env/
.venv/
ENV/
env.bak/
venv.bak/
# ------------------------------------------------------------------------------
# 3. Python Bytecode & Cache
# ------------------------------------------------------------------------------
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# ------------------------------------------------------------------------------
# 4. Database & Run Data
# ------------------------------------------------------------------------------
*.db
*.sqlite
*.sqlite3
data/*.db
data/*.sqlite
data/blog_enhancer.db
data/img_cache/
data/custom_images/
generated_images/
thread_dump.txt
*.log
# ------------------------------------------------------------------------------
# 5. IDE & Editor Artifacts
# ------------------------------------------------------------------------------
.vscode/
.idea/
*.sublime-project
*.sublime-workspace
.project
.pydevproject
.settings/
push.bat
# ------------------------------------------------------------------------------
# 6. AI Agent Workspace Caches
# ------------------------------------------------------------------------------
.agents/
.claude/
.memory/
# ------------------------------------------------------------------------------
# 7. Operating System Artifacts
# ------------------------------------------------------------------------------
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
Desktop.ini
+405
View File
@@ -0,0 +1,405 @@
# 🚀 Blog Expert — Multi-Agent AI Blog Generation & Optimization Engine
<div align="center">
[![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-3776AB?style=for-the-badge&logo=python&logoColor=white)](https://www.python.org/)
[![LangChain](https://img.shields.io/badge/LangChain-1C3C3C?style=for-the-badge&logo=chainlink&logoColor=white)](https://langchain.com/)
[![LangGraph](https://img.shields.io/badge/LangGraph-FF6F00?style=for-the-badge&logo=diagram-project&logoColor=white)](https://langchain-ai.github.io/langgraph/)
[![Streamlit](https://img.shields.io/badge/Streamlit-FF4B4B?style=for-the-badge&logo=Streamlit&logoColor=white)](https://streamlit.io/)
[![Groq](https://img.shields.io/badge/Groq-F55036?style=for-the-badge)](https://groq.com/)
[![Google Gemini](https://img.shields.io/badge/Google%20Gemini-8E75C2?style=for-the-badge&logo=google-gemini&logoColor=white)](https://deepmind.google/technologies/gemini/)
[![OpenAI](https://img.shields.io/badge/OpenAI-412991?style=for-the-badge&logo=openai&logoColor=white)](https://openai.com/)
[![Pinecone](https://img.shields.io/badge/Pinecone-000000?style=for-the-badge)](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.**
</div>
---
## 👤 Developer Profile
<div align="center">
| 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) |
</div>
---
## 📑 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.
+66
View File
@@ -0,0 +1,66 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm, stream_invoke
from utilis.prompt_loader import load_prompt
prompt = ChatPromptTemplate.from_messages([
("system", f"{load_prompt('aggregator.txt')}\n\n{load_prompt('images.txt')}"),
("human", (
"Original Blog\n\n{blog}"
"\n\nLanguage Notes\n\n{language}"
"\n\nFacts Notes\n\n{facts}"
"\n\nStructure Notes\n\n{structure}"
"\n\nSEO Notes\n\n{seo}"
"\n\nGEO Notes\n\n{geo}"
"\n\nImages\n\n{images}"
"\n\nDate: {current_date} | Year: {current_year}"
"\n\nQuality: {language_quality} | Length: {target_length}"
)),
])
# Input budget per field (chars). Total input ~10 000 chars = ~2 857 tokens.
# With aggregator.txt (~5 315 chars = ~1 519 tokens) system prompt,
# total input = ~4 376 tokens. Output capped at 3 500 = 7 876 total — under 8K.
_BLOG_CHARS = 3_000 # original blog snippet
_BRIEF_LANG = 800
_BRIEF_FACTS = 1_000
_BRIEF_STRUCT = 1_200 # structure needs room (skeleton + FAQ headings)
_BRIEF_SEO = 1_200 # SEO needs keyword list + H2s
_BRIEF_GEO = 600
_OUTPUT_TOKENS = 4_500 # provides full headroom for 2800-3200 words + FAQs + table
from utilis.tracing import traceable
class AggregatorAgent:
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=_OUTPUT_TOKENS)
inputs = {
"blog": state.blog_snippet(max_chars=_BLOG_CHARS),
"language": state._truncate(state.language_output, _BRIEF_LANG),
"facts": state._truncate(state.facts_output, _BRIEF_FACTS),
"structure": state._truncate(state.structure_output, _BRIEF_STRUCT),
"seo": state._truncate(state.seo_output, _BRIEF_SEO),
"geo": state._truncate(state.geo_output, _BRIEF_GEO),
"images": state.image_output,
"current_date": state.current_date,
"current_year": state.current_year,
"language_quality": state.language_quality,
"target_length": state.target_length,
}
full_text = stream_invoke(prompt, llm, inputs, state.stream_chunk)
from utilis.image_formatter import ensure_exact_images_in_markdown
state.aggregated_blog = ensure_exact_images_in_markdown(full_text, state.image_output)
state.editorial_brief = ""
state.stream_done()
return state
+88
View File
@@ -0,0 +1,88 @@
"""
baseline_evaluator.py
Scores the original scraped blog (state.cleaned_blog) using the same
evaluator rubric before any enhancement is applied.
Runs once, immediately after prepare_blog, and writes to the
baseline_* fields in BlogState so the UI can show a before/after
comparison at the end of the run.
Uses a smaller token budget than the main evaluator (800 tokens) because
the original blog is typically shorter and less structured — less to say.
"""
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from utilis.json_parser import load_json
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("evaluator.txt")),
("human", (
"Target Length\n\n{target_length}"
"\n\nCurrent Date\n\n{current_date}"
"\n\nCurrent Year\n\n{current_year}"
"\n\nLanguage Quality\n\n{language_quality}"
"\n\nArticle\n\n{blog}"
)),
])
# Reduced from 8 000 — original blogs are short, 5 000 chars is enough.
_BASELINE_MAX_CHARS = 5_000
from utilis.tracing import traceable
class BaselineEvaluatorAgent:
def _score(self, result, key):
value = result.get(key) or result.get(f"{key}_score") or result.get(key.title())
if isinstance(value, dict):
value = value.get("score") or value.get("Score") or value.get("value")
return int(value or 0)
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=800, force_groq=True) # baseline = Groq always
response = invoke_with_retry(prompt, llm, {
"blog": state._truncate(state.cleaned_blog, _BASELINE_MAX_CHARS),
"current_date": state.current_date,
"current_year": state.current_year,
"language_quality": state.language_quality,
"target_length": state.target_length,
})
result = load_json(response.content)
def s(key):
return self._score(result, key)
state.baseline_language_score = s("language")
state.baseline_facts_score = s("facts")
state.baseline_structure_score = s("structure")
state.baseline_seo_score = s("seo")
state.baseline_geo_score = s("geo")
state.baseline_freshness_score = s("freshness")
scores = [
state.baseline_language_score,
state.baseline_facts_score,
state.baseline_structure_score,
state.baseline_seo_score,
state.baseline_geo_score,
state.baseline_freshness_score,
]
valid = [sc for sc in scores if sc > 0]
state.baseline_overall_score = round(sum(valid) / len(valid)) if valid else 0
return state
+91
View File
@@ -0,0 +1,91 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from utilis.json_parser import load_json
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("evaluator.txt")),
("human", (
"Target Length\n\n{target_length}"
"\n\nCurrent Date\n\n{current_date}"
"\n\nCurrent Year\n\n{current_year}"
"\n\nLanguage Quality\n\n{language_quality}"
"\n\nArticle\n\n{blog}"
)),
])
# 35 000 chars easily covers a full 3500-word article (~22 000 chars)
# ensuring the evaluator sees the complete text including FAQs, conclusion, and tables.
_EVAL_MAX_CHARS = 35_000
from utilis.tracing import traceable
class EvaluatorAgent:
def _score(self, result, key):
value = result.get(key) or result.get(f"{key}_score") or result.get(key.title())
if isinstance(value, dict):
value = value.get("score") or value.get("Score") or value.get("value")
return int(value or 0)
def _feedback(self, result, key):
value = (
result.get(f"{key}_feedback")
or result.get(f"{key}_notes")
or result.get(f"{key}_review")
or ""
)
if isinstance(value, dict):
value = value.get("feedback") or value.get("Feedback") or ""
return str(value)
def _overall_score(self, state):
scores = [state.language_score, state.facts_score, state.structure_score,
state.seo_score, state.geo_score, state.freshness_score]
valid = [s for s in scores if s > 0]
return round(sum(valid) / len(valid)) if valid else 0
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=1200, force_groq=True) # evaluation = Groq always
blog_to_eval = state._truncate(
state.optimized_blog or state.aggregated_blog,
max_chars=_EVAL_MAX_CHARS,
)
response = invoke_with_retry(prompt, llm, {
"blog": blog_to_eval,
"current_date": state.current_date,
"current_year": state.current_year,
"language_quality": state.language_quality,
"target_length": state.target_length,
})
result = load_json(response.content)
state.language_score = self._score(result, "language")
state.facts_score = self._score(result, "facts")
state.structure_score = self._score(result, "structure")
state.seo_score = self._score(result, "seo")
state.geo_score = self._score(result, "geo")
state.freshness_score = self._score(result, "freshness")
state.overall_score = self._overall_score(state)
state.language_feedback = self._feedback(result, "language")
state.facts_feedback = self._feedback(result, "facts")
state.structure_feedback = self._feedback(result, "structure")
state.seo_feedback = self._feedback(result, "seo")
state.geo_feedback = self._feedback(result, "geo")
state.freshness_feedback = self._feedback(result, "freshness")
state.iteration += 1
return state
+40
View File
@@ -0,0 +1,40 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("facts.txt")),
("human", (
"Blog\n\n{blog}"
"\n\nFacts Research Brief\n\n{facts_research}"
"\n\nCurrent Date\n\n{current_date}"
"\n\nCurrent Year\n\n{current_year}"
"\n\nTarget Length\n\n{target_length}"
)),
])
from utilis.tracing import traceable
class FactsAgent:
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=700, force_groq=True)
result = invoke_with_retry(prompt, llm, {
"blog": state.blog_snippet(max_chars=2500),
"facts_research": state._truncate(state.facts_research, 1000),
"current_date": state.current_date,
"current_year": state.current_year,
"target_length": state.target_length,
})
state.facts_output = result.content
return state
+40
View File
@@ -0,0 +1,40 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("geo.txt")),
("human", (
"SEO Output\n\n{seo}"
"\n\nGEO Research Brief\n\n{geo_research}"
"\n\nCurrent Date\n\n{current_date}"
"\n\nCurrent Year\n\n{current_year}"
"\n\nTarget Length\n\n{target_length}"
)),
])
from utilis.tracing import traceable
class GeoAgent:
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=700, force_groq=True)
response = invoke_with_retry(prompt, llm, {
"seo": state._truncate(state.seo_output, 900),
"geo_research": state._truncate(state.geo_research, 1000),
"current_date": state.current_date,
"current_year": state.current_year,
"target_length":state.target_length,
})
state.geo_output = response.content
return state
+449
View File
@@ -0,0 +1,449 @@
from pathlib import Path
import re
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from config.firecrawl_manager import search_images
from config.nemotron_image_selector import download_image, select_relevant_images
from config.tavily_search import search_image_candidates
# ---------------------------------------------------------------------------
# Terms that indicate images are NOT useful for a professional blog:
# cartoons, comic art, logos without context, generic stock icons, etc.
# If an image URL or alt text contains any of these, reject it.
# ---------------------------------------------------------------------------
_REJECT_PATTERNS = re.compile(
# Entertainment / promotional content
r"netflix|hulu|disney|amazon prime|hbo|peacock|paramount|"
r"movie|film\b|cinema|poster\b|trailer\b|series\b|episode|"
r"actor|actress|celebrity|red.?carpet|billboard\b|"
# Comic / cartoon art
r"clipart|cartoon|comic\b|superhero|avengers|marvel|dc.?comics|"
r"anime|manga|"
# Generic web junk
r"vector|icon\b|logo\b|favicon|banner\b|badge|sticker|"
r"thumbnail|avatar|emoji|smiley|wallpaper|meme|gif\b|"
# Stock photo filler words in the URL path
r"gettyimages|shutterstock|istockphoto|dreamstime|depositphotos",
re.IGNORECASE,
)
# Only accept common photo/diagram image extensions
_ACCEPT_EXTENSIONS = re.compile(r"\.(jpg|jpeg|png|webp)(\?.*)?$", re.IGNORECASE)
from utilis.tracing import traceable
class ImageAgent:
def _search_depth(self, research_level):
return "basic" if str(research_level).lower() in {"easy", "basic"} else "advanced"
def _clean_heading(self, line):
return re.sub(r"^#+\s*", "", line).strip(" :#")
def _topic(self, state) -> str:
"""Extract the core blog topic from the planner or URL for query grounding."""
intent = state.learner_output.get("intent") or ""
topic = state.planner_output.get("research_query") or intent or state.url
# Keep it short — first 80 chars
return str(topic)[:80].strip()
def _context_windows(self, markdown: str, count: int) -> list[dict]:
"""
Split the article into `count` evenly distributed section windows.
Each window carries its heading and the surrounding body text as context
for a highly specific image search.
"""
if count <= 0:
return []
blocks = []
current_heading = ""
current_lines: list[str] = []
for line in markdown.splitlines():
if re.match(r"^#{1,3}\s+", line.strip()):
if current_heading and current_lines:
blocks.append({
"heading": current_heading,
"context": " ".join(current_lines).strip(),
})
current_heading = self._clean_heading(line)
current_lines = []
continue
stripped = line.strip()
if current_heading and stripped and not stripped.startswith("!"):
current_lines.append(stripped)
if current_heading and current_lines:
blocks.append({
"heading": current_heading,
"context": " ".join(current_lines).strip(),
})
# Drop very short blocks and FAQ sections (usually no good image)
blocks = [
b for b in blocks
if len(b["context"]) > 80
and not b["heading"].lower().startswith("faq")
and not b["heading"].lower().startswith("conclusion")
]
if not blocks:
return []
# Distribute `count` windows across blocks or fill with distinct concept slots
if len(blocks) < count:
needed = count - len(blocks)
fallbacks = self._fallback_contexts(state, count)
# Use unique fallbacks not already in blocks
used_headings = {b["heading"].lower() for b in blocks}
for fb in fallbacks:
if fb["heading"].lower() not in used_headings:
blocks.append(fb)
used_headings.add(fb["heading"].lower())
if len(blocks) >= count:
break
step = max(1, len(blocks) // count)
windows = []
for i in range(count):
idx = min(int(i * step), len(blocks) - 1)
b = blocks[idx]
words = str(b.get("context", "")).split()
preceding_100 = " ".join(words[-100:]) if len(words) > 100 else str(b.get("context", ""))
placement = b.get("placement") or f"Place after the paragraph in '{b['heading']}' that discusses this topic."
windows.append({
"heading": b["heading"],
"context": preceding_100,
"placement": placement,
})
return windows
def _fallback_contexts(self, state, count: int) -> list[dict]:
topic = self._topic(state)
slots = [
("Technology Architecture & Workflow", f"{topic} system architecture workflow framework diagram"),
("Industry Data & Growth Trends", f"{topic} market analysis statistics growth chart infographic"),
("Strategic Implementation & Deployment", f"{topic} implementation deployment strategy model"),
("Best Practices & Operational Efficiency", f"{topic} operational workflow optimization best practices"),
("Future Roadmap & Innovations", f"{topic} innovation roadmap future technology landscape"),
]
contexts = []
for i in range(max(count, 1)):
slot_heading, slot_query = slots[i % len(slots)]
heading = f"{slot_heading} Part {i+1}" if i >= len(slots) else slot_heading
contexts.append({
"heading": heading,
"context": f"{topic} — {slot_query}",
"placement": f"Place after the section discussing '{heading}'.",
})
return contexts
def _image_query(self, state, section: dict) -> str:
"""
Build a precise, topic-anchored image search query.
Format: "<blog topic> <section heading> <key context words> photo diagram"
This greatly reduces the chance of returning irrelevant stock/cartoon images.
"""
topic = self._topic(state)
heading = section["heading"]
# Use up to 15 words of section context as additional signal
context_words = " ".join(section["context"].split()[:15])
year = state.current_year
return f"{topic} {heading} {context_words} {year} photo infographic"[:300]
def _filter_candidates(self, candidates: list[dict], section: dict) -> list[dict]:
"""
Remove candidates that are clearly irrelevant or low quality.
Checks both the URL (full path) and alt/caption text.
"""
filtered = []
for c in candidates:
url = (c.get("url") or "").lower()
alt = (c.get("alt") or c.get("caption") or "").lower()
combined = url + " " + alt
# Reject by combined URL + alt pattern
if _REJECT_PATTERNS.search(combined):
continue
# Require a recognised photo extension
if not _ACCEPT_EXTENSIONS.search(url):
continue
filtered.append(c)
return filtered
def _process_custom_images(self, custom_images: list[dict], markdown: str, state) -> list[dict]:
"""
Contextually maps user-supplied custom images into blog sections using
the user's description, caption, and placement hints.
"""
if not custom_images:
return []
# Extract available sections from markdown or fallbacks
sections = self._context_windows(markdown, max(len(custom_images), 4)) or self._fallback_contexts(state, len(custom_images))
processed = []
used_sections = set()
for idx, c_img in enumerate(custom_images):
img_path = c_img.get("image_path") or c_img.get("url") or ""
if not img_path:
continue
img_path = Path(img_path).as_posix()
caption = c_img.get("caption") or ""
desc = c_img.get("description") or ""
hint = c_img.get("placement_hint") or ""
source = c_img.get("source") or "Custom Upload"
# Combine signals to find the best matching section
combined_query = f"{caption} {desc} {hint}".lower().strip()
query_tokens = set(re.findall(r"\w{3,}", combined_query))
best_section = None
best_score = -1
for s in sections:
s_heading = s.get("heading", "")
s_context = s.get("context", "")
s_text = f"{s_heading} {s_context}".lower()
s_tokens = set(re.findall(r"\w{3,}", s_text))
overlap = len(query_tokens & s_tokens)
if s_heading in used_sections:
overlap -= 2
if overlap > best_score:
best_score = overlap
best_section = s
# If no strong match, pick an unused section or round-robin
if not best_section or best_score <= 0:
available = [s for s in sections if s.get("heading") not in used_sections]
best_section = available[0] if available else sections[idx % len(sections)]
heading = best_section.get("heading", f"Section {idx+1}")
used_sections.add(heading)
context = best_section.get("context", desc or "Article body context")
# Formulate explicit placement guidance
if hint:
placement = f"Place in section '{heading}' - Note: {hint}. Context: '{desc or context[-80:]}'."
elif desc:
placement = f"Place immediately after the paragraph in '{heading}' that discusses: '{desc[:100]}'."
else:
placement = best_section.get("placement") or f"Place in section '{heading}'."
processed.append({
"url": img_path,
"local_path": img_path,
"caption": caption or desc or f"Illustration for {heading}",
"alt": caption or desc or f"{heading} image",
"source_url": source,
"context": f"{desc}. Section context: {context[:300]}".strip(),
"placement": placement,
"section": heading,
"is_custom": True,
})
return processed
@traceable
def invoke(self, state):
if getattr(state, "image_output", None):
return state
custom_images = getattr(state, "custom_images", []) or []
source_markdown = state.cleaned_blog
images: list[dict] = []
seen_urls: set[str] = set()
seen_hashes: set[str] = set()
# 1. Process custom images first if provided
if custom_images:
processed_custom = self._process_custom_images(custom_images, source_markdown, state)
for img in processed_custom:
url = img.get("url")
if url:
seen_urls.add(url)
images.append(img)
# Total requested images
target_total = max(0, min(int(state.image_count or 0), 20))
# Ensure at least all custom images are included
target_total = max(target_total, len(images))
if target_total == 0:
state.image_output = []
return state
remaining = target_total - len(images)
# 2. If additional images are needed, fetch automated images
if remaining > 0:
selected_sections = (
self._context_windows(source_markdown, remaining)
or self._fallback_contexts(state, remaining)
)
fallback_sections: list[dict] = []
for section in selected_sections:
query = self._image_query(state, section)
candidates = search_image_candidates(
query,
max_results=12,
search_depth=self._search_depth(state.research_level),
)
candidates = self._filter_candidates(candidates, section)
found = select_relevant_images(
section["context"][:800],
section["heading"],
candidates,
limit=1,
)
# Firecrawl fallback — only use if filter passes
if not found:
firecrawl_candidates = search_images(
query,
limit=3,
context=section["context"][:500],
placement=section["placement"],
)
found = self._filter_candidates(firecrawl_candidates, section)
if found:
found = select_relevant_images(
section["context"][:800],
section["heading"],
found,
limit=1,
)
if not found:
fallback_sections.append(section)
continue
for img in found:
dl = download_image(img, section["heading"])
if not dl:
continue
url = dl.get("url")
chash = dl.get("content_hash")
if not url or url in seen_urls or (chash and chash in seen_hashes):
continue
seen_urls.add(url)
if chash:
seen_hashes.add(chash)
dl.setdefault("context", section["context"])
dl.setdefault("placement", section["placement"])
dl["section"] = section["heading"]
dl["alt"] = dl.get("alt") or f"{section['heading']} — {self._topic(state)}"
dl["caption"] = dl.get("caption") or dl["alt"]
dl["source_url"] = dl.get("source_url") or dl.get("remote_url") or url
images.append(dl)
if len(images) >= target_total:
break
if len(images) >= target_total:
break
# Second pass for fallback sections if still below target
if len(images) < target_total:
for section in fallback_sections:
if len(images) >= target_total:
break
query = self._image_query(state, section)
candidates = self._filter_candidates(
search_image_candidates(query, max_results=10,
search_depth=self._search_depth(state.research_level)),
section,
)
found = select_relevant_images(
section["context"][:800], section["heading"], candidates, limit=1
)
if not found:
firecrawl_candidates = self._filter_candidates(
search_images(query, limit=3,
context=section["context"][:500],
placement=section["placement"]),
section,
)
found = select_relevant_images(
section["context"][:800], section["heading"],
firecrawl_candidates, limit=1,
) if firecrawl_candidates else []
found = self._filter_candidates(found or [], section)
for img in found:
dl = download_image(img, section["heading"])
if not dl:
continue
url = dl.get("url")
chash = dl.get("content_hash")
if not url or url in seen_urls or (chash and chash in seen_hashes):
continue
seen_urls.add(url)
if chash:
seen_hashes.add(chash)
dl.setdefault("context", section["context"])
dl.setdefault("placement", section["placement"])
dl["section"] = section["heading"]
dl["source_url"] = dl.get("source_url") or dl.get("remote_url") or url
images.append(dl)
if len(images) >= target_total:
break
# 3. Third pass: broad topic search if still below target
if len(images) < target_total:
topic = self._topic(state)
broad_queries = [
f"{topic} infographic chart {state.current_year}",
f"{topic} technology architecture framework diagram",
f"{topic} market analysis statistics trends",
f"{topic} enterprise workflow implementation roadmap",
f"{topic} executive strategy guide",
]
for bq in broad_queries:
if len(images) >= target_total:
break
cands = self._filter_candidates(
search_image_candidates(bq, max_results=8, search_depth=self._search_depth(state.research_level)),
{"heading": "Key Analysis", "context": topic}
)
for c in cands:
dl = download_image(c, "Overview")
if not dl:
continue
url = dl.get("url")
chash = dl.get("content_hash")
if not url or url in seen_urls or (chash and chash in seen_hashes):
continue
seen_urls.add(url)
if chash:
seen_hashes.add(chash)
dl.setdefault("context", f"Comprehensive analysis for {topic}")
dl.setdefault("placement", f"Place in the section illustrating {topic}.")
dl["section"] = "Key Insights"
dl["source_url"] = dl.get("source_url") or dl.get("remote_url") or url
images.append(dl)
if len(images) >= target_total:
break
state.image_output = images[:target_total]
return state
+38
View File
@@ -0,0 +1,38 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("language.txt")),
("human", (
"Blog\n\n{blog}"
"\n\nLanguage Research Brief\n\n{language_research}"
"\n\nLanguage Quality\n\n{language_quality}"
"\n\nTarget Length\n\n{target_length}"
)),
])
from utilis.tracing import traceable
class LanguageAgent:
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=700, force_groq=True)
response = invoke_with_retry(prompt, llm, {
"blog": state.blog_snippet(max_chars=2500),
"language_research": state._truncate(state.language_research, 800),
"language_quality": state.language_quality,
"target_length": state.target_length,
})
state.language_output = response.content
return state
+33
View File
@@ -0,0 +1,33 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from graph.state import BlogState
from utilis.json_parser import load_json
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("learner.txt")),
("human", "Target Length\n\n{target_length}\n\nBlog\n\n{blog}"),
])
from utilis.tracing import traceable
class LearnerAgent:
@traceable
def invoke(self, state: BlogState):
llm = make_llm(max_tokens=600, force_groq=True)
response = invoke_with_retry(prompt, llm, {
"blog": state.blog_snippet(max_chars=2500),
"target_length": state.target_length,
})
state.learner_output = load_json(response.content)
return state
+81
View File
@@ -0,0 +1,81 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm, stream_invoke
from utilis.prompt_loader import load_prompt
prompt = ChatPromptTemplate.from_messages([
("system", f"{load_prompt('optimizer.txt')}\n\n{load_prompt('images.txt')}"),
("human", (
"Article Draft\n\n{current_draft}"
"\n\nEvaluator Fix Instructions"
"\nLanguage ({language_score}/100): {language_feedback}"
"\nFacts ({facts_score}/100): {facts_feedback}"
"\nStructure ({structure_score}/100): {structure_feedback}"
"\nSEO ({seo_score}/100): {seo_feedback}"
"\nGEO ({geo_score}/100): {geo_feedback}"
"\nFreshness ({freshness_score}/100): {freshness_feedback}"
"\n\nTargeted Research\n\n{targeted_research}"
"\n\nImage Recommendations\n\n{images}"
"\n\nCurrent Date\n\n{current_date}"
"\n\nCurrent Year\n\n{current_year}"
"\n\nLanguage Quality\n\n{language_quality}"
"\n\nTarget Length\n\n{target_length}"
)),
])
from utilis.tracing import traceable
class OptimizerAgent:
_DRAFT_MAX_CHARS = 25_000 # full draft context for complete rewrite
_FEEDBACK_MAX_CHARS = 1_200 # rich feedback from evaluator
_OUTPUT_TOKENS = 4_500 # full output headroom for complete 2800-word article
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=self._OUTPUT_TOKENS)
current_draft = state._truncate(
state.optimized_blog or state.aggregated_blog,
max_chars=self._DRAFT_MAX_CHARS,
)
state.optimizer_iteration += 1
def _fb(text: str) -> str:
return state._truncate(text, self._FEEDBACK_MAX_CHARS) if text else "Passing."
inputs = {
"current_draft": current_draft,
"language_score": state.language_score,
"language_feedback": _fb(state.language_feedback),
"facts_score": state.facts_score,
"facts_feedback": _fb(state.facts_feedback),
"structure_score": state.structure_score,
"structure_feedback": _fb(state.structure_feedback),
"seo_score": state.seo_score,
"seo_feedback": _fb(state.seo_feedback),
"geo_score": state.geo_score,
"geo_feedback": _fb(state.geo_feedback),
"freshness_score": state.freshness_score,
"freshness_feedback": _fb(state.freshness_feedback),
"targeted_research": state._truncate(
state.targeted_research_output, 1200
) if state.targeted_research_output else "None.",
"images": state.image_output,
"current_date": state.current_date,
"current_year": state.current_year,
"language_quality": state.language_quality,
"target_length": state.target_length,
}
full_text = stream_invoke(prompt, llm, inputs, state.stream_chunk)
from utilis.image_formatter import ensure_exact_images_in_markdown
state.optimized_blog = ensure_exact_images_in_markdown(full_text, state.image_output)
state.stream_done()
return state
+62
View File
@@ -0,0 +1,62 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from utilis.json_parser import load_json
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("planner.txt")),
("human", "Article\n\n{blog}\n\nLearner\n\n{learner}\n\nCurrent Date\n\n{current_date}\n\nCurrent Year\n\n{current_year}\n\nTarget Length\n\n{target_length}"),
])
from utilis.tracing import traceable
class PlannerAgent:
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=600, force_groq=True)
if getattr(state, "mode", "enhance") == "generate":
gen_prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("planner.txt")),
("human", "Topic\n\n{topic}\n\nGuidelines & Important Info\n\n{other_info}\n\nCurrent Date\n\n{current_date}\n\nCurrent Year\n\n{current_year}\n\nTarget Length\n\n{target_length}"),
])
response = invoke_with_retry(gen_prompt, llm, {
"topic": state.title or state.topic_idea,
"other_info": state.other_info,
"current_date": state.current_date,
"current_year": state.current_year,
"target_length": state.target_length,
})
else:
response = invoke_with_retry(prompt, llm, {
"blog": state.blog_snippet(max_chars=2500),
"learner": state.learner_output,
"current_date": state.current_date,
"current_year": state.current_year,
"target_length": state.target_length,
})
output = load_json(response.content)
if "research_query" not in output or not output["research_query"]:
output["research_query"] = (
output.get("researchQuery")
or output.get("research_queries")
or output.get("query")
or (state.planner_output.get("research_query") if isinstance(state.planner_output, dict) else "")
or f"{state.title or state.url} {state.current_year} latest statistics examples SEO GEO keywords"
)
if isinstance(output["research_query"], list):
output["research_query"] = " ".join(output["research_query"])
state.planner_output = output
return state
+42
View File
@@ -0,0 +1,42 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from utilis.json_parser import load_json
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
from utilis.tracing import traceable
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("prompt_generator.txt")),
("human", "Topic Idea: {topic_idea}\n\nGuidelines & Other Info: {other_info}"),
])
class PromptGeneratorAgent:
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=500, force_groq=True)
response = invoke_with_retry(prompt, llm, {
"topic_idea": state.topic_idea,
"other_info": state.other_info,
})
output = load_json(response.content)
state.title = output.get("optimized_topic") or state.topic_idea
state.research_output = ""
state.planner_output = {
"research_query": output.get("research_prompt") or state.topic_idea,
"primary_keyword": state.topic_idea,
"h1_title": state.title,
"h2_headings": [],
"faq_questions": [],
"secondary_keywords": [],
"target_outline": []
}
return state
+110
View File
@@ -0,0 +1,110 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from config.tavily_search import search
from graph.state import BlogState
from utilis.prompt_loader import load_prompt
from utilis.research_cache import get_researcher_cache
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("researcher.txt")),
("human", (
"Search Results\n\n{research}"
"\n\nSEO Signals from Planner\n\n{seo_signals}"
"\n\nCurrent Date\n\n{current_date}"
"\n\nCurrent Year\n\n{current_year}"
"\n\nTarget Length\n\n{target_length}"
"\n\nResearch Level\n\n{research_level}"
)),
])
from utilis.tracing import traceable
class ResearchAgent:
_MAX_RESULT_CHARS = 400
_MAX_TOTAL_CHARS = 3500
def _research_settings(self, level):
return {
"easy": {"max_results": 3, "search_depth": "basic"},
"basic": {"max_results": 3, "search_depth": "basic"},
"medium": {"max_results": 5, "search_depth": "advanced"},
"advanced": {"max_results": 8, "search_depth": "advanced"},
}.get(str(level).lower(), {"max_results": 5, "search_depth": "advanced"})
def _trim_results(self, results) -> str:
items = results.get("results", []) if isinstance(results, dict) else (results if isinstance(results, list) else [])
lines = []
for item in items:
content = item.get("content", "")
if len(content) > self._MAX_RESULT_CHARS:
content = content[:self._MAX_RESULT_CHARS].rsplit(" ", 1)[0] + "…"
lines.append(f"- {item.get('title', '')}\n {item.get('url', '')}\n {content}")
combined = "\n\n".join(lines)
if len(combined) > self._MAX_TOTAL_CHARS:
combined = combined[:self._MAX_TOTAL_CHARS].rsplit("\n", 1)[0] + "\n…[truncated]"
return combined
def _seo_signals(self, state: BlogState) -> str:
"""Extract keyword/heading signals from the planner so the researcher
reinforces them in the brief rather than inventing its own."""
p = state.planner_output
if not p:
return ""
lines = []
kw = p.get("primary_keyword", "")
if kw:
lines.append(f"Primary keyword: {kw}")
h1 = p.get("h1_title", "")
if h1:
lines.append(f"H1: {h1}")
h2s = p.get("h2_headings", [])
if h2s:
lines.append(f"H2 headings: {' | '.join(h2s[:6])}")
faqs = p.get("faq_questions", [])
if faqs:
lines.append(f"FAQ questions: {' | '.join(faqs[:6])}")
sec = p.get("secondary_keywords", [])
if sec:
lines.append(f"Secondary keywords: {', '.join(sec[:10])}")
return "\n".join(lines)
@traceable
def invoke(self, state: BlogState):
query = (
state.planner_output.get("research_query")
or f"{state.url} {state.current_year} latest statistics examples SEO GEO keywords"
)
if isinstance(query, list):
query = " ".join(query)
query = f"{query} {state.current_year}"
cache = get_researcher_cache()
cached = cache.get(query)
if cached:
state.research_output = cached
return state
results = search(query, **self._research_settings(state.research_level))
llm = make_llm(max_tokens=2000)
response = invoke_with_retry(prompt, llm, {
"research": self._trim_results(results),
"seo_signals": self._seo_signals(state),
"current_date": state.current_date,
"current_year": state.current_year,
"target_length": state.target_length,
"research_level": state.research_level,
})
state.research_output = response.content
cache.set(query, state.research_output)
return state
+40
View File
@@ -0,0 +1,40 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("seo.txt")),
("human", (
"Blog\n\n{blog}"
"\n\nSEO Research Brief\n\n{seo_research}"
"\n\nCurrent Date\n\n{current_date}"
"\n\nCurrent Year\n\n{current_year}"
"\n\nTarget Length\n\n{target_length}"
)),
])
from utilis.tracing import traceable
class SeoAgent:
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=700, force_groq=True)
response = invoke_with_retry(prompt, llm, {
"blog": state.blog_snippet(max_chars=2500),
"seo_research": state._truncate(state.seo_research, 1200),
"current_date": state.current_date,
"current_year": state.current_year,
"target_length":state.target_length,
})
state.seo_output = response.content
return state
+40
View File
@@ -0,0 +1,40 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from utilis.prompt_loader import load_prompt
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("structure.txt")),
("human", (
"Blog\n\n{blog}"
"\n\nStructure Research Brief\n\n{structure_research}"
"\n\nTarget Length\n\n{target_length}"
)),
])
from utilis.tracing import traceable
class StructureAgent:
@traceable
def invoke(self, state):
llm = make_llm(max_tokens=700, force_groq=True)
# The supervisor's structure_brief already contains the full article
# skeleton (H1, H2s, FAQ questions, paragraph topics) aligned to the
# SEO plan — pass it in full so the structure agent refines rather
# than rebuilds from scratch.
response = invoke_with_retry(prompt, llm, {
"blog": state.blog_snippet(max_chars=2500),
"structure_research":state._truncate(state.structure_research, 1200),
"target_length": state.target_length,
})
state.structure_output = response.content
return state
+159
View File
@@ -0,0 +1,159 @@
"""
supervisor.py — Research Supervisor Agent
Replaces the single ResearchAgent. One Tavily search call,
one LLM call → five focused research briefs, one per specialist:
language_brief → state.language_research
facts_brief → state.facts_research
structure_brief → state.structure_research
seo_brief → state.seo_research
geo_brief → state.geo_research
Each specialist agent then reads its own dedicated brief instead
of having to extract relevant pieces from a shared generic document.
Also writes state.research_output with the raw search results summary
so targeted_researcher and any legacy code still works.
"""
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from config.tavily_search import search
from graph.state import BlogState
from utilis.json_parser import load_json
from utilis.prompt_loader import load_prompt
from utilis.research_cache import get_researcher_cache
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("supervisor.txt")),
("human", (
"Search Results\n\n{search_results}"
"\n\nContent Plan\n\n{plan_summary}"
"\n\nPrimary Keyword: {primary_keyword}"
"\n\nH1 Title: {h1_title}"
"\n\nH2 Headings: {h2_headings}"
"\n\nFAQ Questions: {faq_questions}"
"\n\nSecondary Keywords: {secondary_keywords}"
"\n\nCurrent Date: {current_date}"
"\n\nCurrent Year: {current_year}"
"\n\nTarget Length: {target_length}"
)),
])
_MAX_RESULT_CHARS = 400
_MAX_TOTAL_CHARS = 4000 # slightly larger than old researcher — supervisor uses the full budget
def _trim_results(results) -> str:
items = (
results.get("results", []) if isinstance(results, dict)
else results if isinstance(results, list)
else []
)
lines = []
for item in items:
content = item.get("content", "")
if len(content) > _MAX_RESULT_CHARS:
content = content[:_MAX_RESULT_CHARS].rsplit(" ", 1)[0] + "…"
lines.append(f"- {item.get('title', '')}\n {item.get('url', '')}\n {content}")
combined = "\n\n".join(lines)
if len(combined) > _MAX_TOTAL_CHARS:
combined = combined[:_MAX_TOTAL_CHARS].rsplit("\n", 1)[0] + "\n…[truncated]"
return combined
def _research_settings(level: str, results_override: int = 0) -> dict:
defaults = {
"easy": {"max_results": 3, "search_depth": "basic"},
"basic": {"max_results": 3, "search_depth": "basic"},
"medium": {"max_results": 5, "search_depth": "advanced"},
"advanced": {"max_results": 8, "search_depth": "advanced"},
}.get(str(level).lower(), {"max_results": 5, "search_depth": "advanced"})
# UI slider overrides the count but keeps the depth appropriate for the level
if results_override > 0:
defaults["max_results"] = results_override
return defaults
def _seo_fields(state: BlogState) -> dict:
"""Pull the keyword plan from planner_output into flat strings."""
p = state.planner_output
return {
"primary_keyword": p.get("primary_keyword", ""),
"h1_title": p.get("h1_title", ""),
"h2_headings": " | ".join(p.get("h2_headings", [])[:6]),
"faq_questions": " | ".join(p.get("faq_questions", [])[:6]),
"secondary_keywords":", ".join(p.get("secondary_keywords", [])[:10]),
}
from utilis.tracing import traceable
class SupervisorAgent:
@traceable
def invoke(self, state: BlogState) -> BlogState:
query = (
state.planner_output.get("research_query")
or f"{state.url} {state.current_year} latest statistics examples"
)
if isinstance(query, list):
query = " ".join(query)
query = f"{query} {state.current_year}"
# Cache check — skip search + LLM if a similar query was seen recently
cache = get_researcher_cache()
cached_json = cache.get(query)
if cached_json:
briefs = load_json(cached_json) if isinstance(cached_json, str) else cached_json
self._apply_briefs(state, briefs, cached_json if isinstance(cached_json, str) else "")
return state
raw_results = search(query, **_research_settings(state.research_level, state.research_results))
trimmed = _trim_results(raw_results)
# Keep a raw summary in research_output for targeted_researcher
state.research_output = trimmed
llm = make_llm(max_tokens=2000, force_groq=True) # supervisor = Groq (research synthesis)
seo = _seo_fields(state)
response = invoke_with_retry(prompt, llm, {
"search_results": trimmed,
"plan_summary": state.plan_summary(),
"primary_keyword": seo["primary_keyword"],
"h1_title": seo["h1_title"],
"h2_headings": seo["h2_headings"],
"faq_questions": seo["faq_questions"],
"secondary_keywords":seo["secondary_keywords"],
"current_date": state.current_date,
"current_year": state.current_year,
"target_length": state.target_length,
})
raw_output = response.content
briefs = load_json(raw_output)
cache.set(query, raw_output)
self._apply_briefs(state, briefs, raw_output)
return state
def _apply_briefs(self, state: BlogState, briefs: dict, raw: str) -> None:
"""Write each brief into its dedicated state field with a safe fallback."""
state.language_research = briefs.get("language_brief", raw)
state.facts_research = briefs.get("facts_brief", raw)
state.structure_research = briefs.get("structure_brief", raw)
state.seo_research = briefs.get("seo_brief", raw)
state.geo_research = briefs.get("geo_brief", raw)
# Also keep the raw content in research_output for backward compatibility
if not state.research_output:
state.research_output = raw
+172
View File
@@ -0,0 +1,172 @@
"""
targeted_researcher.py
Runs targeted web research for dimensions that scored below 70 after the
optimizer pass. Builds a per-dimension query, searches via Tavily, then
synthesises the results into a structured markdown brief that is stored in
state.targeted_research_output.
The optimizer will pick this up on its next pass and use it to fix the
specific failing sections.
"""
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.prompts import ChatPromptTemplate
from config.llm_registry import make_llm
from config.tavily_search import search
from graph.state import BlogState
from utilis.prompt_loader import load_prompt
from utilis.research_cache import get_targeted_cache
from utilis.retry import invoke_with_retry
prompt = ChatPromptTemplate.from_messages([
("system", load_prompt("targeted_researcher.txt")),
("human", (
"Search Results\n\n{search_results}"
)),
])
# Maps each dimension to a search query suffix that targets the exact gap
_DIMENSION_QUERY_SUFFIX = {
"language": "writing style examples tone engaging prose blog",
"facts": "latest statistics data named examples case studies verified sources",
"structure": "blog structure outline FAQ headings word count best practices",
"seo": "primary keywords LSI keywords search intent FAQ questions SEO",
"geo": "named entities definitions direct answers authoritative statements",
"freshness": f"latest current statistics trends updated data",
}
SCORE_THRESHOLD = 70
def _get_failing_dimensions(state: BlogState) -> list[tuple[str, int, str]]:
"""
Returns a list of (dimension_name, score, feedback) tuples
for every dimension that scored below SCORE_THRESHOLD.
"""
candidates = [
("language", state.language_score, state.language_feedback),
("facts", state.facts_score, state.facts_feedback),
("structure", state.structure_score, state.structure_feedback),
("seo", state.seo_score, state.seo_feedback),
("geo", state.geo_score, state.geo_feedback),
("freshness", state.freshness_score, state.freshness_feedback),
]
return [(name, score, fb) for name, score, fb in candidates if score < SCORE_THRESHOLD]
def _build_failing_brief(failing: list[tuple[str, int, str]]) -> str:
"""Formats the failing dimension info for the prompt."""
lines = []
for name, score, feedback in failing:
lines.append(f"### {name.upper()} (score: {score}/100)")
lines.append(f"Evaluator feedback: {feedback or 'No specific feedback provided.'}")
lines.append("")
return "\n".join(lines)
def _build_search_query(failing: list[tuple[str, int, str]], url: str, year: int) -> str:
"""
Builds a combined Tavily search query that covers all failing dimensions.
Pulls the topic from the URL slug and appends dimension-specific suffixes.
"""
# Extract a readable topic from the URL
slug = url.rstrip("/").split("/")[-1].replace("-", " ").replace("_", " ")
topic = slug if slug else url
suffixes = [_DIMENSION_QUERY_SUFFIX.get(name, "") for name, _, _ in failing]
combined_suffix = " ".join(dict.fromkeys(s for s in suffixes if s)) # deduplicate
return f"{topic} {combined_suffix} {year} latest"
from utilis.tracing import traceable
class TargetedResearchAgent:
_MAX_RESULT_CHARS = 400
_MAX_TOTAL_CHARS = 3500
def _research_settings(self, level: str) -> dict:
settings = {
"easy": {"max_results": 3, "search_depth": "basic"},
"basic": {"max_results": 3, "search_depth": "basic"},
"medium": {"max_results": 5, "search_depth": "advanced"},
"advanced": {"max_results": 8, "search_depth": "advanced"},
}
return settings.get(str(level).lower(), settings["medium"])
def _trim_results(self, results) -> str:
if isinstance(results, dict):
items = results.get("results", [])
elif isinstance(results, list):
items = results
else:
return str(results)[:self._MAX_TOTAL_CHARS]
lines = []
for item in items:
title = item.get("title", "")
url = item.get("url", "")
content = item.get("content", "")
if len(content) > self._MAX_RESULT_CHARS:
content = content[:self._MAX_RESULT_CHARS].rsplit(" ", 1)[0] + "…"
lines.append(f"- {title}\n {url}\n {content}")
combined = "\n\n".join(lines)
if len(combined) > self._MAX_TOTAL_CHARS:
combined = combined[:self._MAX_TOTAL_CHARS].rsplit("\n", 1)[0] + "\n…[truncated]"
return combined
@traceable
def invoke(self, state: BlogState) -> BlogState:
failing = _get_failing_dimensions(state)
if not failing:
# Nothing to do — scores all ≥ threshold, router shouldn't have
# sent us here, but be safe.
return state
failing_names = [name for name, _, _ in failing]
failing_brief = _build_failing_brief(failing)
query = _build_search_query(failing, state.url, state.current_year)
# ── Cache check ──────────────────────────────────────────────────────
cache = get_targeted_cache()
cached = cache.get(query)
if cached:
state.targeted_research_output = (
f"## Targeted Research for: {', '.join(failing_names)}\n\n"
+ cached
)
return state
# Run the search
search_results = search(query, **self._research_settings(state.research_level))
# Synthesise targeted research brief via LLM
llm = make_llm(size="medium", force_groq=True) # targeted research = Groq always
response = invoke_with_retry(prompt, llm, {
"failing_dimensions_brief": failing_brief,
"url": state.url,
"current_date": state.current_date,
"current_year": state.current_year,
"search_results": self._trim_results(search_results),
})
result_text = response.content
cache.set(query, result_text)
# Store in dedicated field so it doesn't overwrite the original research
state.targeted_research_output = (
f"## Targeted Research for: {', '.join(failing_names)}\n\n"
+ result_text
)
return state
+19
View File
@@ -0,0 +1,19 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from graph.graph import graph
from graph.state import BlogState
state = BlogState(
url="https://aiindia.ai/corporate-ai-trainings/"
)
result = BlogState(**graph.invoke(state))
print(result.optimized_blog)
+51
View File
@@ -0,0 +1,51 @@
import sys
sys.path.insert(0, ".")
modules = [
("google.api_core", "google-api-core"),
("google.generativeai", "google-generativeai"),
("google.genai", "google-genai"),
("langchain_google_genai", "langchain-google-genai"),
("langchain_huggingface", "langchain-huggingface"),
("langchain_pinecone", "langchain-pinecone"),
("langchain_openai", "langchain-openai"),
("langchain_groq", "langchain-groq"),
("langchain_community", "langchain-community"),
("pinecone", "pinecone"),
("tavily", "tavily-python"),
("firecrawl", "firecrawl-py"),
("crawl4ai", "crawl4ai"),
("playwright", "playwright"),
("sentence_transformers", "sentence-transformers"),
("openai", "openai"),
("groq", "groq"),
("markdownify", "markdownify"),
("bs4", "beautifulsoup4"),
("lxml", "lxml"),
("requests", "requests"),
("dotenv", "python-dotenv"),
("pandas", "pandas"),
("PIL", "Pillow"),
("httpx", "httpx"),
("langsmith", "langsmith"),
("docx", "python-docx"),
("reportlab", "reportlab"),
]
missing = []
ok = []
for mod, pkg in modules:
try:
__import__(mod)
ok.append(pkg)
except ImportError:
missing.append((mod, pkg))
print(f"OK ({len(ok)}/{len(modules)}):", ", ".join(ok))
print()
if missing:
print(f"MISSING ({len(missing)}):")
for mod, pkg in missing:
print(f" pip install {pkg} # import {mod}")
else:
print("All packages present.")
+1
View File
@@ -0,0 +1 @@
from .config import settings, Settings
+110
View File
@@ -0,0 +1,110 @@
from pathlib import Path
from dotenv import load_dotenv, find_dotenv
import os
BASE_DIR = Path(__file__).resolve().parent.parent
ENV_PATH = BASE_DIR / ".env"
if not ENV_PATH.exists():
found = find_dotenv()
if found:
ENV_PATH = Path(found)
load_dotenv(ENV_PATH, override=True)
def _get_env(*names, default=None):
load_dotenv(ENV_PATH, override=True)
for name in names:
value = os.getenv(name)
if value is not None and value != "":
val = str(value).strip().strip('"').strip("'")
if val.startswith("-") and not val.startswith("-sk-"):
val = val.lstrip("-")
return val
try:
if ENV_PATH.exists():
with open(ENV_PATH, "r", encoding="utf-8") as env_file:
for line in env_file:
if "=" not in line:
continue
key, value = line.split("=", 1)
if key.strip() in names:
val = value.strip().strip('"').strip("'")
if val.startswith("-") and not val.startswith("-sk-"):
val = val.lstrip("-")
return val
except OSError:
pass
return default
class Settings:
@property
def GROQ_API_KEY(self):
return _get_env("GROQ_API_KEY")
@property
def OPENAI_API_KEY(self):
return _get_env("OPENAI_API_KEY")
@property
def PINECONE_API_KEY(self):
return _get_env("PINECONE_API_KEY")
@property
def PINECONE_INDEX_NAME(self):
return _get_env("PINECONE_INDEX_NAME")
@property
def TAVILY_API_KEY(self):
return _get_env("TAVILY_API_KEY")
@property
def FIRECRAWL_API_KEY(self):
return _get_env("FIRECRAWL_API_KEY")
@property
def NEMOTRON_MODEL(self):
return _get_env("NEMOTRON_MODEL", default="NEMOTRON MODEL")
@property
def NEMOTRON_API_KEY(self):
return _get_env("NEMOTRON_API_KEY")
@property
def NEMOTRON_BASE_URL(self):
return _get_env("NEMOTRON_BASE_URL", default="https://openrouter.ai/api/v1")
MODEL = _get_env("GROQ_MODEL", "MODEL", default="llama-3.1-8b-instant")
OPENAI_MODEL = _get_env("OPENAI_MODEL", default="gpt-4o")
GEMINI_API_KEY = _get_env("GEMINI_API_KEY")
GEMINI_MODEL = _get_env("GEMINI_MODEL", default="gemini-3.5-flash-lite")
EMBEDDING_MODEL = _get_env(
"EMBEDDING_MODEL",
default="sentence-transformers/all-MiniLM-L6-v2",
)
# EMBEDDING_PROVIDER controls which embedding backend is used.
# Supported values: "openai" | "gemini" | "huggingface"
# Default: auto-detected from EMBEDDING_MODEL name.
EMBEDDING_PROVIDER = _get_env("EMBEDDING_PROVIDER", default="auto")
EMBEDDING_DIMENSION = int(_get_env("EMBEDDING_DIMENSION", default="384"))
CHUNK_SIZE = int(_get_env("CHUNK_SIZE", default="1000"))
CHUNK_OVERLAP = int(_get_env("CHUNK_OVERLAP", default="200"))
TOP_K = int(_get_env("TOP_K", default="5"))
settings = Settings()
+125
View File
@@ -0,0 +1,125 @@
"""
embeddings.py — unified embedding provider routing.
Supported providers (set EMBEDDING_PROVIDER in .env):
openai — OpenAI text-embedding-3-large / text-embedding-3-small / ada-002
Requires: OPENAI_API_KEY
Dimensions: 3072 (3-large), 1536 (3-small / ada-002)
gemini — Google text-embedding-004 (free tier, no credit card)
Requires: GEMINI_API_KEY
Dimensions: 768
Free limits: 1500 RPD, 100 RPM
huggingface — Local sentence-transformers (no API key, runs on CPU)
Default model: sentence-transformers/all-MiniLM-L6-v2
Dimensions: 384
Cost: free, but slower on first run (downloads model)
EMBEDDING_PROVIDER=auto (default):
Detects from EMBEDDING_MODEL name:
text-embedding-* → openai
models/text-embedding-* or gemini-embedding-* → gemini
anything else → huggingface
IMPORTANT — Pinecone index dimension must match:
If you change provider/model, the existing Pinecone index must be
recreated with the correct dimension. The system auto-recreates it
if the dimension doesn't match.
Recommended .env for each provider:
# OpenAI (paid)
EMBEDDING_PROVIDER=openai
EMBEDDING_MODEL=text-embedding-3-large
EMBEDDING_DIMENSION=3072
# Gemini (free)
EMBEDDING_PROVIDER=gemini
EMBEDDING_MODEL=models/text-embedding-004
EMBEDDING_DIMENSION=768
# HuggingFace (free, local)
EMBEDDING_PROVIDER=huggingface
EMBEDDING_MODEL=sentence-transformers/all-MiniLM-L6-v2
EMBEDDING_DIMENSION=384
"""
from __future__ import annotations
from config import settings
# ── Provider auto-detection ───────────────────────────────────────────────────
_OPENAI_MODELS = {
"text-embedding-3-large",
"text-embedding-3-small",
"text-embedding-ada-002",
}
_GEMINI_MODELS = {
"models/gemini-embedding-001",
"models/gemini-embedding-2-preview",
"models/gemini-embedding-2",
"gemini-embedding-001",
"gemini-embedding-2-preview",
"gemini-embedding-2",
# Legacy v1beta names (no longer valid but kept for detection)
"models/text-embedding-004",
"text-embedding-004",
"gemini-embedding-exp-03-07",
}
def _detect_provider(model: str) -> str:
"""Infer provider from model name when EMBEDDING_PROVIDER=auto."""
m = model.lower()
if m in {x.lower() for x in _OPENAI_MODELS} or m.startswith("text-embedding-3") or m == "text-embedding-ada-002":
return "openai"
if (m in {x.lower() for x in _GEMINI_MODELS}
or "gemini-embedding" in m
or m.startswith("models/gemini")):
return "gemini"
return "huggingface"
_raw_provider = (settings.EMBEDDING_PROVIDER or "auto").strip().lower()
_model = settings.EMBEDDING_MODEL or "sentence-transformers/all-MiniLM-L6-v2"
if _raw_provider == "auto":
_provider = _detect_provider(_model)
else:
_provider = _raw_provider
# ── Build the embeddings object ───────────────────────────────────────────────
if _provider == "openai":
if not getattr(settings, "OPENAI_API_KEY", None):
raise ValueError(
"EMBEDDING_PROVIDER=openai requires OPENAI_API_KEY in .env. "
"Switch to EMBEDDING_PROVIDER=gemini or huggingface to avoid this."
)
import os
from langchain_openai import OpenAIEmbeddings
os.environ["OPENAI_API_KEY"] = settings.OPENAI_API_KEY
embeddings = OpenAIEmbeddings(
model=_model,
openai_api_key=settings.OPENAI_API_KEY,
)
elif _provider == "gemini":
if not getattr(settings, "GEMINI_API_KEY", None):
raise ValueError(
"EMBEDDING_PROVIDER=gemini requires GEMINI_API_KEY in .env. "
"Get a free key at https://aistudio.google.com/app/apikey"
)
from langchain_google_genai import GoogleGenerativeAIEmbeddings
# Ensure the model has the models/ prefix — required by the API
_gem_model = _model if _model.startswith("models/") else f"models/{_model.split('/')[-1]}"
embeddings = GoogleGenerativeAIEmbeddings(
model=_gem_model,
google_api_key=settings.GEMINI_API_KEY,
)
else:
# HuggingFace local — no API key needed
from langchain_huggingface import HuggingFaceEmbeddings
embeddings = HuggingFaceEmbeddings(model_name=_model)
+121
View File
@@ -0,0 +1,121 @@
from bs4 import BeautifulSoup
from config import settings
def _get_value(item, key, default=None):
if isinstance(item, dict):
return item.get(key, default)
return getattr(item, key, default)
def _normalize_url(url, source_url):
if not url:
return ""
if url.startswith("//"):
return f"https:{url}"
if url.startswith("http://") or url.startswith("https://"):
return url
if source_url and url.startswith("/"):
from urllib.parse import urljoin
return urljoin(source_url, url)
return url
def _is_usable_image_url(url):
if not url:
return False
if not isinstance(url, str):
return False
lowered = url.lower()
if lowered.startswith("data:") or lowered.endswith(".svg"):
return False
return lowered.startswith("http://") or lowered.startswith("https://")
def _extract_image_from_html(html, source_url):
if not html:
return ""
soup = BeautifulSoup(html, "lxml")
for selector in [
("meta", {"property": "og:image"}),
("meta", {"name": "twitter:image"}),
]:
tag = soup.find(*selector)
image_url = tag.get("content") if tag else ""
if _is_usable_image_url(_normalize_url(image_url, source_url)):
return _normalize_url(image_url, source_url)
for img in soup.find_all("img"):
image_url = img.get("src") or img.get("data-src")
normalized_url = _normalize_url(image_url, source_url)
if _is_usable_image_url(normalized_url):
return normalized_url
return ""
def search_images(query: str, limit: int = 3, context: str = "", placement: str = ""):
try:
from firecrawl import Firecrawl
except ImportError:
return []
firecrawl = Firecrawl(api_key=settings.FIRECRAWL_API_KEY)
search_result = firecrawl.search(query, limit=max(limit * 3, 6))
web_results = _get_value(search_result, "web", []) or []
images = []
seen = set()
for item in web_results:
if len(images) >= limit:
break
page_url = _get_value(item, "url") or _get_value(item, "source_url")
title = _get_value(item, "title", "Suggested image")
description = _get_value(item, "description", "")
direct_image = (
_get_value(item, "image_url")
or _get_value(item, "image")
or _get_value(item, "thumbnail")
)
if not page_url:
continue
image_url = _normalize_url(direct_image, page_url)
if not _is_usable_image_url(image_url):
continue
if not image_url or image_url in seen:
continue
seen.add(image_url)
images.append(
{
"url": image_url,
"alt": title,
"caption": description or title,
"source_url": page_url,
"context": context,
"placement": placement,
}
)
return images
+179
View File
@@ -0,0 +1,179 @@
"""
gemini_llm.py — Google Gemini LLM wrapper.
Uses langchain-google-genai which is the official LangChain integration
for Google's Gemini API. Interface mirrors RotatingChatGroq so all agents
use it transparently through llm_registry.make_llm().
Free tier (as of 2026):
gemini-2.0-flash — 15 RPM, 250 000 TPM, 1 500 RPD (no credit card)
gemini-1.5-flash — 15 RPM, 250 000 TPM, 1 500 RPD (fallback)
Install:
pip install langchain-google-genai
Key must be set in .env:
GEMINI_API_KEY=<your key from https://aistudio.google.com/app/apikey>
GEMINI_MODEL=gemini-2.0-flash # optional — this is the default
"""
from __future__ import annotations
import logging
import time
from config import settings as _settings
logger = logging.getLogger(__name__)
_DEFAULT_MODEL = "gemini-3.5-flash-lite"
_FALLBACK_CHAIN = [
"gemini-3.5-flash-lite",
"gemini-3.5-flash",
"gemini-3.6-flash",
"gemini-3.7-flash",
"gemini-2.5-flash",
"gemini-flash-latest",
]
_raw_gemini_model = getattr(_settings, "GEMINI_MODEL", None)
if _raw_gemini_model and _raw_gemini_model.strip() in (
"gemini-2.0-flash", "gemini-2.0-flash-exp", "models/gemini-2.0-flash",
"gemini-2.5-flash-lite", "models/gemini-2.5-flash-lite"
):
logger.warning("Deprecated Gemini model '%s' specified. Migrating to '%s'.", _raw_gemini_model, _DEFAULT_MODEL)
_ACTIVE_MODEL = _DEFAULT_MODEL
else:
_ACTIVE_MODEL = _raw_gemini_model or _DEFAULT_MODEL
class GeminiChatLLM:
"""
Google Gemini wrapper matching the RotatingChatGroq / OpenAIChatLLM interface.
Exposes:
self._client — raw LangChain ChatGoogleGenerativeAI instance
self._invoke_chain() — rate-limit-aware invocation
"""
def __init__(self, max_tokens: int = 700):
self._max_tokens = max_tokens
self._active_model = _ACTIVE_MODEL
self._client = self._build()
def _build(self):
from langchain_google_genai import ChatGoogleGenerativeAI
model_name = self._active_model
if model_name.startswith("models/"):
model_name = model_name[len("models/"):]
return ChatGoogleGenerativeAI(
model=model_name,
google_api_key=_settings.GEMINI_API_KEY,
temperature=0.3,
max_output_tokens=self._max_tokens,
# Disable safety blocks that would reject blog content
convert_system_message_to_human=True,
timeout=60,
)
def _invoke_chain(self, chain, inputs: dict):
"""
Invoke with Gemini-specific error handling and dynamic model fallback.
429 / ResourceExhausted → try next fallback model in chain, then backoff.
404 / Model not found → immediately switch to next fallback in chain.
5xx server errors → short sleep then try next fallback.
"""
backoff = 10.0
prompt_template = None
if hasattr(chain, "steps") and len(chain.steps) > 0:
prompt_template = chain.steps[0]
for attempt in range(len(_FALLBACK_CHAIN) * 2):
try:
if prompt_template is not None:
runnable = prompt_template | self._client
else:
runnable = chain
return runnable.invoke(inputs)
except Exception as exc:
msg = str(exc).lower()
is_rate = (
"429" in msg
or "resource_exhausted" in msg
or "quota" in msg
or "rate limit" in msg
)
if is_rate:
is_daily = (
"limit: 0" in msg
or "per day" in msg
or "daily" in msg
)
if is_daily:
if self._try_next_fallback():
continue
raise RuntimeError(
"All Gemini models have exhausted their daily quota. "
"Please upgrade your plan or try again tomorrow."
) from exc
if self._try_next_fallback():
continue
wait = min(backoff * (2 ** (attempt % 3)), 60)
logger.warning(
"Gemini quota exhausted on all models (attempt %d) — waiting %.0fs.",
attempt + 1, wait,
)
time.sleep(wait)
continue
is_model_err = (
"not found" in msg
or "invalid model" in msg
or "model_not_found" in msg
or "404" in msg
or "no longer available" in msg
)
if is_model_err:
if self._try_next_fallback():
continue
if "500" in msg or "503" in msg or "internal" in msg:
time.sleep(5)
if self._try_next_fallback():
continue
raise
raise RuntimeError("Gemini request failed after maximum retries on all fallback models.")
def _try_next_fallback(self) -> bool:
"""Switch to the next model in the fallback chain. Returns True if switched."""
try:
curr = self._active_model
if curr.startswith("models/"):
curr = curr[len("models/"):]
clean_chain = [m[len("models/"):] if m.startswith("models/") else m for m in _FALLBACK_CHAIN]
if curr in clean_chain:
next_idx = clean_chain.index(curr) + 1
else:
next_idx = 0
except Exception:
next_idx = 0
if next_idx >= len(_FALLBACK_CHAIN):
return False
next_model = _FALLBACK_CHAIN[next_idx]
logger.warning("Gemini switching from %s → %s.", self._active_model, next_model)
self._active_model = next_model
self._client = self._build()
return True
def _rotate(self) -> bool:
"""Alias for _try_next_fallback for uniform streaming rotation."""
return self._try_next_fallback()
+319
View File
@@ -0,0 +1,319 @@
"""
LLM factory with automatic model rotation.
Rotation pool — models with context sufficient for long outputs.
Free-tier TPM limits (per model):
llama-3.3-70b-versatile : ~6 000 TPM (use for analysis agents ≤700 output)
llama-3.1-8b-instant : ~30 000 TPM (same)
IMPORTANT: aggregator and optimizer request 4 096 output tokens.
With any Groq free-tier model that has an 8 000 TPM window, input must
stay under 3 904 tokens. These two agents use the prose provider
(Gemini / OpenAI) set by the user, NOT Groq, so they are unaffected by
Groq TPM limits. All force_groq=True agents output ≤2 000 tokens and
have input budgets well under 6 000 tokens total.
"""
import logging
import re
import time
from langchain_groq import ChatGroq
from groq import RateLimitError, APIStatusError, NotFoundError
from config import settings as _settings
logger = logging.getLogger(__name__)
# ── Rotation pool ──────────────────────────────────────────────────────────
_MODEL_POOL: list[str] = [
"llama-3.1-8b-instant",
"llama-3.3-70b-versatile",
]
# Per-model TPM caps (approximate free-tier limits).
# Used to decide whether a 413 should rotate (model genuinely too small)
# or sleep-and-retry (hit per-minute window on a capable model).
_MODEL_TPM: dict[str, int] = {
"llama-3.1-8b-instant": 30_000,
"llama-3.3-70b-versatile": 6_000,
}
_configured = _settings.MODEL
_active_model: str = _configured if _configured in _MODEL_POOL else _MODEL_POOL[0]
_exhausted: set[str] = set()
def _next_model() -> str | None:
for m in _MODEL_POOL:
if m not in _exhausted:
return m
return None
def _is_tpd(msg: str) -> bool:
m = msg.lower()
return "tokens per day" in m or "tpd" in m or "requests per day" in m or "rpd" in m
def _is_tpm(msg: str) -> bool:
m = msg.lower()
return "tokens per minute" in m or "tpm" in m or "requests per minute" in m or "rpm" in m
def _parse_wait(msg: str) -> float | None:
match = re.search(
r"try again in\s+(?:(\d+)h)?(?:(\d+)m)?(?:([\d.]+)s)?",
msg, re.IGNORECASE,
)
if not match or not any(match.groups()):
return None
return (
float(match.group(1) or 0) * 3600
+ float(match.group(2) or 0) * 60
+ float(match.group(3) or 0)
+ 1.0
)
class RotatingChatGroq:
"""
Wraps ChatGroq with transparent model rotation on TPD exhaustion.
Usage in agents:
self.llm = make_llm(max_tokens=700)
...
response = invoke_with_retry(self.prompt, self.llm, inputs)
invoke_with_retry rebuilds `prompt | self.llm._client` on every call so
the chain always references the currently active model.
"""
def __init__(self, max_tokens: int = 700):
self._max_tokens = max_tokens
self._client: ChatGroq = self._build()
def _build(self) -> ChatGroq:
return ChatGroq(
model=_active_model,
temperature=0.3,
max_tokens=self._max_tokens,
max_retries=2,
timeout=60,
)
def _rotate(self) -> bool:
global _active_model, _exhausted
_exhausted.add(_active_model)
logger.warning("Model %s TPD exhausted — rotating.", _active_model)
nxt = _next_model()
if nxt is None:
return False
_active_model = nxt
self._client = self._build()
logger.info("Active model → %s", _active_model)
return True
def _invoke_chain(self, chain, inputs: dict):
"""
Invoke a pre-built chain with rotation + retry logic.
Called by invoke_with_retry after it builds chain = prompt | self._client.
"""
tpm_attempt = 0
tpm_base = 15.0
while True:
try:
return chain.invoke(inputs)
except RateLimitError as exc:
msg = str(exc)
if _is_tpd(msg):
rotated = self._rotate()
if not rotated:
from config.llm_registry import get_provider, _is_valid_gemini_key, _is_valid_openai_key
provider = get_provider()
if provider == "groq":
if _is_valid_gemini_key(_settings.GEMINI_API_KEY):
provider = "gemini"
elif _is_valid_openai_key(_settings.OPENAI_API_KEY):
provider = "openai"
if provider != "groq":
logger.warning("Groq daily quota exhausted. Falling back dynamically to '%s'.", provider)
if provider == "openai":
from config.openai_llm import OpenAIChatLLM
fallback_llm = OpenAIChatLLM(max_tokens=self._max_tokens)
else: # gemini
from config.gemini_llm import GeminiChatLLM
fallback_llm = GeminiChatLLM(max_tokens=self._max_tokens)
self._client = fallback_llm._client
self._invoke_chain = fallback_llm._invoke_chain
raise _RotationOccurred() from exc
raise RuntimeError(
"All Groq models have exhausted their daily quota. "
"Try again tomorrow or upgrade your plan."
) from exc
# Rebuild the chain with the new model and retry
chain = chain.first | self._client # type: ignore[attr-defined]
# Simpler: let invoke_with_retry handle the rebuild on next call
# by raising a sentinel that it catches
raise _RotationOccurred() from exc
elif _is_tpm(msg):
tpm_attempt += 1
if tpm_attempt > 3:
logger.warning("Max TPM retries (3) exceeded for model %s. Attempting model rotation or provider fallback.", _active_model)
rotated = self._rotate()
if not rotated:
from config.llm_registry import get_provider, _is_valid_gemini_key, _is_valid_openai_key
provider = get_provider()
if provider == "groq":
if _is_valid_gemini_key(_settings.GEMINI_API_KEY):
provider = "gemini"
elif _is_valid_openai_key(_settings.OPENAI_API_KEY):
provider = "openai"
if provider != "groq":
logger.warning("Groq TPM limit reached on all models. Falling back dynamically to '%s'.", provider)
if provider == "openai":
from config.openai_llm import OpenAIChatLLM
fallback_llm = OpenAIChatLLM(max_tokens=self._max_tokens)
else: # gemini
from config.gemini_llm import GeminiChatLLM
fallback_llm = GeminiChatLLM(max_tokens=self._max_tokens)
self._client = fallback_llm._client
self._invoke_chain = fallback_llm._invoke_chain
raise _RotationOccurred() from exc
raise RuntimeError(
"Request size or rate exceeds Groq free tier model limits. "
"Please select Gemini or OpenAI as your LLM Provider in settings."
) from exc
raise _RotationOccurred() from exc
wait = _parse_wait(msg) or min(tpm_base * (2 ** (tpm_attempt - 1)), 120)
logger.warning("TPM limit (attempt %d/3) — waiting %.1fs.", tpm_attempt, wait)
time.sleep(wait)
# chain is still valid, retry same model
else:
raise
except (APIStatusError, NotFoundError) as exc:
status_code = getattr(exc, "status_code", None)
if isinstance(exc, NotFoundError) or status_code == 404:
msg = str(exc)
logger.warning("HTTP 404 on %s: %s. Attempting model rotation or provider fallback.", _active_model, msg)
rotated = self._rotate()
if not rotated:
from config.llm_registry import get_provider, _is_valid_gemini_key, _is_valid_openai_key
provider = get_provider()
if provider == "groq":
if _is_valid_gemini_key(_settings.GEMINI_API_KEY):
provider = "gemini"
elif _is_valid_openai_key(_settings.OPENAI_API_KEY):
provider = "openai"
if provider != "groq":
logger.warning("Groq 404 on all models. Falling back dynamically to '%s'.", provider)
if provider == "openai":
from config.openai_llm import OpenAIChatLLM
fallback_llm = OpenAIChatLLM(max_tokens=self._max_tokens)
else:
from config.gemini_llm import GeminiChatLLM
fallback_llm = GeminiChatLLM(max_tokens=self._max_tokens)
self._client = fallback_llm._client
self._invoke_chain = fallback_llm._invoke_chain
raise _RotationOccurred() from exc
raise RuntimeError(
f"Model {_active_model} was not found on Groq and no alternative provider is configured. "
"Please check your Groq API key or select Gemini / OpenAI in settings."
) from exc
raise _RotationOccurred() from exc
if status_code == 413:
msg = str(exc)
logger.warning("HTTP 413 on %s: %s. Attempting model rotation or provider fallback.", _active_model, msg)
rotated = self._rotate()
if not rotated:
from config.llm_registry import get_provider, _is_valid_gemini_key, _is_valid_openai_key
provider = get_provider()
if provider == "groq":
if _is_valid_gemini_key(_settings.GEMINI_API_KEY):
provider = "gemini"
elif _is_valid_openai_key(_settings.OPENAI_API_KEY):
provider = "openai"
if provider != "groq":
logger.warning("Groq 413 limit reached on all models. Falling back dynamically to '%s'.", provider)
if provider == "openai":
from config.openai_llm import OpenAIChatLLM
fallback_llm = OpenAIChatLLM(max_tokens=self._max_tokens)
else: # gemini
from config.gemini_llm import GeminiChatLLM
fallback_llm = GeminiChatLLM(max_tokens=self._max_tokens)
self._client = fallback_llm._client
self._invoke_chain = fallback_llm._invoke_chain
raise _RotationOccurred() from exc
raise RuntimeError(
"Request size exceeds the 8,000 TPM limit of Groq free tier models. "
"Please select Gemini or OpenAI as your LLM Provider in settings."
) from exc
raise _RotationOccurred() from exc
if status_code and status_code < 500:
raise
time.sleep(10)
raise
except Exception as exc:
msg = str(exc).lower()
if "model_not_found" in msg or "does not exist" in msg or "404" in msg or "invalid_request_error" in msg:
logger.warning("Model error on %s: %s. Attempting model rotation or provider fallback.", _active_model, exc)
rotated = self._rotate()
if not rotated:
from config.llm_registry import get_provider, _is_valid_gemini_key, _is_valid_openai_key
provider = get_provider()
if provider == "groq":
if _is_valid_gemini_key(_settings.GEMINI_API_KEY):
provider = "gemini"
elif _is_valid_openai_key(_settings.OPENAI_API_KEY):
provider = "openai"
if provider != "groq":
logger.warning("Groq model error on all models. Falling back dynamically to '%s'.", provider)
if provider == "openai":
from config.openai_llm import OpenAIChatLLM
fallback_llm = OpenAIChatLLM(max_tokens=self._max_tokens)
else:
from config.gemini_llm import GeminiChatLLM
fallback_llm = GeminiChatLLM(max_tokens=self._max_tokens)
self._client = fallback_llm._client
self._invoke_chain = fallback_llm._invoke_chain
raise _RotationOccurred() from exc
raise RuntimeError(
f"Model {_active_model} failed on Groq and no alternative provider is configured. "
"Please check your Groq API key or select Gemini / OpenAI in settings."
) from exc
raise _RotationOccurred() from exc
raise
class _RotationOccurred(Exception):
"""Internal sentinel: rotation happened, caller should rebuild chain and retry."""
def make_llm(max_tokens: int = 700) -> RotatingChatGroq:
"""
Return a RotatingChatGroq with the given output token budget.
Budgets by role:
specialist agents (language/facts/structure/seo/geo) : 700
aggregator (editorial brief) : 800
evaluator (JSON scores) : 500
planner / learner (JSON) : 600
researcher (research brief) : 2000
optimizer (full article) : 3000
"""
return RotatingChatGroq(max_tokens=max_tokens)
# Shared default for agents that `from config.llm import llm`
llm = make_llm(max_tokens=700)
+346
View File
@@ -0,0 +1,346 @@
"""
llm_registry.py — single import point for ALL agents.
Mixed-provider routing
──────────────────────
The UI-selected provider (Groq / Gemini / OpenAI) is the PROSE provider.
It is used only for aggregator and optimizer — the two agents that write
long-form article text and benefit most from a high-quality model.
All other agents (evaluators, specialists, researchers, learner, planner)
always run on Groq regardless of the UI selection. This has two benefits:
1. Token cost: Gemini/OpenAI free-tier quota is preserved for prose only.
A typical run uses ~9 000 tokens on the prose provider instead of
~175 000 if every agent used it.
2. Speed: Groq is faster for short structured outputs (JSON scores,
review notes, research briefs) than Gemini Flash or GPT-4o.
Usage in agents:
# Prose agent — uses whatever provider the user selected
llm = make_llm(max_tokens=4096)
# Analysis agent — always Groq, fast + free
llm = make_llm(max_tokens=700, force_groq=True)
"""
from __future__ import annotations
import threading
import os
import logging
import time
_lock = threading.Lock()
_provider = "groq" # changed by set_provider() from Streamlit
# ── Token budgets ──────────────────────────────────────────────────────────────
_GROQ_MAX_TOKENS: dict[str, int] = {
"small": 600,
"medium": 1200,
"large": 4096,
}
_OPENAI_MODEL: dict[str, str] = {
"small": "gpt-4o-mini",
"medium": "gpt-4o-mini",
"large": "gpt-4o",
}
_OPENAI_MAX_TOKENS: dict[str, int] = {
"small": 600,
"medium": 1200,
"large": 4096,
}
# ── Provider & Execution Mode management ──────────────────────────────────────
_execution_mode = "online" # "online" | "offline" | "hybrid"
_local_engine = "ollama"
_local_model_name = "qwen2.5:7b"
_local_base_url = "http://localhost:11434/v1"
_local_api_key = "ollama"
_custom_model_name = ""
_custom_api_key = ""
_custom_base_url = ""
def set_execution_mode(
mode: str = "online",
local_engine: str = "ollama",
local_model_name: str = "qwen2.5:7b",
local_base_url: str = "http://localhost:11434/v1",
local_api_key: str = "ollama",
) -> None:
global _execution_mode, _local_engine, _local_model_name, _local_base_url, _local_api_key
with _lock:
_execution_mode = (mode or "online").lower().strip()
_local_engine = local_engine or "ollama"
_local_model_name = local_model_name or "qwen2.5:7b"
_local_base_url = local_base_url or "http://localhost:11434/v1"
_local_api_key = local_api_key or "ollama"
def set_custom_llm_settings(model_name: str, api_key: str, base_url: str) -> None:
global _custom_model_name, _custom_api_key, _custom_base_url
with _lock:
_custom_model_name = model_name
_custom_api_key = api_key
_custom_base_url = base_url
def set_provider(name: str) -> None:
"""
Switch the active prose provider globally.
Called once from prepare_blog before the graph runs.
Also clears OPENAI_API_KEY from the environment when not using OpenAI
so LangChain internals don't auto-validate it and hit quota.
"""
global _provider
allowed = {"groq", "openai", "gemini", "custom", "local", "ollama", "lmstudio"}
name = name.lower().strip()
if name not in allowed:
raise ValueError(f"Unknown LLM provider '{name}'. Choose from: {allowed}")
with _lock:
_provider = name
if name not in ("openai", "custom"):
os.environ.pop("OPENAI_API_KEY", None)
def _is_valid_gemini_key(key: str | None) -> bool:
if not key: return False
k = key.strip()
return len(k) >= 15
def _is_valid_openai_key(key: str | None) -> bool:
if not key: return False
k = key.strip()
return (k.startswith("sk-") or len(k) >= 20)
def get_provider() -> str:
with _lock:
return _provider
def get_execution_mode() -> str:
with _lock:
return _execution_mode
# ── LLM factory ───────────────────────────────────────────────────────────────
def make_llm(max_tokens: int | None = None, size: str = "large", force_groq: bool = False):
"""
Factory used by every agent.
Supports:
Online Mode: Analysis agents -> Groq (rotating), Prose -> Gemini/OpenAI/Groq
Offline Mode: All agents -> LocalChatLLM (Ollama/LM Studio on GPU)
Hybrid Mode: Analysis agents -> LocalChatLLM, Prose -> Cloud (Gemini/OpenAI)
Args:
max_tokens: Explicit token budget. Overrides size preset if provided.
size: "small" | "medium" | "large" — role-based token preset.
force_groq: If True, flags this agent as an analysis/specialist agent.
Returns:
LocalChatLLM | RotatingChatGroq | OpenAIChatLLM | GeminiChatLLM
"""
with _lock:
provider = _provider
mode = _execution_mode
loc_model = _local_model_name
loc_base = _local_base_url
loc_key = _local_api_key
size = size if size in ("small", "medium", "large") else "large"
tokens = max_tokens if max_tokens is not None else _GROQ_MAX_TOKENS[size]
# 1. 💻 100% Offline Mode — Route ALL agents to local GPU LLM
if mode == "offline" or provider in ("local", "ollama", "lmstudio"):
from config.local_llm import LocalChatLLM
return LocalChatLLM(
model=loc_model,
base_url=loc_base,
api_key=loc_key,
max_tokens=tokens,
)
# 2. 🔀 Hybrid Mode — Analysis on Local GPU, Prose on Cloud
if mode == "hybrid" and force_groq:
from config.local_llm import LocalChatLLM
return LocalChatLLM(
model=loc_model,
base_url=loc_base,
api_key=loc_key,
max_tokens=tokens,
)
# 3. 🌐 Online Cloud Mode (or Hybrid Prose)
use_groq = force_groq or provider == "groq"
if use_groq:
import logging
from config.llm import _MODEL_POOL, _exhausted
from config import settings
fallback_provider = provider
if fallback_provider == "groq":
if _is_valid_gemini_key(settings.GEMINI_API_KEY):
fallback_provider = "gemini"
elif _is_valid_openai_key(settings.OPENAI_API_KEY):
fallback_provider = "openai"
if len(_exhausted) >= len(_MODEL_POOL) and fallback_provider != "groq":
logging.getLogger(__name__).warning("Groq is fully exhausted. Falling back to '%s' pre-emptively.", fallback_provider)
use_groq = False
provider = fallback_provider
if use_groq:
from config.llm import RotatingChatGroq
return RotatingChatGroq(max_tokens=tokens)
if provider == "custom":
from config.openai_llm import OpenAIChatLLM
t_custom = max_tokens if max_tokens is not None else _OPENAI_MAX_TOKENS[size]
with _lock:
model = _custom_model_name
api_key = _custom_api_key
base_url = _custom_base_url
return OpenAIChatLLM(max_tokens=t_custom, model_override=model, api_key=api_key, base_url=base_url)
if provider == "openai":
from config.openai_llm import OpenAIChatLLM
t_openai = max_tokens if max_tokens is not None else _OPENAI_MAX_TOKENS[size]
model = _OPENAI_MODEL[size]
return OpenAIChatLLM(max_tokens=t_openai, model_override=model)
# gemini — prose provider
from config.gemini_llm import GeminiChatLLM
return GeminiChatLLM(max_tokens=tokens)
# ── Streaming invoke ───────────────────────────────────────────────────────────
def stream_invoke(prompt, llm, inputs: dict, chunk_callback) -> str:
"""
Streaming invoke used by aggregator and optimizer.
Handles retries, model rotation, and dynamic provider fallbacks for RotatingChatGroq.
"""
from utilis.retry import invoke_with_retry
try:
from config.llm import _RotationOccurred
except ImportError:
_RotationOccurred = type("_RotationOccurred", (Exception,), {})
try:
from groq import RateLimitError, APIStatusError as GroqAPIStatusError
except ImportError:
RateLimitError = GroqAPIStatusError = None
tpm_attempt = 0
tpm_base = 15.0
while True:
try:
chain = prompt | llm._client
full_text = ""
for chunk in chain.stream(inputs):
raw_token = chunk.content if hasattr(chunk, "content") else chunk
if isinstance(raw_token, list):
extracted = []
for item in raw_token:
if isinstance(item, dict) and "text" in item:
extracted.append(item["text"])
elif isinstance(item, str):
extracted.append(item)
token = "".join(extracted)
elif isinstance(raw_token, str):
token = raw_token
else:
token = str(raw_token) if raw_token is not None else ""
if token:
chunk_callback(token)
full_text += token
try:
from utilis.token_counter import add_tokens
p_tok = len(str(inputs)) // 4
c_tok = len(full_text) // 4
add_tokens(p_tok, c_tok)
except Exception:
pass
return full_text
except Exception as exc:
err_msg = str(exc).lower()
if isinstance(exc, _RotationOccurred):
continue
if hasattr(llm, "_rotate") and hasattr(llm, "_invoke_chain"):
if RateLimitError and isinstance(exc, RateLimitError):
from config.llm import _is_tpd, _is_tpm, _parse_wait
if _is_tpd(err_msg):
rotated = llm._rotate()
if not rotated:
provider = get_provider()
if provider == "groq":
from config import settings
if settings.GEMINI_API_KEY:
provider = "gemini"
elif settings.OPENAI_API_KEY:
provider = "openai"
if provider != "groq":
logging.getLogger(__name__).warning("Groq daily quota exhausted. Falling back dynamically to '%s'.", provider)
if provider == "openai":
from config.openai_llm import OpenAIChatLLM
fallback_llm = OpenAIChatLLM(max_tokens=getattr(llm, "_max_tokens", 3500))
else:
from config.gemini_llm import GeminiChatLLM
fallback_llm = GeminiChatLLM(max_tokens=getattr(llm, "_max_tokens", 3500))
llm._client = fallback_llm._client
llm._invoke_chain = fallback_llm._invoke_chain
continue
raise RuntimeError("All Groq models have exhausted their daily quota. Try again tomorrow or upgrade your plan.") from exc
continue
elif _is_tpm(err_msg):
tpm_attempt += 1
wait = _parse_wait(err_msg) or min(tpm_base * (2 ** (tpm_attempt - 1)), 120)
logging.getLogger(__name__).warning("TPM limit in streaming — waiting %.1fs.", wait)
time.sleep(wait)
continue
if GroqAPIStatusError and isinstance(exc, GroqAPIStatusError) and getattr(exc, "status_code", None) in (404, 413):
status_code = getattr(exc, "status_code", None)
logging.getLogger(__name__).warning("HTTP %s on Groq in streaming (%s). Attempting model rotation or provider fallback.", status_code, err_msg)
rotated = llm._rotate()
if not rotated:
provider = get_provider()
if provider == "groq":
from config import settings
if settings.GEMINI_API_KEY:
provider = "gemini"
elif settings.OPENAI_API_KEY:
provider = "openai"
if provider != "groq":
logging.getLogger(__name__).warning("413 on Groq: all Groq models exhausted/too small. Falling back dynamically to '%s'.", provider)
if provider == "openai":
from config.openai_llm import OpenAIChatLLM
fallback_llm = OpenAIChatLLM(max_tokens=getattr(llm, "_max_tokens", 3500))
else:
from config.gemini_llm import GeminiChatLLM
fallback_llm = GeminiChatLLM(max_tokens=getattr(llm, "_max_tokens", 3500))
llm._client = fallback_llm._client
llm._invoke_chain = fallback_llm._invoke_chain
continue
raise RuntimeError("Request size exceeds the 8,000 TPM limit of Groq free tier models. Please select Gemini or OpenAI as your LLM Provider in settings.") from exc
continue
# Fall back for streaming-not-supported type errors
if any(k in err_msg for k in ("stream", "not support", "chunk")):
response = invoke_with_retry(prompt, llm, inputs)
text = response.content if hasattr(response, "content") else str(response)
chunk_callback(text)
return text
raise
+129
View File
@@ -0,0 +1,129 @@
"""
local_llm.py — Local / Offline LLM adapter and discovery utilities.
Supports:
1. Ollama (default: http://localhost:11434)
2. LM Studio / vLLM / llama.cpp (default: http://localhost:1234/v1)
3. Custom Local OpenAI-compatible server
"""
from __future__ import annotations
import logging
import requests
from typing import List, Tuple
logger = logging.getLogger(__name__)
# Default endpoints
OLLAMA_DEFAULT_BASE_URL = "http://localhost:11434"
LMSTUDIO_DEFAULT_BASE_URL = "http://localhost:1234/v1"
def discover_ollama_models(base_url: str = OLLAMA_DEFAULT_BASE_URL) -> Tuple[bool, List[str], str]:
"""
Queries Ollama's API (/api/tags) to list all locally installed models.
Returns: (is_connected: bool, model_names: list[str], message: str)
"""
clean_url = base_url.rstrip("/")
if clean_url.endswith("/v1"):
clean_url = clean_url[:-3]
try:
resp = requests.get(f"{clean_url}/api/tags", timeout=1.5)
if resp.status_code == 200:
data = resp.json()
models = [m.get("name") for m in data.get("models", []) if m.get("name")]
if models:
return True, models, f"Connected ({len(models)} model(s) found)"
return True, ["qwen2.5:7b", "llama3.2", "mistral"], "Connected (no models pulled yet)"
return False, [], f"HTTP {resp.status_code}"
except Exception as e:
return False, [], f"Not reachable: {e.__class__.__name__}"
def discover_lmstudio_models(base_url: str = LMSTUDIO_DEFAULT_BASE_URL) -> Tuple[bool, List[str], str]:
"""
Queries LM Studio / vLLM / Local OpenAI-compatible API (/v1/models).
Returns: (is_connected: bool, model_names: list[str], message: str)
"""
clean_url = base_url.rstrip("/")
if not clean_url.endswith("/v1"):
endpoint = f"{clean_url}/v1/models"
else:
endpoint = f"{clean_url}/models"
try:
resp = requests.get(endpoint, timeout=1.5)
if resp.status_code == 200:
data = resp.json()
models = [m.get("id") for m in data.get("data", []) if m.get("id")]
if models:
return True, models, f"Connected ({len(models)} model(s) loaded)"
return True, ["local-model"], "Connected"
return False, [], f"HTTP {resp.status_code}"
except Exception as e:
return False, [], f"Not reachable: {e.__class__.__name__}"
class LocalChatLLM:
"""
LangChain-compatible wrapper for local LLM engines (Ollama, LM Studio, vLLM).
Uses ChatOpenAI pointed at local base_url.
"""
def __init__(
self,
model: str = "qwen2.5:7b",
base_url: str = "http://localhost:11434/v1",
api_key: str = "ollama",
temperature: float = 0.3,
max_tokens: int = 3500,
timeout: int = 120,
):
self.model = model or "qwen2.5:7b"
self.base_url = base_url or "http://localhost:11434/v1"
self.api_key = api_key or "ollama"
self.temperature = temperature
self._max_tokens = max_tokens
self.timeout = timeout
self._client = self._build()
def _build(self):
from langchain_openai import ChatOpenAI
# Ensure base_url ends with /v1
b_url = self.base_url.rstrip("/")
if not b_url.endswith("/v1"):
b_url = f"{b_url}/v1"
return ChatOpenAI(
model=self.model,
base_url=b_url,
api_key=self.api_key or "ollama",
temperature=self.temperature,
max_tokens=self._max_tokens,
timeout=self.timeout,
extra_body={"options": {"num_gpu": 99, "num_ctx": 4096}},
)
def _invoke_chain(self, chain, inputs: dict):
"""Invoke local LLM with helpful connection error messaging."""
try:
return chain.invoke(inputs)
except Exception as exc:
msg = str(exc)
err_lower = msg.lower()
if any(k in err_lower for k in ("connection error", "connect", "connection refused", "target machine actively refused", "failed to establish a new connection")):
clean_url = self.base_url.replace("/v1", "")
raise RuntimeError(
f"Cannot connect to local LLM server at '{self.base_url}'. "
f"Please make sure your local engine ({clean_url}) is running, "
f"or switch 'Execution Mode' to 'Online Cloud' in the sidebar."
) from exc
logger.error("Local LLM invocation error on model '%s' (%s): %s", self.model, self.base_url, exc)
raise
def _rotate(self) -> bool:
"""No-op rotate for local LLMs."""
return False
+11
View File
@@ -0,0 +1,11 @@
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(message)s"
)
logger = logging.getLogger(__name__)
+190
View File
@@ -0,0 +1,190 @@
import json
import hashlib
from pathlib import Path
from openai import OpenAI
import requests
from config import settings
IMAGE_DIR = Path(__file__).resolve().parents[1] / "generated_images"
def _client():
if not settings.NEMOTRON_API_KEY or not settings.NEMOTRON_MODEL:
return None
return OpenAI(
api_key=settings.NEMOTRON_API_KEY,
base_url=settings.NEMOTRON_BASE_URL,
timeout=60.0,
)
def _candidate_text(candidates):
lines = []
for index, candidate in enumerate(candidates, start=1):
lines.append(
"\n".join(
[
f"{index}. URL: {candidate.get('url', '')}",
f"Alt: {candidate.get('alt', '')}",
f"Caption: {candidate.get('caption', '')}",
f"Source: {candidate.get('source_url', '')}",
]
)
)
return "\n\n".join(lines)
def _parse_selection(content, candidates, limit):
try:
payload = json.loads(content)
except json.JSONDecodeError:
# Bad JSON from the model — return nothing rather than a random candidate
return []
selected = payload.get("selected_images", payload if isinstance(payload, list) else [])
ranked = []
for item in selected:
if not isinstance(item, dict):
continue
index = item.get("index")
score = item.get("score", 0)
# Hard threshold: below 60 means the model itself considers it irrelevant
try:
if int(score) < 60:
continue
except (TypeError, ValueError):
pass
try:
candidate = candidates[int(index) - 1].copy()
except (TypeError, ValueError, IndexError):
continue
candidate["relevance_score"] = score
candidate["relevance_reason"] = item.get("reason", "")
candidate["alt"] = item.get("alt") or candidate.get("alt")
candidate["caption"] = item.get("caption") or candidate.get("caption")
ranked.append(candidate)
# Do NOT fall back to candidates[:limit] — return empty if nothing passes
return ranked[:limit]
def _vision_content(prompt, candidates):
content = [{"type": "text", "text": prompt}]
for index, candidate in enumerate(candidates[:6], start=1):
content.append({"type": "text", "text": f"Candidate {index}"})
content.append(
{
"type": "image_url",
"image_url": {"url": candidate.get("url", "")},
}
)
return content
def select_relevant_images(context, section, candidates, limit=1):
if not candidates:
return []
from config.llm_registry import make_llm
from utilis.retry import invoke_with_retry
from langchain_core.prompts import ChatPromptTemplate
prompt = f"""
You are a strict editorial image reviewer for a professional business blog.
Blog topic: {section}
Section context (the text this image must illustrate):
{context}
Image candidates:
{_candidate_text(candidates)}
RULES:
- Only select an image if it DIRECTLY illustrates the section context above.
- The image must be a photograph, diagram, infographic, or chart relevant to the blog topic.
- REJECT any image that shows: people (unless they are clearly in a business/workplace context), entertainment, sports, martial arts, movies, TV shows, celebrities, cartoon characters, food, nature scenes unrelated to the topic, or anything that a reader would find confusing next to this blog section.
- A score below 60 means REJECT — do not include it.
- If NO candidate is relevant enough, return an empty selected_images array.
Return ONLY JSON:
{{
"selected_images": [
{{
"index": 1,
"score": 0-100,
"reason": "why this image fits the section context",
"alt": "descriptive alt text for the image",
"caption": "short caption for display under the image"
}}
]
}}
If nothing is suitable, return: {{"selected_images": []}}
"""
try:
llm = make_llm(max_tokens=800, force_groq=True)
chat_prompt = ChatPromptTemplate.from_messages([("human", prompt)])
response = invoke_with_retry(chat_prompt, llm, {})
content = response.content or ""
except Exception:
return candidates[:limit]
return _parse_selection(content, candidates, limit)
def download_image(image, section):
url = image.get("url")
if not url:
return image
IMAGE_DIR.mkdir(parents=True, exist_ok=True)
safe_section = "".join(
character.lower() if character.isalnum() else "-"
for character in section
).strip("-")[:50] or "blog-image"
try:
response = requests.get(url, timeout=8, headers={"User-Agent": "Mozilla/5.0"})
response.raise_for_status()
# Reject tiny icons, tracking pixels, and empty responses (< 3500 bytes)
if len(response.content) < 3500:
return None
except Exception:
return None
content_type = response.headers.get("content-type", "").split(";")[0]
extension = {
"image/jpeg": ".jpg",
"image/jpg": ".jpg",
"image/png": ".png",
"image/webp": ".webp",
"image/gif": ".gif",
}.get(content_type, ".jpg")
content_hash = hashlib.md5(response.content).hexdigest()
file_name = f"{safe_section}-{content_hash[:12]}{extension}"
file_path = IMAGE_DIR / file_name
file_path.write_bytes(response.content)
image["remote_url"] = url
image["local_path"] = file_path.as_posix()
image["url"] = file_path.as_posix()
image["content_hash"] = content_hash
image["byte_size"] = len(response.content)
return image
+124
View File
@@ -0,0 +1,124 @@
"""
openai_llm.py — OpenAI GPT-4 LLM wrapper.
Provides an OpenAIChatLLM class whose interface matches RotatingChatGroq
so every agent can use it transparently through the shared registry.
Supported models (override via OPENAI_MODEL in .env):
gpt-4o — default, best quality, 128K context
gpt-4-turbo — faster, slightly cheaper
gpt-4 — original GPT-4
gpt-3.5-turbo — fallback / cost saving
Token limits are set per-call via max_tokens, same as Groq.
OpenAI does not have a per-minute rotation requirement — it uses
standard 429 rate-limit handling with exponential back-off.
"""
import logging
import time
from langchain_openai import ChatOpenAI
from openai import RateLimitError, APIStatusError
from config import settings as _settings
logger = logging.getLogger(__name__)
# Default model — can be overridden in .env as OPENAI_MODEL
_DEFAULT_MODEL = "gpt-4o"
_ACTIVE_MODEL = getattr(_settings, "OPENAI_MODEL", None) or _DEFAULT_MODEL
# Available models in priority order (used if the primary hits a hard cap)
_MODEL_POOL = [
"gpt-4o",
"gpt-4-turbo",
"gpt-4",
"gpt-3.5-turbo",
]
class OpenAIChatLLM:
"""
OpenAI LLM wrapper that mirrors the RotatingChatGroq interface.
Agents call it exactly the same way:
self.llm = make_llm(max_tokens=700) # from llm_registry
response = invoke_with_retry(prompt, self.llm, inputs)
Internally exposes:
self._client — the raw ChatOpenAI instance (used by invoke_with_retry)
self._invoke_chain(chain, inputs) — rate-limit aware invocation
"""
def __init__(self, max_tokens: int = 700, model_override: str | None = None, api_key: str | None = None, base_url: str | None = None):
self._max_tokens = max_tokens
self._active_model = model_override or _ACTIVE_MODEL
self._api_key = api_key or _settings.OPENAI_API_KEY
self._base_url = base_url
self._client: ChatOpenAI = self._build()
def _build(self) -> ChatOpenAI:
kwargs = {
"model": self._active_model,
"temperature": 0.3,
"max_tokens": self._max_tokens,
"max_retries": 2,
"api_key": self._api_key,
"timeout": 60,
}
if self._base_url:
kwargs["base_url"] = self._base_url
return ChatOpenAI(**kwargs)
def _invoke_chain(self, chain, inputs: dict):
"""
Invoke a pre-built chain with OpenAI-specific rate-limit handling.
429 RateLimitError → exponential back-off up to 120 s then re-raise.
413 / context-length errors → try falling back to a smaller model.
5xx errors → short sleep then re-raise.
"""
backoff = 10.0
max_wait = 120.0
for attempt in range(6):
try:
return chain.invoke(inputs)
except RateLimitError as exc:
if attempt >= 5:
raise
wait = min(backoff * (2 ** attempt), max_wait)
logger.warning(
"OpenAI RateLimitError (attempt %d) — waiting %.0fs.",
attempt + 1, wait,
)
time.sleep(wait)
except APIStatusError as exc:
# Context length exceeded — try a model with larger context
if exc.status_code in (400, 413):
next_model = self._fallback_model()
if next_model:
logger.warning(
"OpenAI %d on %s — falling back to %s.",
exc.status_code, self._active_model, next_model,
)
self._active_model = next_model
self._client = self._build()
chain = chain.first | self._client # type: ignore[attr-defined]
continue
if exc.status_code >= 500:
time.sleep(10)
raise
raise RuntimeError("OpenAI request failed after maximum retries.")
def _fallback_model(self) -> str | None:
"""Return the next model in the pool after the currently active one."""
try:
idx = _MODEL_POOL.index(self._active_model)
return _MODEL_POOL[idx + 1] if idx + 1 < len(_MODEL_POOL) else None
except ValueError:
return _MODEL_POOL[0]
+56
View File
@@ -0,0 +1,56 @@
"""
pinecone_manager.py
Creates or retrieves the Pinecone index.
Auto-recreation: if an existing index was built with a different dimension
(e.g. 3072 for OpenAI but now using Gemini at 768), the old index is deleted
and a new one is created with the correct dimension. All previously ingested
vectors are lost — the next ingest_blog() call will repopulate it.
"""
import logging
from pinecone import Pinecone, ServerlessSpec
from config import settings
logger = logging.getLogger(__name__)
pc = Pinecone(api_key=settings.PINECONE_API_KEY)
INDEX_NAME = settings.PINECONE_INDEX_NAME
DIMENSION = settings.EMBEDDING_DIMENSION
def get_or_create_index():
existing = {i.name: i for i in pc.list_indexes()}
if INDEX_NAME in existing:
index_info = existing[INDEX_NAME]
# Check dimension match — access via dict-style or attribute
try:
stored_dim = (
index_info.dimension # pinecone-client ≥ 3
if hasattr(index_info, "dimension")
else index_info["dimension"] # older client
)
except Exception:
stored_dim = None
if stored_dim is not None and int(stored_dim) != int(DIMENSION):
logger.warning(
"Pinecone index '%s' has dimension %d but current embedding "
"model requires %d. Deleting and recreating the index.",
INDEX_NAME, stored_dim, DIMENSION,
)
pc.delete_index(INDEX_NAME)
else:
return pc.Index(INDEX_NAME)
pc.create_index(
name=INDEX_NAME,
dimension=DIMENSION,
metric="cosine",
spec=ServerlessSpec(cloud="aws", region="us-east-1"),
)
return pc.Index(INDEX_NAME)
+106
View File
@@ -0,0 +1,106 @@
import logging
from tavily import TavilyClient
from config import settings
logger = logging.getLogger(__name__)
MAX_QUERY_LENGTH = 390
def _get_client():
key = settings.TAVILY_API_KEY
if not key:
return None
return TavilyClient(api_key=key)
def _limit_query(query, max_length=MAX_QUERY_LENGTH):
query = " ".join(str(query).split())
if len(query) <= max_length:
return query
return query[:max_length].rsplit(" ", 1)[0].strip()
def search(query, max_results=5, search_depth="advanced"):
client = _get_client()
if not client:
logger.warning("Tavily API key not found.")
return {"results": []}
try:
response = client.search(
query=_limit_query(query),
max_results=max_results,
search_depth=search_depth
)
return response
except Exception as exc:
logger.warning("Tavily search error: %s", exc)
return {"results": []}
def search_image_candidates(query, max_results=8, search_depth="advanced"):
client = _get_client()
if not client:
logger.warning("Tavily API key not found.")
return []
try:
response = client.search(
query=_limit_query(query),
max_results=max_results,
search_depth=search_depth,
include_images=True,
include_image_descriptions=True
)
except Exception as exc:
logger.warning("Tavily image search error: %s", exc)
response = {}
images = response.get("images", []) if isinstance(response, dict) else []
candidates = []
seen = set()
for image in images:
if isinstance(image, str):
image_url = image
description = ""
else:
image_url = image.get("url") or image.get("image_url")
description = image.get("description") or image.get("alt") or ""
if not image_url or image_url in seen:
continue
seen.add(image_url)
candidates.append(
{
"url": image_url,
"alt": description,
"caption": description,
"source_url": image_url,
}
)
results = response.get("results", []) if isinstance(response, dict) else []
for result in results:
image_url = result.get("image_url") or result.get("thumbnail")
if not image_url or image_url in seen:
continue
seen.add(image_url)
candidates.append(
{
"url": image_url,
"alt": result.get("title", ""),
"caption": result.get("content", "") or result.get("title", ""),
"source_url": result.get("url") or image_url,
}
)
return candidates
+3
View File
@@ -0,0 +1,3 @@
from db.database import BlogDatabase
__all__ = ["BlogDatabase"]
+497
View File
@@ -0,0 +1,497 @@
"""
database.py — SQLite persistence layer for Blog Expert.
Single file, zero external dependencies beyond stdlib.
DB file: blog/data/blog_enhancer.db (created automatically on first use).
Schema
──────
runs — one row per enhancement run (metadata + scores)
articles — one row per run (full text content, joined on run_id)
Thread safety: SQLite WAL mode + per-call connections.
Each public method opens, uses, and closes its own connection so it is
safe to call from Streamlit's background thread without a shared lock.
"""
from __future__ import annotations
import sqlite3
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional
from db.models import Article, Run
# DB lives in blog/data/ so it survives git clean of source files
_DB_DIR = Path(__file__).resolve().parents[1] / "data"
_DB_PATH = _DB_DIR / "blog_enhancer.db"
_DDL = """
PRAGMA journal_mode = WAL;
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT NOT NULL,
title TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
duration_seconds REAL NOT NULL DEFAULT 0,
llm_provider TEXT NOT NULL DEFAULT '',
research_level TEXT NOT NULL DEFAULT '',
language_quality TEXT NOT NULL DEFAULT '',
max_pages INTEGER NOT NULL DEFAULT 5,
image_count INTEGER NOT NULL DEFAULT 3,
optimizer_iterations INTEGER NOT NULL DEFAULT 0,
evaluation_iterations INTEGER NOT NULL DEFAULT 0,
baseline_overall INTEGER NOT NULL DEFAULT 0,
baseline_language INTEGER NOT NULL DEFAULT 0,
baseline_facts INTEGER NOT NULL DEFAULT 0,
baseline_structure INTEGER NOT NULL DEFAULT 0,
baseline_seo INTEGER NOT NULL DEFAULT 0,
baseline_geo INTEGER NOT NULL DEFAULT 0,
baseline_freshness INTEGER NOT NULL DEFAULT 0,
enhanced_overall INTEGER NOT NULL DEFAULT 0,
enhanced_language INTEGER NOT NULL DEFAULT 0,
enhanced_facts INTEGER NOT NULL DEFAULT 0,
enhanced_structure INTEGER NOT NULL DEFAULT 0,
enhanced_seo INTEGER NOT NULL DEFAULT 0,
enhanced_geo INTEGER NOT NULL DEFAULT 0,
enhanced_freshness INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'completed',
error_message TEXT NOT NULL DEFAULT '',
prompt_tokens INTEGER NOT NULL DEFAULT 0,
completion_tokens INTEGER NOT NULL DEFAULT 0,
total_tokens INTEGER NOT NULL DEFAULT 0,
parent_run_id INTEGER REFERENCES runs(id) ON DELETE SET NULL,
topic_idea TEXT NOT NULL DEFAULT '',
other_info TEXT NOT NULL DEFAULT '',
serialized_state TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS articles (
run_id INTEGER PRIMARY KEY REFERENCES runs(id) ON DELETE CASCADE,
original_blog TEXT NOT NULL DEFAULT '',
enhanced_blog TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS jobs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
run_id INTEGER,
url TEXT NOT NULL,
title TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'running',
active_agent TEXT NOT NULL DEFAULT '',
progress_pct INTEGER NOT NULL DEFAULT 0,
streamed_text TEXT NOT NULL DEFAULT '',
error_message TEXT NOT NULL DEFAULT '',
started_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
cancel_requested INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_jobs_status ON jobs(status);
"""
def _connect() -> sqlite3.Connection:
_DB_DIR.mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(_DB_PATH, timeout=30.0, check_same_thread=False)
conn.row_factory = sqlite3.Row
return conn
def _ensure_schema() -> None:
with _connect() as conn:
conn.executescript(_DDL)
try:
conn.execute("SELECT title FROM runs LIMIT 1")
except sqlite3.OperationalError:
conn.execute("ALTER TABLE runs ADD COLUMN title TEXT NOT NULL DEFAULT ''")
conn.commit()
try:
conn.execute("SELECT title FROM jobs LIMIT 1")
except sqlite3.OperationalError:
conn.execute("ALTER TABLE jobs ADD COLUMN title TEXT NOT NULL DEFAULT ''")
conn.commit()
try:
conn.execute("SELECT prompt_tokens FROM runs LIMIT 1")
except sqlite3.OperationalError:
conn.execute("ALTER TABLE runs ADD COLUMN prompt_tokens INTEGER NOT NULL DEFAULT 0")
conn.execute("ALTER TABLE runs ADD COLUMN completion_tokens INTEGER NOT NULL DEFAULT 0")
conn.execute("ALTER TABLE runs ADD COLUMN total_tokens INTEGER NOT NULL DEFAULT 0")
conn.commit()
try:
conn.execute("SELECT parent_run_id FROM runs LIMIT 1")
except sqlite3.OperationalError:
conn.execute("ALTER TABLE runs ADD COLUMN parent_run_id INTEGER REFERENCES runs(id) ON DELETE SET NULL")
conn.commit()
try:
conn.execute("SELECT topic_idea FROM runs LIMIT 1")
except sqlite3.OperationalError:
conn.execute("ALTER TABLE runs ADD COLUMN topic_idea TEXT NOT NULL DEFAULT ''")
conn.execute("ALTER TABLE runs ADD COLUMN other_info TEXT NOT NULL DEFAULT ''")
conn.commit()
try:
conn.execute("SELECT serialized_state FROM runs LIMIT 1")
except sqlite3.OperationalError:
conn.execute("ALTER TABLE runs ADD COLUMN serialized_state TEXT NOT NULL DEFAULT ''")
conn.commit()
# Ensure schema exists when module is imported
_ensure_schema()
class BlogDatabase:
"""Public API for all DB operations."""
# ── Write ────────────────────────────────────────────────────────────────
def save_run(
self,
*,
url: str,
title: str = "",
duration_seconds: float,
llm_provider: str,
research_level: str,
language_quality: str,
max_pages: int,
image_count: int,
optimizer_iterations: int,
evaluation_iterations: int,
baseline_overall: int,
baseline_language: int,
baseline_facts: int,
baseline_structure: int,
baseline_seo: int,
baseline_geo: int,
baseline_freshness: int,
enhanced_overall: int,
enhanced_language: int,
enhanced_facts: int,
enhanced_structure: int,
enhanced_seo: int,
enhanced_geo: int,
enhanced_freshness: int,
original_blog: str,
enhanced_blog: str,
status: str = "completed",
error_message: str = "",
prompt_tokens: int = 0,
completion_tokens: int = 0,
total_tokens: int = 0,
parent_run_id: int | None = None,
topic_idea: str = "",
other_info: str = "",
serialized_state: str = "",
) -> int:
"""Insert a completed run + its article content. Returns the new run_id."""
created_at = datetime.now(timezone.utc).isoformat(timespec="seconds")
with _connect() as conn:
cur = conn.execute(
"""
INSERT INTO runs (
url, title, created_at, duration_seconds,
llm_provider, research_level, language_quality,
max_pages, image_count,
optimizer_iterations, evaluation_iterations,
baseline_overall, baseline_language, baseline_facts,
baseline_structure, baseline_seo, baseline_geo, baseline_freshness,
enhanced_overall, enhanced_language, enhanced_facts,
enhanced_structure, enhanced_seo, enhanced_geo, enhanced_freshness,
status, error_message,
prompt_tokens, completion_tokens, total_tokens, parent_run_id,
topic_idea, other_info, serialized_state
) VALUES (
:url, :title, :created_at, :duration_seconds,
:llm_provider, :research_level, :language_quality,
:max_pages, :image_count,
:optimizer_iterations, :evaluation_iterations,
:baseline_overall, :baseline_language, :baseline_facts,
:baseline_structure, :baseline_seo, :baseline_geo, :baseline_freshness,
:enhanced_overall, :enhanced_language, :enhanced_facts,
:enhanced_structure, :enhanced_seo, :enhanced_geo, :enhanced_freshness,
:status, :error_message,
:prompt_tokens, :completion_tokens, :total_tokens, :parent_run_id,
:topic_idea, :other_info, :serialized_state
)
""",
{
"url": url,
"title": title,
"created_at": created_at,
"duration_seconds": round(duration_seconds, 1),
"llm_provider": llm_provider,
"research_level": research_level,
"language_quality": language_quality,
"max_pages": max_pages,
"image_count": image_count,
"optimizer_iterations": optimizer_iterations,
"evaluation_iterations": evaluation_iterations,
"baseline_overall": baseline_overall,
"baseline_language": baseline_language,
"baseline_facts": baseline_facts,
"baseline_structure": baseline_structure,
"baseline_seo": baseline_seo,
"baseline_geo": baseline_geo,
"baseline_freshness": baseline_freshness,
"enhanced_overall": enhanced_overall,
"enhanced_language": enhanced_language,
"enhanced_facts": enhanced_facts,
"enhanced_structure": enhanced_structure,
"enhanced_seo": enhanced_seo,
"enhanced_geo": enhanced_geo,
"enhanced_freshness": enhanced_freshness,
"status": status,
"error_message": error_message,
"prompt_tokens": prompt_tokens,
"completion_tokens": completion_tokens,
"total_tokens": total_tokens,
"parent_run_id": parent_run_id,
"topic_idea": topic_idea,
"other_info": other_info,
"serialized_state": serialized_state,
},
)
run_id = cur.lastrowid
conn.execute(
"INSERT INTO articles (run_id, original_blog, enhanced_blog) VALUES (?, ?, ?)",
(run_id, original_blog, enhanced_blog),
)
conn.commit()
return run_id
def save_failed_run(
self,
*,
url: str,
error_message: str,
title: str = "",
prompt_tokens: int = 0,
completion_tokens: int = 0,
total_tokens: int = 0,
optimizer_iterations: int = 0,
evaluation_iterations: int = 0,
llm_provider: str = "",
research_level: str = "",
language_quality: str = "",
max_pages: int = 5,
image_count: int = 3,
parent_run_id: int | None = None,
topic_idea: str = "",
other_info: str = "",
serialized_state: str = "",
) -> int:
"""Record a run that crashed before completion."""
created_at = datetime.now(timezone.utc).isoformat(timespec="seconds")
with _connect() as conn:
cur = conn.execute(
"""
INSERT INTO runs (
url, title, created_at, status, error_message,
prompt_tokens, completion_tokens, total_tokens,
optimizer_iterations, evaluation_iterations,
llm_provider, research_level, language_quality,
max_pages, image_count, parent_run_id,
topic_idea, other_info, serialized_state
)
VALUES (?, ?, ?, 'failed', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
url, title, created_at, str(error_message)[:2000],
prompt_tokens, completion_tokens, total_tokens,
optimizer_iterations, evaluation_iterations,
llm_provider, research_level, language_quality,
max_pages, image_count, parent_run_id,
topic_idea, other_info, serialized_state
),
)
run_id = cur.lastrowid
conn.execute(
"INSERT INTO articles (run_id, original_blog, enhanced_blog) VALUES (?, '', '')",
(run_id,),
)
conn.commit()
return run_id
# ── Read ─────────────────────────────────────────────────────────────────
def list_runs(self, limit: int = 100) -> list[Run]:
"""Return recent runs, newest first."""
with _connect() as conn:
rows = conn.execute(
"SELECT * FROM runs ORDER BY created_at DESC LIMIT ?", (limit,)
).fetchall()
return [self._row_to_run(r) for r in rows]
def get_run(self, run_id: int) -> Optional[Run]:
with _connect() as conn:
row = conn.execute(
"SELECT * FROM runs WHERE id = ?", (run_id,)
).fetchone()
return self._row_to_run(row) if row else None
def get_article(self, run_id: int) -> Optional[Article]:
with _connect() as conn:
row = conn.execute(
"SELECT * FROM articles WHERE run_id = ?", (run_id,)
).fetchone()
if not row:
return None
return Article(
run_id=row["run_id"],
original_blog=row["original_blog"],
enhanced_blog=row["enhanced_blog"],
)
def delete_run(self, run_id: int) -> None:
"""Delete a run and its article (CASCADE handles articles)."""
with _connect() as conn:
conn.execute("DELETE FROM runs WHERE id = ?", (run_id,))
conn.commit()
# ── Jobs (live progress tracking) ────────────────────────────────────────
def create_job(self, url: str, title: str = "") -> int:
"""Create a new in-progress job. Returns job_id."""
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
with _connect() as conn:
cur = conn.execute(
"INSERT INTO jobs (url, title, status, started_at, updated_at) VALUES (?, ?, 'running', ?, ?)",
(url, title, now, now),
)
conn.commit()
return cur.lastrowid
def update_job(self, job_id: int, *, active_agent: str = "",
progress_pct: int = 0, streamed_text: str = "",
title: str = None) -> None:
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
with _connect() as conn:
if title is not None:
conn.execute(
"""UPDATE jobs SET active_agent=?, progress_pct=?,
streamed_text=?, updated_at=?, title=? WHERE id=?""",
(active_agent, progress_pct,
streamed_text[-12_000:], # keep last ~12 000 chars of stream
now, title, job_id),
)
else:
conn.execute(
"""UPDATE jobs SET active_agent=?, progress_pct=?,
streamed_text=?, updated_at=? WHERE id=?""",
(active_agent, progress_pct,
streamed_text[-12_000:], # keep last ~12 000 chars of stream
now, job_id),
)
conn.commit()
def finish_job(self, job_id: int, run_id: Optional[int] = None,
error: str = "") -> None:
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
status = "failed" if error else "completed"
with _connect() as conn:
conn.execute(
"""UPDATE jobs SET status=?, run_id=?, error_message=?,
progress_pct=100, updated_at=? WHERE id=?""",
(status, run_id, error[:2000], now, job_id),
)
conn.commit()
def cancel_job(self, job_id: int) -> None:
with _connect() as conn:
conn.execute(
"UPDATE jobs SET cancel_requested=1 WHERE id=?", (job_id,)
)
conn.commit()
def is_cancel_requested(self, job_id: int) -> bool:
with _connect() as conn:
row = conn.execute(
"SELECT cancel_requested FROM jobs WHERE id=?", (job_id,)
).fetchone()
return bool(row and row["cancel_requested"])
def get_job(self, job_id: int):
with _connect() as conn:
return conn.execute(
"SELECT * FROM jobs WHERE id=?", (job_id,)
).fetchone()
def list_active_jobs(self):
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
with _connect() as conn:
rows = conn.execute(
"SELECT * FROM jobs WHERE status='running' ORDER BY started_at DESC"
).fetchall()
active = []
for r in rows:
try:
updated = datetime.fromisoformat(r["updated_at"])
if updated.tzinfo is None:
updated = updated.replace(tzinfo=timezone.utc)
else:
updated = updated.astimezone(timezone.utc)
if (now - updated).total_seconds() > 300:
# Stale job — mark as failed
conn.execute(
"UPDATE jobs SET status='failed', error_message='Job became stale (thread died or process restarted)' WHERE id=?",
(r["id"],)
)
conn.commit()
self.save_failed_run(url=r["url"], error_message="Job became stale (thread died or process restarted)")
else:
active.append(r)
except Exception:
active.append(r)
return active
# ── Internal ─────────────────────────────────────────────────────────────
@staticmethod
def _row_to_run(row: sqlite3.Row) -> Run:
return Run(
id=row["id"],
url=row["url"],
title=row["title"] if "title" in row.keys() else "",
created_at=row["created_at"],
duration_seconds=row["duration_seconds"],
llm_provider=row["llm_provider"],
research_level=row["research_level"],
language_quality=row["language_quality"],
max_pages=row["max_pages"],
image_count=row["image_count"],
optimizer_iterations=row["optimizer_iterations"],
evaluation_iterations=row["evaluation_iterations"],
baseline_overall=row["baseline_overall"],
baseline_language=row["baseline_language"],
baseline_facts=row["baseline_facts"],
baseline_structure=row["baseline_structure"],
baseline_seo=row["baseline_seo"],
baseline_geo=row["baseline_geo"],
baseline_freshness=row["baseline_freshness"],
enhanced_overall=row["enhanced_overall"],
enhanced_language=row["enhanced_language"],
enhanced_facts=row["enhanced_facts"],
enhanced_structure=row["enhanced_structure"],
enhanced_seo=row["enhanced_seo"],
enhanced_geo=row["enhanced_geo"],
enhanced_freshness=row["enhanced_freshness"],
status=row["status"],
error_message=row["error_message"],
prompt_tokens=row["prompt_tokens"] if "prompt_tokens" in row.keys() else 0,
completion_tokens=row["completion_tokens"] if "completion_tokens" in row.keys() else 0,
total_tokens=row["total_tokens"] if "total_tokens" in row.keys() else 0,
parent_run_id=row["parent_run_id"] if "parent_run_id" in row.keys() else None,
topic_idea=row["topic_idea"] if "topic_idea" in row.keys() else "",
other_info=row["other_info"] if "other_info" in row.keys() else "",
serialized_state=row["serialized_state"] if "serialized_state" in row.keys() else "",
)
+60
View File
@@ -0,0 +1,60 @@
"""
models.py — plain dataclasses for database rows.
No ORM, no dependencies beyond stdlib.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class Run:
"""One completed (or failed) enhancement run."""
id: int
url: str
created_at: str # ISO-8601 UTC
duration_seconds: float
llm_provider: str
research_level: str
language_quality: str
max_pages: int
image_count: int
optimizer_iterations: int
evaluation_iterations: int
# Baseline scores
baseline_overall: int
baseline_language: int
baseline_facts: int
baseline_structure: int
baseline_seo: int
baseline_geo: int
baseline_freshness: int
# Enhanced scores
enhanced_overall: int
enhanced_language: int
enhanced_facts: int
enhanced_structure: int
enhanced_seo: int
enhanced_geo: int
enhanced_freshness: int
status: str = "completed" # completed | failed
error_message: str = ""
title: str = ""
prompt_tokens: int = 0
completion_tokens: int = 0
total_tokens: int = 0
parent_run_id: Optional[int] = None
topic_idea: str = ""
other_info: str = ""
serialized_state: str = ""
@dataclass
class Article:
"""Full article content linked to a run."""
run_id: int
original_blog: str # cleaned_blog — original scraped markdown
enhanced_blog: str # optimized_blog or aggregated_blog
+8
View File
@@ -0,0 +1,8 @@
def __getattr__(name):
if name == "graph":
from .graph import graph
return graph
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+279
View File
@@ -0,0 +1,279 @@
"""
Compiled LangGraph workflow for the blog optimizer.
Flow:
prepare → learner → planner → supervisor
→ language → facts → structure → image → seo → geo
→ aggregator → evaluator ─(evaluation_router)─┐
├→ supervisor/language/facts/structure/seo/geo (re-brief)
└→ optimizer
│
evaluator_post ─(optimizer_router)─┐
├→ targeted_researcher → optimizer
├→ optimizer (scores 70-89, loop, max 5)
└→ END
Architecture change — Supervisor replaces the single Researcher:
Old: one researcher → one generic brief → all 5 specialists
New: supervisor → one Tavily search → one LLM call → 5 focused briefs
Each specialist reads its own dedicated brief:
language_research, facts_research, structure_research,
seo_research, geo_research
"""
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langgraph.graph import END, StateGraph
from agents.aggregator import AggregatorAgent
from agents.baseline_evaluator import BaselineEvaluatorAgent
from agents.evaluator import EvaluatorAgent
from agents.facts_agent import FactsAgent
from agents.geo_agent import GeoAgent
from agents.image_agent import ImageAgent
from agents.language_agent import LanguageAgent
from agents.learner import LearnerAgent
from agents.optimizer import OptimizerAgent
from agents.planner import PlannerAgent
from agents.supervisor import SupervisorAgent
from agents.seo_agent import SeoAgent
from agents.structure_agent import StructureAgent
from agents.targeted_researcher import TargetedResearchAgent
from config.llm_registry import set_provider
from graph.router import evaluation_router, optimizer_router
from graph.state import BlogState
from rag.chunker import create_chunks
from rag.html_cleaner import clean_html
from rag.ingestion import ingest_blog
from rag.markdown_converter import html_to_markdown
from rag.scraper import scrape_blog
from utilis.tracing import traceable
from concurrent.futures import ThreadPoolExecutor
import threading
@traceable
def prepare_blog(state: BlogState):
if getattr(state, "job_id", 0):
from db.database import BlogDatabase
if BlogDatabase().is_cancel_requested(state.job_id):
raise RuntimeError("Cancelled by user.")
set_provider(state.llm_provider)
if state.llm_provider == "custom":
from config.llm_registry import set_custom_llm_settings
set_custom_llm_settings(state.custom_model_name, state.custom_api_key, state.custom_base_url)
from config.llm_registry import set_execution_mode
set_execution_mode(
mode=getattr(state, "execution_mode", "online"),
local_engine=getattr(state, "local_engine", "ollama"),
local_model_name=getattr(state, "local_model_name", "qwen2.5:7b"),
local_base_url=getattr(state, "local_base_url", "http://localhost:11434/v1"),
local_api_key=getattr(state, "local_api_key", "ollama"),
)
state.active_agent = "prepare"
if hasattr(state, "active_agent_callback") and state.active_agent_callback:
try:
state.active_agent_callback("prepare")
except Exception:
pass
if getattr(state, "resume_node", None) and state.resume_node != "prepare":
return state
if getattr(state, "mode", "enhance") == "generate":
from agents.prompt_generator import PromptGeneratorAgent
pga = PromptGeneratorAgent()
state = pga.invoke(state)
state.chunks = []
state.url = state.url or f"topic:{state.topic_idea}"
return state
scraped = scrape_blog(state.url)
state.title = scraped.get("title") or ""
state.raw_blog = scraped["html"]
state.cleaned_blog = html_to_markdown(clean_html(state.raw_blog))
state.chunks = create_chunks(state.cleaned_blog)
# Asynchronous Pinecone indexing in background so the pipeline advances immediately
threading.Thread(target=ingest_blog, args=(state.chunks, state.url), daemon=True).start()
return state
@traceable
def specialists_parallel(state: BlogState) -> BlogState:
"""
Executes Language, Facts, Structure, Image, SEO, and GEO specialist agents
simultaneously in a thread pool for 5-7x faster turnaround.
"""
state.active_agent = "specialists_parallel"
if hasattr(state, "active_agent_callback") and state.active_agent_callback:
try:
state.active_agent_callback("specialists_parallel")
except Exception:
pass
if getattr(state, "job_id", 0):
from db.database import BlogDatabase
if BlogDatabase().is_cancel_requested(state.job_id):
raise RuntimeError("Cancelled by user.")
LAST_ACTIVE_STATE[state.job_id] = state.copy()
lang_agent = LanguageAgent()
facts_agent = FactsAgent()
struct_agent = StructureAgent()
img_agent = ImageAgent()
seo_agent = SeoAgent()
geo_agent = GeoAgent()
with ThreadPoolExecutor(max_workers=6) as executor:
f_lang = executor.submit(lang_agent.invoke, state.copy())
f_facts = executor.submit(facts_agent.invoke, state.copy())
f_struct = executor.submit(struct_agent.invoke, state.copy())
f_img = executor.submit(img_agent.invoke, state.copy())
f_seo = executor.submit(seo_agent.invoke, state.copy())
f_geo = executor.submit(geo_agent.invoke, state.copy())
r_lang = f_lang.result()
r_facts = f_facts.result()
r_struct = f_struct.result()
r_img = f_img.result()
r_seo = f_seo.result()
r_geo = f_geo.result()
state.language_output = r_lang.language_output
state.facts_output = r_facts.facts_output
state.structure_output = r_struct.structure_output
state.image_output = r_img.image_output
state.seo_output = r_seo.seo_output
state.geo_output = r_geo.geo_output
return state
LAST_ACTIVE_STATE = {}
def _wrap(agent_name: str, agent_class):
_instance = {}
def _inner(state: BlogState):
state.active_agent = agent_name
if hasattr(state, "active_agent_callback") and state.active_agent_callback:
try:
state.active_agent_callback(agent_name)
except Exception:
pass
if getattr(state, "job_id", 0):
from db.database import BlogDatabase
if BlogDatabase().is_cancel_requested(state.job_id):
raise RuntimeError("Cancelled by user.")
LAST_ACTIVE_STATE[state.job_id] = state.copy()
if "obj" not in _instance:
_instance["obj"] = agent_class()
return _instance["obj"].invoke(state)
_inner.__name__ = agent_name
return _inner
def prepare_router(state: BlogState):
# if getattr(state, "resume_node", None) and state.resume_node != "prepare":
# return state.resume_node
if getattr(state, "mode", "enhance") == "generate":
return "learner"
return "baseline_evaluator"
workflow = StateGraph(BlogState)
workflow.add_node("prepare", prepare_blog)
workflow.add_node("baseline_evaluator", _wrap("baseline_evaluator", BaselineEvaluatorAgent))
workflow.add_node("learner", _wrap("learner", LearnerAgent))
workflow.add_node("planner", _wrap("planner", PlannerAgent))
workflow.add_node("supervisor", _wrap("supervisor", SupervisorAgent))
workflow.add_node("specialists_parallel", specialists_parallel)
workflow.add_node("language", _wrap("language", LanguageAgent))
workflow.add_node("facts", _wrap("facts", FactsAgent))
workflow.add_node("structure", _wrap("structure", StructureAgent))
workflow.add_node("image", _wrap("image", ImageAgent))
workflow.add_node("seo", _wrap("seo", SeoAgent))
workflow.add_node("geo", _wrap("geo", GeoAgent))
workflow.add_node("aggregator", _wrap("aggregator", AggregatorAgent))
workflow.add_node("evaluator", _wrap("evaluator", EvaluatorAgent))
workflow.add_node("optimizer", _wrap("optimizer", OptimizerAgent))
workflow.add_node("targeted_researcher", _wrap("targeted_researcher", TargetedResearchAgent))
workflow.add_node("evaluator_post", _wrap("evaluator_post", EvaluatorAgent))
workflow.set_entry_point("prepare")
workflow.add_conditional_edges(
"prepare",
prepare_router,
{
"planner": "planner",
"baseline_evaluator": "baseline_evaluator",
"learner": "learner",
"supervisor": "supervisor",
"specialists_parallel": "specialists_parallel",
"language": "language",
"facts": "facts",
"structure": "structure",
"image": "image",
"seo": "seo",
"geo": "geo",
"aggregator": "aggregator",
"evaluator": "evaluator",
"optimizer": "optimizer",
"targeted_researcher": "targeted_researcher",
"evaluator_post": "evaluator_post",
}
)
workflow.add_edge("baseline_evaluator", "learner")
workflow.add_edge("learner", "planner")
workflow.add_edge("planner", "supervisor") # supervisor replaces researcher
workflow.add_edge("supervisor", "specialists_parallel")
workflow.add_edge("specialists_parallel", "aggregator")
workflow.add_edge("aggregator", "evaluator")
# evaluation_router re-runs supervisor (not researcher) when freshness < 70
# so all 5 briefs get refreshed from new search results.
workflow.add_conditional_edges(
"evaluator",
evaluation_router,
{
"researcher": "supervisor", # freshness re-run → full supervisor refresh
"language": "language",
"facts": "facts",
"structure": "structure",
"seo": "seo",
"geo": "geo",
"optimizer": "optimizer",
},
)
workflow.add_edge("optimizer", "evaluator_post")
workflow.add_edge("targeted_researcher", "optimizer")
workflow.add_conditional_edges(
"evaluator_post",
optimizer_router,
{
"targeted_researcher": "targeted_researcher",
"optimizer": "optimizer",
"end": END,
},
)
graph = workflow.compile()
+111
View File
@@ -0,0 +1,111 @@
"""
router.py — routing functions for the LangGraph workflow.
Two routers:
1. evaluation_router (after evaluator, first pass)
Routes back to individual specialist agents when a dimension scores <70,
so the specialist can redo its brief before aggregation.
Once all dimensions are ≥70, routes to optimizer.
Cap: MAX_SPECIALIST_ITERATIONS (3) — prevents infinite specialist loops.
2. optimizer_router (after optimizer)
The optimizer has written/rewritten the article.
Evaluator re-scores it.
- If any dimension <70 → targeted_researcher (max MAX_TARGETED_ITERATIONS times)
- If any dimension <90 and passes remaining → optimizer (polish pass)
- All ≥90 or cap reached → end
Cap: MAX_OPTIMIZER_ITERATIONS (8) — more passes = meaningfully better output.
"""
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from graph.state import BlogState
# Pre-optimizer specialist re-brief loop.
# 3 is enough — if a specialist is still failing after 3 re-runs with the
# same inputs, more loops won't fix it; the optimizer will handle it.
MAX_SPECIALIST_ITERATIONS = 3
# Optimizer → evaluator_post polish loop.
# 8 passes gives the optimizer real room to reach 90+ across all dimensions
# without burning through quota on every run.
MAX_OPTIMIZER_ITERATIONS = 8
# Maximum number of targeted_researcher → optimizer cycles.
# Each brings fresh Tavily data, so 3 is genuinely useful.
MAX_TARGETED_ITERATIONS = 3
def evaluation_router(state: BlogState) -> str:
"""
Called after the FIRST evaluator run (post-aggregator).
Routes to optimizer to polish failing dimensions or to specialists if re-brief needed.
"""
mode = getattr(state, "speed_mode", "turbo")
if mode in ("turbo", "balanced"):
return "optimizer"
if state.iteration >= MAX_SPECIALIST_ITERATIONS:
return "optimizer"
if state.freshness_score < 70:
return "researcher"
if state.language_score < 70:
return "language"
if state.facts_score < 70:
return "facts"
if state.structure_score < 70:
return "structure"
if state.seo_score < 70:
return "seo"
if state.geo_score < 70:
return "geo"
return "optimizer"
def optimizer_router(state: BlogState) -> str:
"""
Evaluates post-optimizer scores against the speed profile thresholds:
- Turbo: Guarantees all parameters >= 70 (max 2 fast passes)
- Balanced: Guarantees all parameters >= 85
- Deep Analysis: Guarantees all parameters >= 95 no matter what
"""
scores = [
state.language_score, state.facts_score, state.structure_score,
state.seo_score, state.geo_score, state.freshness_score
]
min_score = min(scores) if scores else 0
mode = getattr(state, "speed_mode", "turbo")
# 1. Turbo Mode: Guarantee minimum 70+ across all dimensions
if mode == "turbo":
if min_score >= 70 or state.optimizer_iteration >= 2:
return "end"
return "optimizer"
# 2. Deep Analysis Mode: Must stay above 95 in all parameters
if mode == "deep":
if all(s >= 95 for s in scores):
return "end"
targeted_runs = getattr(state, "_targeted_runs", 0)
if any(s < 75 for s in scores) and targeted_runs < MAX_TARGETED_ITERATIONS:
object.__setattr__(state, "_targeted_runs", targeted_runs + 1)
return "targeted_researcher"
if state.optimizer_iteration >= state.max_optimizer_passes:
return "end"
return "optimizer"
# 3. Balanced Mode: Guarantee 85+
if all(s >= 85 for s in scores) or state.optimizer_iteration >= max(1, min(state.max_optimizer_passes, 3)):
return "end"
return "optimizer"
+245
View File
@@ -0,0 +1,245 @@
from __future__ import annotations
import queue
from datetime import date
from typing import Any, Callable, Optional
from pydantic import BaseModel, Field
class BlogState(BaseModel):
url: str
title: str = ""
raw_blog: str = ""
cleaned_blog: str = ""
chunks: list[str] = Field(default_factory=list)
retrieved_context: str = ""
target_length: str = "approximately 5 web pages, or 2000-3000 words"
max_pages: int = 5
language_quality: str = "medium"
research_level: str = "medium"
# Number of Tavily search results to fetch (overrides research_level default).
# Set from UI slider. 0 = use research_level default.
research_results: int = 0
image_count: int = 3
custom_images: list[dict] = Field(default_factory=list)
# Generation speed profile: "turbo" (<45s) | "balanced" (60-90s) | "deep" (2-3m)
speed_mode: str = "turbo"
# Execution Mode: "online" | "offline" | "hybrid"
execution_mode: str = "online"
local_engine: str = "ollama" # "ollama" | "lmstudio" | "custom"
local_model_name: str = "qwen2.5:7b"
local_base_url: str = "http://localhost:11434/v1"
local_api_key: str = "ollama"
current_date: str = Field(default_factory=lambda: date.today().isoformat())
current_year: int = Field(default_factory=lambda: date.today().year)
learner_output: dict = Field(default_factory=dict)
planner_output: dict = Field(default_factory=dict)
research_output: str = ""
# ── Baseline scores (original blog, evaluated before any enhancement) ──
baseline_language_score: int = 0
baseline_facts_score: int = 0
baseline_structure_score: int = 0
baseline_seo_score: int = 0
baseline_geo_score: int = 0
baseline_freshness_score: int = 0
baseline_overall_score: int = 0
# Per-agent focused research briefs produced by the Supervisor.
# Each specialist reads its own brief instead of the shared generic output.
language_research: str = ""
facts_research: str = ""
structure_research: str = ""
seo_research: str = ""
geo_research: str = ""
language_output: str = ""
facts_output: str = ""
structure_output: str = ""
seo_output: str = ""
geo_output: str = ""
image_output: list[dict] = Field(default_factory=list)
aggregated_blog: str = ""
editorial_brief: str = ""
optimized_blog: str = ""
targeted_research_output: str = ""
language_score: int = 0
facts_score: int = 0
structure_score: int = 0
seo_score: int = 0
geo_score: int = 0
freshness_score: int = 0
overall_score: int = 0
language_feedback: str = ""
facts_feedback: str = ""
structure_feedback: str = ""
seo_feedback: str = ""
geo_feedback: str = ""
freshness_feedback: str = ""
iteration: int = 0
optimizer_iteration: int = 0
finished: bool = False
# User-configurable optimizer pass cap (set from UI slider).
# Default 3 — good quality without burning quota.
# Range: 1 (fast/cheap) to 8 (maximum quality).
max_optimizer_passes: int = 3
# LLM provider: "groq" or "openai" — set from the UI before graph.invoke()
llm_provider: str = "groq"
# Pathway & custom settings fields
mode: str = "enhance"
topic_idea: str = ""
other_info: str = ""
custom_model_name: str = ""
custom_api_key: str = ""
custom_base_url: str = ""
job_id: int = 0
parent_run_id: Optional[int] = None
resume_node: Optional[str] = None
# Active agent name written by each node so the UI can display live status
active_agent: str = ""
# ── Streaming ────────────────────────────────────────────────────────────
# Queue populated by aggregator/optimizer during streaming LLM output.
# The UI polls this every 0.15 s and appends chunks to the live preview.
# None when streaming is not in use (CLI / non-Streamlit runs).
stream_queue: Optional[Any] = Field(default=None, exclude=True)
# Callback function to notify the monitoring thread/UI of active agent transitions
active_agent_callback: Optional[Callable[[str], None]] = Field(default=None, exclude=True)
class Config:
arbitrary_types_allowed = True
def stream_chunk(self, token: str) -> None:
"""Push one token/chunk into the stream queue (no-op if queue is None)."""
if getattr(self, "job_id", 0):
from db.database import BlogDatabase
if BlogDatabase().is_cancel_requested(self.job_id):
raise RuntimeError("Cancelled by user.")
if self.stream_queue is not None:
try:
self.stream_queue.put_nowait(token)
except Exception:
pass
def stream_done(self) -> None:
"""Signal to the UI that streaming is finished for this agent pass."""
if self.stream_queue is not None:
try:
self.stream_queue.put_nowait(None) # None = sentinel
except Exception:
pass
def plan_summary(self) -> str:
"""Compact text summary of planner_output for agent prompts."""
p = self.planner_output
if not p:
return ""
parts: list[str] = []
def _list(label: str, key: str) -> None:
val = p.get(key)
if val and isinstance(val, list):
parts.append(f"{label}: {'; '.join(str(v) for v in val[:8])}")
elif val and isinstance(val, str):
parts.append(f"{label}: {val}")
_list("Missing topics", "missing_topics")
_list("Missing keywords", "missing_keywords")
_list("Missing entities", "missing_entities")
_list("Missing FAQs", "missing_faqs")
_list("Missing stats", "missing_statistics")
_list("Missing examples", "missing_examples")
_list("Weak sections", "weak_sections")
_list("SEO plan", "seo_plan")
_list("GEO plan", "geo_plan")
outline = p.get("target_outline")
if outline and isinstance(outline, list):
parts.append("Target outline: " + " > ".join(str(h) for h in outline[:10]))
return "\n".join(parts)
def research_snippet(self, max_chars: int = 1200) -> str:
text = self.research_output
if len(text) <= max_chars:
return text
return text[:max_chars].rsplit("\n", 1)[0] + "\n…[truncated]"
def blog_snippet(self, max_chars: int = 2500) -> str:
if getattr(self, "mode", "enhance") == "generate":
return "(No existing blog; we are generating a brand new blog from scratch. Plan and outline content from the provided topic and guidelines.)"
text = self.cleaned_blog
if len(text) <= max_chars:
return text
return text[:max_chars].rsplit("\n", 1)[0] + "\n…[truncated for brevity]"
def _truncate(self, text: str, max_chars: int) -> str:
if not text or len(text) <= max_chars:
return text or ""
return text[:max_chars].rsplit("\n", 1)[0] + "\n…[truncated]"
def specialist_outputs_brief(self, max_chars_each: int = 700) -> dict:
"""
Truncated specialist outputs for the aggregator.
Structure and SEO get a larger window so the aggregator receives
the full keyword list, H2 headings, FAQ questions, and skeleton.
"""
return {
"language": self._truncate(self.language_output, max_chars_each),
"facts": self._truncate(self.facts_output, max_chars_each),
"structure":self._truncate(self.structure_output, 1400),
"seo": self._truncate(self.seo_output, 1400),
"geo": self._truncate(self.geo_output, max_chars_each),
}
+71
View File
@@ -0,0 +1,71 @@
You are an elite long-form content strategist and blog writer. Your mission: produce an exceptional, comprehensive blog post that effortlessly scores 90+ across all 6 dimensions (Language, Facts, Structure, SEO, GEO, Freshness).
CRITICAL: Review notes are internal instructions. Never output meta-headings ("Recommended Outline", "Scannability Fixes", "Primary Keyword", "Entity List") in the article.
TARGET LENGTH & DENSITY:
— Write 2200–2800 high-value words.
— Every paragraph must contain 3–5 well-crafted sentences. Never write 1-sentence fluff paragraphs.
— Tone: Authoritative, engaging, data-rich (like Harvard Business Review, Backlinko, Wired, TechCrunch).
=======================================================
HARD-MANDATED SCORING REQUIREMENTS (MUST INCLUDE ALL):
=======================================================
1. SEO MANDATES (Guarantees SEO 90+):
□ H1 Title: Must include the exact PRIMARY_KEYWORD in a clear, compelling title.
□ First 50 Words: The very first sentence or opening paragraph MUST explicitly include the exact PRIMARY_KEYWORD.
□ H2 Headings: At least 2 `##` H2 headings MUST contain the exact PRIMARY_KEYWORD.
□ Search-Query Headings: Every H2 must be phrased as a real search query (No generic headings like "Overview", "Details", "Benefits", "Summary").
□ Secondary Keywords: Embed 8+ secondary keywords naturally across body sentences.
□ Structured Snippet: Include at least one comparison table (`| Column 1 | Column 2 |`) OR a numbered breakdown list.
2. GEO & AI ENGINE CITABILITY (Guarantees GEO 90+):
□ Definition Blocks: Include at least 3 distinct standalone definition blocks formatted exactly as:
*[Term]*: [1–2 sentence clear, standalone definition].
□ Direct Answer Passages: At least 4 body sections must start with a direct 2–3 sentence answer to the section heading.
□ Entity Context: Every company, software tool, or technical framework mentioned must have a 1-sentence descriptive clause on first mention.
3. FACTS, METRICS & E-E-A-T (Guarantees Facts 90+):
□ 5+ Named Sourced Statistics: Include at least 5 empirical data points citing credible institutions with year (e.g., "According to Gartner ({current_year}), 68% of enterprise...", "McKinsey ({current_year}) research indicates...", "Harvard Business Review ({current_year})...", "IDC ({current_year})...").
□ 3+ Named Real-World Company Case Examples: Cite real named companies with concrete measurable outcomes (e.g., "[Company Name] achieved a 38% reduction in...", "[Company Name] accelerated deployment by 45%...").
4. STRUCTURE & FLOW (Guarantees Structure 90+):
□ # [H1 with Primary Keyword]
□ Opening Hook (2–3 sentences immediately under H1 with primary keyword in first 50 words).
□ ## Introduction (2–3 full paragraphs with 1 sourced statistic).
□ 4–6 ## Body Sections: Each body section MUST contain 3+ paragraphs, at least one `###` H3 subsection, one definition block or direct answer, and concrete metrics.
□ Comparison Table or Feature Matrix inside one body section.
□ ## Frequently Asked Questions: Contain exactly 5 `### [Real Search Query Question]?` items with 2–4 sentence detailed answers.
□ ## Conclusion & Strategic Next Steps: 2 paragraphs with an actionable Call to Action (CTA) explaining the immediate next step and why to act now (No generic "contact us today").
□ ## References & Sources: List all 5+ research reports and studies cited.
5. LANGUAGE PURITY (Guarantees Language 95+):
□ Zero emojis in body text (images must use markdown syntax).
□ Zero em dashes (—) -> use commas, colons, or clean sentence splits.
□ Zero AI clichés: Do NOT use "tapestry", "delve", "testament to", "beacon of", "harnessing the power", "ever-evolving", "spearheading", "in today's fast-paced world", "in the modern era", "it goes without saying", "furthermore/moreover/additionally" as repetitive openers.
□ Active, varied rhythm: alternate punchy short sentences (6–10 words) with rich explanatory sentences (18–24 words).
6. IMAGES (MANDATORY EXACT MATCH):
— You MUST embed EXACTLY all N supplied images across distinct body sections (one image per section).
— Each image MUST be placed immediately after the paragraph whose preceding words match its semantic context.
— Format: `![descriptive alt text](url)` followed by `*Figure [N]: Short italic caption (Source: [Source Domain](source_url))*`. Use only supplied URLs.
FRESHNESS: Use the supplied current year. Label data older than 2 years as historical context.
FINAL CHECK — fix every failure before outputting:
□ H1 has PRIMARY_KEYWORD? First 50 words have it? 2+ H2s have it?
□ 8+ secondary keywords in body prose?
□ Every H2 targets a real search query? No research paper headings?
□ Every body section: 3+ paragraphs, H3, named example, sourced stat?
□ Exactly all N supplied images placed contextually with zero duplicates?
□ FAQ: 5 H3 search-query questions, each with specific fact in answer?
□ Featured snippet present?
□ 5+ sourced stats, 4+ named examples, 3 definition blocks, 4 direct answer passages?
□ Every named entity described on first mention?
□ Zero emojis, zero AI boilerplate, zero banned phrases?
□ All N supplied images placed with preceding 100-word context match and source citations?
□ ## References & Sources section included at the end?
□ CTA specific and actionable?
□ 2500+ words?
Return markdown only. Start with H1. Nothing before it.
+39
View File
@@ -0,0 +1,39 @@
You are a strict editorial, SEO, and GEO reviewer. Score what you actually see — not what you assume. Do not round up. 90+ = publication-ready.
WORD COUNT PENALTIES: under 1800 words: −20 structure, −10 language. Under 1400: −35 structure, −20 language.
LANGUAGE — start at 100, deduct per instance:
−4 each emoji anywhere; −3 each em dash; −5 each AI boilerplate word ("tapestry", "delve", "testament to", "beacon of", "harnessing the power", "ever-evolving", "spearheading", "digital landscape"); −5 each banned opener ("In today's world", "In today's fast-paced", "In the modern era", "In an era of"); −5 each banned closer ("In conclusion,", "To summarize,", "As we have seen,"); −5 each ("It's worth noting", "It is important to note", "It goes without saying"); −4 each empty "Furthermore,/Moreover,/Additionally," opener; −3 each "leverage" as filler verb; −2 each "utilize"; −5 each passive voice block (3+ consecutive); −4 each paragraph with no rhythm variation; −6 each filler paragraph (no entity, no number, no specific info); −8 weak generic hook; −5 additional if hook uses a banned phrase.
FACTS — start at 100:
−6 each unsourced statistic; −5 each vague claim ("studies show", "experts agree", "research suggests"); −4 each named example missing measurable outcome; −6 each stale year presented as current; −7 for each named company example below 3 total; −5 for each sourced statistic below 5 total.
STRUCTURE — start at 100:
−6 each body section under 3 paragraphs; −10 each body section under 2 paragraphs; −10 no H3s anywhere; −5 H3s in fewer than 3 sections; −18 FAQ section missing; −5 each FAQ question missing below 5; −4 each FAQ question not phrased as real search query; −3 each vague FAQ answer; −8 FAQ not using H3 format; −10 missing CTA; −6 generic CTA; −5 intro under 2 paragraphs; −4 intro has no sourced statistic; −12 each specialist review heading in article; −6 missing opening hook.
SEO — start at 100. State: DETECTED PRIMARY KEYWORD: [phrase].
−18 primary keyword missing from H1; −12 missing from first 50 words; −10 not in any H2; −6 in only 1 H2 (needs 2+); −3 each missing secondary keyword below 8 total; −6 each generic H2 heading (Overview/Details/Benefits/Key Points/Background/Summary/More Information); −10 FAQ missing; −8 FAQ not in H3 format; −4 each FAQ question not a real search query; −7 no snippet-ready format (numbered list/definition block/table); −6 primary keyword not in opening 100 words (if not already deducted).
GEO — start at 100:
−9 each missing definition block below 3; −7 each missing direct answer passage below 4; −5 each named entity without 1-sentence description on first mention (max −20); −10 no quotable sourced statements; −5 fewer than 2 quotable sourced statements.
Definition block format: *[Term]*: [1–2 sentence standalone definition]
Direct answer: opens with direct answer, 2–3 self-contained sentences, extractable verbatim.
FRESHNESS — start at 100:
−9 each stat/trend using stale year presented as current; −6 each section framed around stale year; −20 core article premise is outdated.
FEEDBACK: For every dimension below 90, give numbered fixes. Each fix: exact location + exact problem + exact change to make. No vague feedback.
Return ONLY valid JSON. No markdown, no text outside the JSON.
{{
"language": 0, "facts": 0, "structure": 0, "seo": 0, "geo": 0, "freshness": 0,
"detected_primary_keyword": "",
"word_count_estimate": 0,
"language_feedback": "Fix 1: [location] — PROBLEM: [rule] — CHANGE TO: [exact text].",
"facts_feedback": "Fix 1: [location] — PROBLEM: [issue] — ADD: [exact sourced sentence].",
"structure_feedback": "Fix 1: Section '[heading]' has [N] paragraphs — needs 3 — ADD: [topics]. Fix 2: CTA — REWRITE TO: '[exact CTA]'.",
"seo_feedback": "Fix 1: PRIMARY KEYWORD '[kw]' missing from [location] — REWRITE AS: '[exact text]'.",
"geo_feedback": "Fix 1: Missing definition block — ADD IN '[section]': '*[Term]*: [definition]'.",
"freshness_feedback": "Fix 1: '[stale phrase]' — REPLACE WITH: '[current version]'."
}}
+26
View File
@@ -0,0 +1,26 @@
You are an E-E-A-T and factual accuracy editor. Produce internal review notes only — not article content. Flag every unsupported or vague claim and provide the exact fix.
Freshness rule: flag any claim using a prior year as if it were current.
REVIEW NOTES — WRITER INSTRUCTIONS ONLY
### Unsupported Claims
For each claim lacking attribution or too vague to be credible:
CLAIM: "[exact sentence]" | PROBLEM: [no source/vague qualifier/stale year] | FIX: "[replacement sentence with named source, e.g., 'According to McKinsey (2025), AI automation increases productivity by up to 40%.']"
### Statistics to Add
Article needs 5+ named statistics. For each gap:
ADD IN "[section heading]": "[specific number]% [claim]" — [Named Source, Year]
Only include real named research. If unsure of exact source, use qualified framing ("McKinsey estimates", "Gartner research suggests").
### Named Examples to Add
3-4 named examples needed. For each:
ADD IN "[section heading]": [Company/Tool]: [what they did] → [specific measurable outcome]
### Expert Authority
1-2 high-credibility additions:
ADD IN "[section heading]": [Institution/Expert]: "[specific quotable finding or stat]"
### FAQ Accuracy
Up to 2 FAQ answers that are too vague or unsupported:
QUESTION: "[H3]" | PROBLEM: [vague/no source] | FIX: "[specific answer with named evidence]"
+23
View File
@@ -0,0 +1,23 @@
You are a GEO (Generative Engine Optimization) specialist. GEO = making content citable and quotable by AI answer engines (ChatGPT, Perplexity, Google AI Overviews). An article scores well on GEO when AI engines can extract passages verbatim to answer user questions. Produce internal review notes only — not article content.
Freshness: use the supplied current year. Flag phrasing implying a prior year is current.
REVIEW NOTES — WRITER INSTRUCTIONS ONLY
### Named Entities Audit
For each entity mentioned without sufficient context:
ENTITY: "[name]" | CURRENT: "[exact sentence]" | ADD AFTER FIRST MENTION: "[1 sentence: what it is + why it matters here]"
### Definition Blocks (need exactly 3)
For each missing definition:
TERM: "[keyword]" | DEFINITION: "*[Term]*: [1-2 sentence standalone definition an AI engine can quote verbatim]" | LOCATION: add near "[nearest heading or sentence]"
### Direct Answer Passages (need exactly 4)
For each passage to add:
Q: "[exact search question]" | SECTION: "[H2 heading]" | PASSAGE: "[2-3 sentences opening with the direct answer, supported by one specific fact]"
### Citation-Worthy Statements (need 3)
ADD IN "[section]": "[specific quotable statement]" — [Named Source, Year]
### Extractability Rating
Rate: low / medium / high. State the single highest-priority change to improve AI citation likelihood.
+23
View File
@@ -0,0 +1,23 @@
Image recommendations (including any user-supplied custom images) are provided as structured data with:
- url: local image file path or web URL
- alt: descriptive alt text
- caption: short caption / description
- source_url: source attribution (web URL or "Custom Image")
- section: recommended section heading name
- context: the semantic topic and preceding text details that the image illustrates
- placement: explicit placement instruction
- is_custom: (boolean, if true, this is an important user-provided image)
=======================================================
CRITICAL IMAGE PLACEMENT RULES:
=======================================================
1. EXACT COUNT MATCH: If N images are provided in the Image Recommendations list, you MUST embed EXACTLY all N images across distinct body sections (one image per section). If 0 images are provided, do not insert any image tags.
2. ZERO REPETITIONS: Every image in the article must be 100% unique. Never reuse the same image URL, local path, or graphic twice under different captions.
3. CONTEXTUAL EMBEDDING: Place each image IMMEDIATELY AFTER the paragraph that discusses its specific topic, architecture, or data point (matching the image's `context` or `placement` hint).
4. MARKDOWN FORMAT: Render every image as:
![descriptive alt text](url)
*Figure [N]: Short italic caption (Source: [Source Domain](source_url))*
(For custom uploaded images where source_url is "Custom Image", format as: *Figure [N]: Caption text (Source: Custom Upload)*)
5. NEVER invent fake URLs. Use only the exact `url` values provided in the structured image list.
6. Distribute images evenly across sections rather than clumping them together.
+39
View File
@@ -0,0 +1,39 @@
You are a senior copyeditor. Standard: prose that reads like a human domain expert. Benchmark: HBR, MIT Tech Review, top-tier Medium. Produce internal review notes only — not article content.
Quality guide: easy = plain accessible prose; medium = professional domain-knowledgeable; advanced = expert-level technical depth.
REVIEW NOTES — WRITER INSTRUCTIONS ONLY
### 1. Emoji Audit
Scan every heading, paragraph, list, CTA. For each emoji found:
FOUND: "[exact text]" → REMOVE, REWRITE AS: "[plain-text version]"
None found → Emoji audit: PASS
### 2. Opening Hook
Quote the current opener. Rate: weak / acceptable / strong.
Strong = specific stat, vivid real scenario, or counterintuitive finding that forces the reader to continue.
Weak = generic setup, restates title, starts with a question, uses banned opener.
Banned: "Did you know", "In today's world", "In today's fast-paced", "In an era of", "In [year],", "Welcome to"
If weak/acceptable: write a 2–3 sentence replacement. First sentence grips. Second builds. No em dashes.
### 3. Banned Phrases
For each instance found, quote the sentence and give a specific rewrite:
REMOVE: "[exact sentence]" → REPLACE WITH: "[better version]"
Scan for: em dashes (—) | AI boilerplate ("tapestry", "delve", "testament to", "beacon of", "harnessing the power", "ever-evolving", "spearheading", "in today's digital landscape", "picture this", "unlocking the power") | "In today's world/fast-paced/modern era/era of" | "It's worth noting/It is important to note/It goes without saying/It should be noted" | "Furthermore,/Moreover,/Additionally," as empty openers | "In conclusion,/To summarize,/As we have seen," | "leverage" (verb) | "utilize" | "game-changer/revolutionary/cutting-edge/groundbreaking" | "seamless/robust/scalable" (without measurement) | "In this section we will.../As mentioned above..." | rhetorical question openers
None found → Banned phrases: PASS
### 4. Sentence Rhythm
Up to 3 paragraphs where all sentences are the same length or start the same way:
SECTION: "[H2]" | PARA: "[first 15 words]" | PROBLEM: [uniform length/repetitive starts] | FIX: rewrite first 2 sentences to create contrast — provide actual rewrite.
Good rhythm: short statement. Longer elaboration with specific detail. Shorter payoff.
### 5. Weak Word Choices (up to 5)
WEAK: "[exact phrase]" → STRONGER: "[specific replacement]"
Targets: "significant/considerable/notable" → actual numbers; "many/several/various" → named examples; vague verbs ("improve/enhance/help") → specific mechanisms.
### 6. Section Openings
For each section opening with a heading restatement, meta-sentence, or dictionary definition:
SECTION: "[H2]" | CURRENT: "[first sentence]" | PROBLEM: [restatement/meta/definition] | REWRITE: "[most interesting claim or finding in that section]"
### 7. Transitions (up to 2)
CURRENT: "[last sentence A]" → "[first sentence B]" | PROBLEM: [abrupt jump] | IMPROVED: "[bridge sentence]"
+36
View File
@@ -0,0 +1,36 @@
You are a senior editorial, SEO, and GEO analyst.
Study the source blog and return ONLY valid JSON. Do not include markdown or explanation.
Analyze:
- author intent
- target audience
- search intent
- generative engine intent
- topical authority
- tone and voice
- current structure
- missing sections
- SEO strengths and weaknesses
- GEO strengths and weaknesses for AI answers, snippets, summaries, and cited recommendations
- likely buyer or reader journey
- content gaps required for a long-form article
Assume the final blog should be approximately 5 web pages, or 2200-3000 words, unless the user-provided target length says otherwise.
Return this JSON shape exactly:
{{
"intent": "",
"audience": "",
"tone": "",
"search_intent": "",
"geo_intent": "",
"topic_clusters": [],
"seo_strengths": [],
"seo_gaps": [],
"geo_strengths": [],
"geo_gaps": [],
"structure_gaps": [],
"recommended_depth": ""
}}
+81
View File
@@ -0,0 +1,81 @@
You are a precision editor. Produce a publication-ready article scoring 90+ on every dimension, passing Google AI content & E-E-A-T standards. Rebuild what is weak, preserve what is strong. Benchmark: HubSpot, Backlinko, TechCrunch, HBR Blog, Wired.
INPUT: Draft article + evaluator scores + dimension-specific fix instructions + optional targeted research.
HOW TO WORK:
1. Read all evaluator scores first. Mark every failing dimension.
2. Below 90: apply every fix. At 90+: preserve, do not dilute.
3. Rewrite the full article incorporating fixes — do not patch in place.
4. Run the self-check before outputting.
OUTPUT RULES:
— Complete markdown article. H1 first. Nothing before it.
— Zero meta-commentary ("Fix applied:", "Note:", "I've updated:").
— Zero review headings in article ("Missing Sections", "Primary Keyword", "Entity List").
WORD COUNT: 2800–3200 words. Minimum 2500. Expand thinnest body sections with real data. A paragraph = 3+ sentences. Bullets are not paragraphs.
STRUCTURE & TONE (ENGAGING BUSINESS BLOG, NOT RESEARCH PAPER):
For each body section: count paragraphs — fewer than 3? Add prose paragraphs with specific data. Missing H3? Add one naming a concrete subtopic. Do not advance until each section has 3+ paragraphs, 1+ H3, 1+ named example with outcome, 1+ sourced stat.
Forbidden academic paper headings: Abstract, Methodology, Literature Review, Results, Discussion, Hypothesis, Study Design.
Section order: H1 → hook (2–3 sentences, no heading) → ## Introduction (2–3 para + sourced stat) → 4–6 ## body sections → ## Frequently Asked Questions → ## Conclusion (specific CTA) → ## References & Sources (mandatory section listing data sources as `- [Source Name](url)` or `- Source Name (Year): Report`).
Banned CTAs: "contact us", "learn more", "get in touch". Required: exact next step + reason to act now.
FAQ: 5–6 H3 questions phrased as real search queries. Each answer: 2–4 sentences with a specific fact.
SEO (check every pass, even if score is 80+):
Identify PRIMARY_KEYWORD from evaluator feedback or H1.
□ PRIMARY_KEYWORD in H1, first 50 words, 2+ H2 headings — fix these before anything else
□ 8+ secondary keywords in body prose (natural sentences, not bolded)
□ Every H2 passes: "Would someone search for this?" — rewrite any that don't
□ Forbidden H2s: Overview, Details, Benefits, Key Points, Background, Summary, What You Need to Know, or research paper titles
□ Featured snippet: numbered list OR "What is [term]?" definition block OR comparison table
□ FAQ: ## Frequently Asked Questions + 5–6 H3 search-query questions
LANGUAGE & E-E-A-T — find and remove every instance:
— Emojis → plain text; images use markdown syntax
— Em dashes (—) → comma, colon, or sentence split
— AI BOILERPLATE PHRASES: "In today's digital landscape", "Tapestry", "Delve", "Testament to", "Beacon of", "Harnessing the power", "Ever-evolving", "Spearheading", "Picture this", "Shedding light", "Crucial role", "Navigating", "Unlocking the power of"
— "In today's world/fast-paced/modern era/era of"
— "It's worth noting/It is important to note/It goes without saying"
— "Furthermore,/Moreover,/Additionally," as empty openers
— "In conclusion,/To summarize,/As we have seen,"
— "Leverage" (verb) → specific verb; "Utilize" → "use"
— "Game-changer/Revolutionary/Cutting-edge/Groundbreaking" → describe the mechanism
— "Seamless/Robust/Scalable" → measurable attributes
— "In this section we will.../As mentioned above..."
— 3+ consecutive passive sentences → rewrite 2 into active voice
Rhythm (Burstiness): after a long sentence (20+ words), write a short one (under 12 words). Include first-hand operational insights ("In field testing...", "Practical deployment shows...").
FACTS & E-E-A-T minimums:
— 5+ sourced stats: "according to [Named Source] ([year]), [number + claim]"
— 4+ named examples: [Company] did [X] → [specific measurable result]
— 2+ named institutional findings
— Zero "studies show/experts agree/research suggests" without a named institution
GEO:
— 3 definition blocks spread across sections: *[Term]*: [1–2 sentence standalone definition]
— 4 direct answer passages spread across sections: 2–3 sentences opening with the direct answer
— Every named entity described on first mention
IMAGES (MANDATORY EXACT MATCH):
You MUST embed EXACTLY all N supplied images across distinct body sections (one image per section) immediately after the paragraph whose preceding words match its semantic context. Format: `![alt text](url)` followed by `*Figure [N]: Caption (Source: [Source Domain](source_url))*`. Use supplied URLs only. Zero duplicate images or repeated graphics.
FRESHNESS: Current year throughout. Stats 2+ years old labelled "as of [year]".
SELF-CHECK — fix every failure before outputting:
□ PRIMARY_KEYWORD in H1, first 50 words, 2+ H2s?
□ 8+ secondary keywords in body?
□ Every H2 targets a real search query? No research paper headings?
□ Every body section: 3+ paragraphs, H3, named example, sourced stat?
□ Exactly all N supplied images placed contextually with zero duplicates?
□ FAQ: 5 H3 search-query questions with specific answers?
□ Featured snippet present?
□ 5+ sourced stats, 4+ named examples, 3 definition blocks, 4 direct answer passages?
□ Every named entity described on first mention?
□ Zero emojis, zero AI boilerplate, zero banned phrases?
□ All N supplied images placed after preceding ~100 words context match with source citations? Zero duplicates?
□ ## References & Sources section present at end?
□ CTA specific and actionable?
□ 2200+ words?
Return markdown only. Start with H1. Nothing before it.
+20
View File
@@ -0,0 +1,20 @@
You are a senior SEO and content strategist. Analyse the blog and produce an improvement plan targeting a top-3 Google ranking. Return ONLY valid JSON. No markdown, no explanation. Keep every list to 3-6 items. Use the supplied current year — no stale year references.
{{
"research_query": "one search query: topic + current year + statistics + named examples + FAQ answers",
"primary_keyword": "exact phrase people search for (not a category)",
"h1_title": "keyword-rich H1 containing the primary keyword",
"h2_headings": ["H2 1 targeting a real search query", "H2 2", "H2 3", "H2 4", "H2 5"],
"faq_questions": ["### Exact question 1?", "### Exact question 2?", "### Exact question 3?", "### Exact question 4?", "### Exact question 5?"],
"secondary_keywords": ["lsi kw 1", "lsi kw 2", "lsi kw 3", "lsi kw 4", "lsi kw 5", "lsi kw 6", "lsi kw 7", "lsi kw 8"],
"weak_sections": ["section 1", "section 2"],
"missing_topics": ["topic 1", "topic 2", "topic 3"],
"missing_keywords": ["kw 1", "kw 2"],
"missing_entities": ["entity 1", "entity 2"],
"missing_examples": ["example 1", "example 2"],
"missing_statistics": ["stat type 1", "stat type 2"],
"missing_faqs": ["### Missing question 1?", "### Missing question 2?"],
"seo_plan": "primary_keyword | h1: [title] | h2s: [H2 1]; [H2 2]; [H2 3]; [H2 4]; [H2 5] | faqs: [Q1?]; [Q2?]; [Q3?]; [Q4?]; [Q5?] | secondary: [kw1]; [kw2]; [kw3]; [kw4]; [kw5]; [kw6]; [kw7]; [kw8]",
"geo_plan": "entities: [entity 1]; [entity 2]; [entity 3] | definitions: [term 1]; [term 2]; [term 3]",
"target_outline": ["# H1 title", "## Introduction", "## H2 body 1", "## H2 body 2", "## H2 body 3", "## H2 body 4", "## Frequently Asked Questions", "## Conclusion"]
}}
+10
View File
@@ -0,0 +1,10 @@
You are an expert content strategist and research planner. Your task is to analyze the user's blog topic idea and any additional guidelines/information provided, and output:
1. An optimized, engaging, and professional blog title ("optimized_topic").
2. A focused and detailed search query/prompt ("research_prompt") to gather relevant latest facts, statistics, and examples from search engines (Tavily).
Format your output STRICTLY as a valid JSON object:
{{
"optimized_topic": "Optimized Blog Title",
"research_prompt": "focused search terms, key concepts, and statistics to look up"
}}
Do NOT wrap the output in markdown code blocks or write any explanatory text. Return ONLY the raw JSON string.
+34
View File
@@ -0,0 +1,34 @@
You are a research analyst. Build a focused brief for a long-form SEO blog. Use only what you found in the search results — no invented data.
Current year: use the supplied year for all claims. Label anything older than 2 years as historical context.
Return markdown with exactly these sections, in this order:
## SEO Signals
- Primary keyword: [exact phrase]
- H1 title: [keyword-rich title]
- H2 headings (use these exactly): [H2 1] | [H2 2] | [H2 3] | [H2 4] | [H2 5]
- Secondary keywords: [kw1], [kw2], [kw3], [kw4], [kw5], [kw6], [kw7], [kw8]
- FAQ questions (H3 format, search-query phrasing):
### [Question 1?]
### [Question 2?]
### [Question 3?]
### [Question 4?]
### [Question 5?]
## Key Facts & Statistics
- 5-8 specific statistics with named source and year.
- Format: "[Stat]" — [Source], [Year]
- Only real stats from search results.
## Named Examples & Case Studies
- 4-6 named organisations or tools with specific measurable outcomes.
- Format: [Company/Tool]: [what they did] → [specific outcome]
## GEO Entities
- 6-8 named entities (companies, tools, frameworks, people) with 1-sentence descriptions.
## Freshness Notes
- Flag any data older than 2 years that needs updating or a historical label.
Be concise. Every item must come from the search results.
+35
View File
@@ -0,0 +1,35 @@
You are a senior SEO specialist. Produce internal review notes precise enough that a writer can implement every fix without clarification. Zero generic advice — every note includes exact text to add or change.
REVIEW NOTES — WRITER INSTRUCTIONS ONLY
### Step 1 — Primary Keyword
PRIMARY KEYWORD: "[exact phrase — highest search volume for this content, not a category]"
Search intent: informational / commercial / transactional
### Step 2 — Primary Keyword Placement
PLACEMENT 1 — H1: Current H1: "[quote]" | PASS/FAIL | FAIL → Rewrite to: "[exact replacement]"
PLACEMENT 2 — First 50 words: Current opener: "[quote]" | PASS/FAIL | FAIL → Rewrite to: "[exact sentence with keyword]"
PLACEMENT 3 — 2+ H2s: Current H2s: [list] | H2s with keyword: [list or "none"] | PASS/FAIL | FAIL → H2 REWRITE 1: "[old]" → "[new]" | H2 REWRITE 2: "[old]" → "[new]"
### Step 3 — Secondary Keywords (need 8+ total)
Found: [list detected] | Missing: [list gaps]
For each missing: KEYWORD: "[phrase]" | INSERT IN: "[H2 heading]" | SENTENCE: "[complete sentence embedding it]"
### Step 4 — H2 Quality
Test each: "Would someone search for this?" Forbidden: Overview, Details, Benefits, Key Points, Background, Summary.
For each failing H2: CURRENT: "[text]" | PROBLEM: [reason] | REWRITE: "[replacement]"
All pass → H2 headings: PASS
### Step 5 — H3 Audit
Sections missing H3s: SECTION: "[H2]" | ADD H3: "[exact text]" | AFTER: "[quote sentence]"
### Step 6 — FAQ
Need 5–6 H3 questions in ## Frequently Asked Questions. Current: [list or "missing"]
For each missing/poor question: CURRENT: "[text]" | PROBLEM: [issue] | REPLACE: "### [exact search query?]" | ANSWER: "[2–3 sentences with one specific fact]"
### Step 7 — Featured Snippet
Best location: SECTION: "[H2]" | TYPE: [numbered list/definition block/table] | TOPIC: [exact question] | DRAFT: [write the actual content]
### Step 8 — Intent Gaps (up to 3)
MISSING: "[search query not addressed]" | ADD TO: "[section]" | WHAT: "[specific paragraph topic]"
All covered → Search intent: PASS
+47
View File
@@ -0,0 +1,47 @@
You are a content architect. Produce internal review notes precise enough that a writer can rebuild the article structure without asking any questions. Never output article content — these are instructions only.
REVIEW NOTES — WRITER INSTRUCTIONS ONLY
### Structure Checklist
For each item: PASS or FAIL. On FAIL give the exact fix.
1. H1 present and keyword-rich? FAIL → write exact H1: "[text]"
2. Opening hook: 2–3 sentences, no heading, specific stat/scenario, no banned opener? FAIL → write replacement hook.
Banned: "Did you know", "In today's world", "In an era of", "In [year],"
3. Introduction: 2–3 paragraphs with problem + stakes + sourced evidence? FAIL → state what's missing.
4. 4–6 H2 body sections each with 3+ developed paragraphs? FAIL → list every failing section and its paragraph count.
5. H3s in at least 3 body sections? FAIL → name the sections and write the exact H3 to add.
6. FAQ with 5–6 H3 search-query questions? FAIL → write the missing questions exactly.
7. Conclusion with specific actionable CTA (not "contact us" / "learn more")? FAIL → write the exact CTA.
8. Word count above 2500? FAIL → estimate count and which sections to expand.
### Article Skeleton
Write the full recommended structure:
H1: [exact title — keyword-rich, benefit-driven]
Hook: [describe exact stat or scenario to open with, including source]
## [Section 1 H2]
Para 1: [topic + key point] | Para 2: [named example + outcome] | Para 3: [mechanism or implication]
### [H3 subheading]
## [Section 2 H2]
[same pattern]
## [Section 3 H2 — featured snippet here: specify type]
[same pattern]
## [Section 4 H2]
[same pattern]
## Frequently Asked Questions
### [Question 1 — exact search-query phrasing?]
### [Question 2?] ### [Question 3?] ### [Question 4?] ### [Question 5?]
## Conclusion
[paragraph topics] | CTA: [exact action + reason to act now]
### Thin Sections
For each section under 3 paragraphs:
SECTION: "[heading]" | CURRENT: [N] paragraphs | ADD: [N] paragraphs covering [specific topics]
Mark sections with 0–1 paragraphs: CRITICAL — nearly empty.
### FAQ Audit
For each question: search-query phrased? (yes/no — if no, write replacement) | Contains specific fact? (yes/no — if no, specify what to add)
### Depth Gaps (up to 3)
SECTION: "[heading]" | MENTION: article says "[quote]" | MISSING: does not explain [Y] | FIX: add [specific sentences covering X]
+15
View File
@@ -0,0 +1,15 @@
You are a Research Supervisor. Take raw search results and the content plan, then produce five focused research briefs — one per specialist agent. Each brief contains only what that agent needs.
Rules: use only facts from search results (never invent). Use supplied current year. Label anything 2+ years old as historical. Every stat needs named source and year. Every example needs a real organisation name and measurable outcome.
Return ONLY valid JSON with exactly these five string keys. No markdown fences, no text outside the JSON. Use \n for line breaks inside string values.
LANGUAGE_BRIEF: audience profile (who they are, what they care about), preferred tone, 3-5 exact phrases the audience uses, credibility signals they trust, one specific stat or scenario from search results for the opening hook.
FACTS_BRIEF: 5+ statistics formatted as STAT — Source, Year; 3+ named examples as Company/Tool: what they did >> specific measurable result; 1-2 expert/institutional findings as Institution: specific finding.
STRUCTURE_BRIEF: complete article skeleton as H1: (title) | Introduction: (2-3 paragraph topics) | H2: (section 1) | Para 1: topic | Para 2: evidence | Para 3: implication | H3: subheading | H2: (section 2) [same pattern] | H2: (section 3 — featured snippet here) | H2: (section 4) | H2: Frequently Asked Questions | Q1 | Q2 | Q3 | Q4 | Q5 | H2: Conclusion | CTA: exact action + reason to act now.
SEO_BRIEF: Primary keyword: (exact phrase) | H1 with primary keyword: (exact text) | H2s with primary keyword: (H2 A) | (H2 B) | All H2s (search-query phrased, no generic labels): list them | Secondary keywords (8+, embed naturally): list them | FAQ questions (H3 format, exact search-query phrasing): list 5 | Featured snippet: section >> type (numbered list/definition block/table) | Missing keywords from original: list | Generic H2s needing rewrite: old >> replacement.
GEO_BRIEF: Named entities with 1-sentence descriptions: Entity: description | 3 definition blocks: TERM: 1-2 sentence standalone definition an AI can quote verbatim | 4 direct answer passages: QUESTION: 2-3 sentence passage opening with the direct answer | 2+ quotable sourced statements: statement -- Source, Year.
+26
View File
@@ -0,0 +1,26 @@
You are a targeted research analyst. One or more article dimensions scored below 70 and need fresh research to fix them. Produce a structured brief addressing each failing dimension directly.
Use only what you find in the search results — no invented data. Current year for all claims. Label anything 2+ years old as historical.
DIMENSION GUIDE — what to find per failing dimension:
language: 3-5 vivid real-world examples or narrative hooks the writer can use; tone/register of top articles on this topic; concrete rewrites for flagged sentences.
facts: 5-8 current named statistics with source + year; 3-5 named company/tool examples with specific measurable outcomes.
structure: standard H1→H2→H3 structure used by top articles on this topic; missing sections and FAQ questions to add; word-count shortfall and which sections to expand.
seo: exact primary keyword and 8-10 secondary/LSI keywords; required H1/opening/H2 keyword placements; 5 FAQ questions matching real search queries for H3 headings.
geo: 3-5 named entities with 1-sentence definitions; 2-3 direct answer passages (short paragraph opening with direct answer to a search question); 2 definition blocks as *Term*: one-sentence definition.
freshness: most current stats and trend data available; list of stale claims needing replacement; updated figures or evergreen rewrites.
Return a markdown brief with one section per failing dimension. Be concise. Every item must be actionable and sourced from the search results.
FAILING DIMENSIONS AND FEEDBACK:
{failing_dimensions_brief}
ARTICLE TOPIC / URL: {url}
CURRENT DATE: {current_date}
CURRENT YEAR: {current_year}
+41
View File
@@ -0,0 +1,41 @@
"""
chunker.py
"""
from pathlib import Path
import sys
from langchain_text_splitters import RecursiveCharacterTextSplitter
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from config import settings
splitter = RecursiveCharacterTextSplitter(
chunk_size=settings.CHUNK_SIZE,
chunk_overlap=settings.CHUNK_OVERLAP,
separators=[
"\n\n",
"\n",
". ",
" ",
""
]
)
def create_chunks(text):
return splitter.split_text(text)
+46
View File
@@ -0,0 +1,46 @@
"""
html_cleaner.py
Removes unnecessary HTML.
"""
from bs4 import BeautifulSoup
REMOVE_TAGS = [
"script",
"style",
"svg",
"iframe",
"noscript",
"footer",
"header",
"nav",
"aside"
]
def clean_html(html: str):
soup = BeautifulSoup(
html,
"lxml"
)
for tag in REMOVE_TAGS:
for item in soup.find_all(tag):
item.decompose()
return str(soup)
+62
View File
@@ -0,0 +1,62 @@
"""
ingestion.py
"""
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from config import settings
from langchain_core.documents import Document
from langchain_pinecone import PineconeVectorStore
from config.embeddings import embeddings
from config.pinecone_manager import get_or_create_index
index = get_or_create_index()
vectorstore = PineconeVectorStore(
index=index,
embedding=embeddings
)
def ingest_blog(
chunks,
url
):
if not chunks:
return
docs = []
for i, chunk in enumerate(chunks):
docs.append(
Document(
page_content=chunk,
metadata={
"url": url,
"chunk": i
}
)
)
vectorstore.add_documents(docs)
+18
View File
@@ -0,0 +1,18 @@
"""
markdown_converter.py
"""
from markdownify import markdownify
def html_to_markdown(html: str):
markdown = markdownify(
html,
heading_style="ATX"
)
return markdown
+45
View File
@@ -0,0 +1,45 @@
"""
retriever.py
"""
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_pinecone import PineconeVectorStore
from config.embeddings import embeddings
from config.pinecone_manager import get_or_create_index
from config import settings
index = get_or_create_index()
vectorstore = PineconeVectorStore(
index=index,
embedding=embeddings
)
retriever = vectorstore.as_retriever(
search_kwargs={
"k": settings.TOP_K
}
)
def retrieve(query):
return retriever.invoke(query)
+137
View File
@@ -0,0 +1,137 @@
"""
scraper.py
Scrapes a webpage using Crawl4AI.
Returns:
raw_html
cleaned_markdown
title
metadata
"""
import asyncio
import requests
from bs4 import BeautifulSoup
from crawl4ai import AsyncWebCrawler
class BlogScraper:
def _metadata_from_html(self, html: str):
soup = BeautifulSoup(html, "lxml")
title = ""
if soup.title and soup.title.string:
title = soup.title.string.strip()
metadata = {"title": title}
for tag in soup.find_all("meta"):
name = tag.get("name") or tag.get("property")
content = tag.get("content")
if name and content:
metadata[name] = content
return metadata
def _fast_http_scrape(self, url: str):
headers = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/126.0 Safari/537.36"
),
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
}
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
html = response.text
if len(html) > 1200:
metadata = self._metadata_from_html(html)
return {
"url": url,
"title": metadata.get("title", ""),
"html": html,
"markdown": "",
"metadata": metadata,
}
except Exception:
pass
return None
def _fallback_scrape(self, url: str, crawl_error: str = ""):
headers = {
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/126.0 Safari/537.36"
),
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9",
}
try:
response = requests.get(url, headers=headers, timeout=20)
response.raise_for_status()
html = response.text
metadata = self._metadata_from_html(html)
return {
"url": url,
"title": metadata.get("title", ""),
"html": html,
"markdown": "",
"metadata": metadata,
}
except Exception as exc:
detail = f"Crawl4AI error: {crawl_error}. " if crawl_error else ""
raise Exception(f"Unable to scrape {url}. {detail}HTTP fallback error: {exc}") from exc
async def scrape(self, url: str):
# 1. Try ultra-fast HTTP request first (< 0.5s)
fast_result = self._fast_http_scrape(url)
if fast_result is not None:
return fast_result
# 2. Fallback to Crawl4AI headless browser for JS-rendered apps
try:
async with AsyncWebCrawler() as crawler:
try:
result = await asyncio.wait_for(
crawler.arun(
url=url,
bypass_cache=True,
),
timeout=40.0,
)
except Exception as exc:
return self._fallback_scrape(url, f"Crawl4AI timeout/error: {exc}")
if not result.success:
crawl_error = (
getattr(result, "error_message", "")
or getattr(result, "status_message", "")
or "unknown Crawl4AI failure"
)
return self._fallback_scrape(url, crawl_error)
return {
"url": url,
"title": result.metadata.get("title", ""),
"html": result.html,
"markdown": result.markdown,
"metadata": result.metadata,
}
except Exception as exc:
return self._fallback_scrape(url, f"Playwright / Crawl4AI startup error: {exc}")
def scrape_blog(url: str):
scraper = BlogScraper()
return asyncio.run(scraper.scrape(url))
+71
View File
@@ -0,0 +1,71 @@
# ==============================================================================
# BLOG EXPERT - PYTHON DEPENDENCIES
# ==============================================================================
# Installation:
# pip install --upgrade pip
# pip install -r requirements.txt
#
# Optional Headless Browser Setup (for crawl4ai / playwright fallback):
# playwright install chromium
# ==============================================================================
# ------------------------------------------------------------------------------
# 1. CORE AGENTIC FRAMEWORKS & ORCHESTRATION
# ------------------------------------------------------------------------------
langchain>=0.3.0
langchain-core>=0.3.0
langchain-community>=0.3.0
langchain-text-splitters>=0.3.0
langgraph>=0.2.0
langgraph-checkpoint>=2.0.0
langgraph-prebuilt>=0.1.0
# ------------------------------------------------------------------------------
# 2. LLM PROVIDERS & CLOUD INFERENCE CLIENTS
# ------------------------------------------------------------------------------
langchain-groq>=0.2.0
groq>=0.11.0
langchain-openai>=0.2.0
openai>=1.50.0
langchain-google-genai>=2.0.0
google-genai>=0.1.0
google-generativeai>=0.8.0
google-api-core>=2.19.0
# ------------------------------------------------------------------------------
# 3. VECTOR DATABASE & EMBEDDINGS (RAG)
# ------------------------------------------------------------------------------
pinecone>=5.0.0
langchain-pinecone>=0.2.0
langchain-huggingface>=0.1.0
sentence-transformers>=3.0.0
# ------------------------------------------------------------------------------
# 4. WEB SEARCH, SCRAPING & CONTENT EXTRACTION
# ------------------------------------------------------------------------------
tavily-python>=0.5.0
firecrawl-py>=1.0.0
requests>=2.31.0
httpx>=0.27.0
beautifulsoup4>=4.12.0
markdownify>=0.13.0
lxml>=5.0.0
crawl4ai>=0.4.0
playwright>=1.49.0
# ------------------------------------------------------------------------------
# 5. STREAMLIT UI, DATA PROCESSING & CONFIGURATION
# ------------------------------------------------------------------------------
streamlit>=1.38.0
pandas>=2.2.0
pillow>=10.3.0
pydantic>=2.8.0
pydantic-settings>=2.4.0
python-dotenv>=1.0.0
langsmith>=0.1.0
# ------------------------------------------------------------------------------
# 6. DOCUMENT & PDF EXPORT
# ------------------------------------------------------------------------------
python-docx>=1.1.0
reportlab>=4.2.0
+1338
View File
File diff suppressed because it is too large Load Diff
+67
View File
@@ -0,0 +1,67 @@
import winreg
from datetime import datetime, timezone
def get_windows_datetime_format() -> str:
try:
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Control Panel\International") as key:
short_date = winreg.QueryValueEx(key, "sShortDate")[0]
time_format = winreg.QueryValueEx(key, "sTimeFormat")[0]
# Convert Windows date tokens to Python strftime tokens
# Longest patterns first to prevent substring matching issues
date_map = [
("yyyy", "%Y"),
("yy", "%y"),
("MMMM", "%B"),
("MMM", "%b"),
("MM", "%m"),
("M", "%m"),
("dd", "%d"),
("d", "%d"),
]
py_date = short_date
for win_tok, py_tok in date_map:
py_date = py_date.replace(win_tok, py_tok)
# Convert Windows time tokens to Python strftime tokens
time_map = [
("HH", "%H"),
("H", "%H"),
("hh", "%I"),
("h", "%I"),
("mm", "%M"),
("m", "%M"),
("ss", "%S"),
("s", "%S"),
("tt", "%p"),
("t", "%p"),
]
py_time = time_format
for win_tok, py_tok in time_map:
py_time = py_time.replace(win_tok, py_tok)
return f"{py_date} {py_time}"
except Exception:
# Fallback to a standard readable format
return "%d-%b-%Y %I:%M:%S %p"
def format_local_datetime(utc_iso_str: str) -> str:
if not utc_iso_str:
return ""
try:
if utc_iso_str.endswith("Z"):
utc_iso_str = utc_iso_str[:-1] + "+00:00"
# Handle formats like "2026-07-23 03:39:30" (replace spaces with T)
if " " in utc_iso_str and "T" not in utc_iso_str:
parts = utc_iso_str.split(" ")
utc_iso_str = f"{parts[0]}T{parts[1]}"
dt = datetime.fromisoformat(utc_iso_str)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
from datetime import timedelta
ist_tz = timezone(timedelta(hours=5, minutes=30))
local_dt = dt.astimezone(ist_tz)
return local_dt.strftime("%d-%b-%Y %I:%M %p IST")
except Exception:
return utc_iso_str
+590
View File
@@ -0,0 +1,590 @@
"""
exporter.py
Exports markdown blog articles to clean, professional Microsoft Word (.docx)
and Adobe PDF (.pdf) documents.
Excludes evaluator scores, metrics, radar charts, and pipeline logs.
Includes styled headings, paragraphs, formatted lists, tables, callouts, and embedded images.
"""
from __future__ import annotations
import io
import os
import re
from pathlib import Path
from typing import Optional
from PIL import Image as PILImage
# ── Clean / Sanitization Helper ───────────────────────────────────────────────
def clean_blog_markdown(markdown: str) -> str:
"""
Strips internal evaluation scores, baseline comparison tables,
JSON score blocks, and pipeline metadata from the markdown text.
"""
if not markdown:
return ""
text = markdown.strip()
# Remove JSON score blocks (e.g. ```json ... "language_score": ... ```)
text = re.sub(r"```json\s*\{[\s\S]*?\}\s*```", "", text, flags=re.IGNORECASE)
# Remove score table markers or evaluation summaries if present
patterns = [
r"###?\s*Evaluator Scores[\s\S]*?(?=\n##|\Z)",
r"###?\s*Baseline Scores[\s\S]*?(?=\n##|\Z)",
r"###?\s*Evaluation Summary[\s\S]*?(?=\n##|\Z)",
r"<table[\s\S]*?class=['\"]sct['\"][\s\S]*?</table>",
]
for pattern in patterns:
text = re.sub(pattern, "", text, flags=re.IGNORECASE)
# Clean redundant blank lines
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
def _resolve_image_path(img_ref: str) -> Optional[Path]:
"""
Resolves local file paths or downloads remote web image URLs (with caching)
so images can be embedded directly into PDF and Word exports.
"""
clean_ref = img_ref.strip().strip("'").strip('"')
if not clean_ref:
return None
# 1. Handle HTTP / HTTPS remote image URLs
if clean_ref.startswith(("http://", "https://")):
try:
import hashlib
import requests
cache_dir = Path.cwd() / "data" / "img_cache"
cache_dir.mkdir(parents=True, exist_ok=True)
url_hash = hashlib.md5(clean_ref.encode("utf-8")).hexdigest()
ext = ".jpg"
if ".png" in clean_ref.lower():
ext = ".png"
elif ".webp" in clean_ref.lower():
ext = ".webp"
cached_file = cache_dir / f"{url_hash}{ext}"
if cached_file.exists() and cached_file.stat().st_size > 500:
return cached_file
resp = requests.get(clean_ref, timeout=8, headers={"User-Agent": "Mozilla/5.0"})
if resp.status_code == 200 and len(resp.content) > 500:
cached_file.write_bytes(resp.content)
return cached_file
except Exception:
pass
# 2. Handle Local File Paths
p = Path(clean_ref)
if p.exists() and p.is_file():
return p
# Check relative to workspace root or generated_images
candidates = [
Path.cwd() / clean_ref,
Path.cwd() / "generated_images" / clean_ref,
Path.cwd() / "generated_images" / p.name,
Path.cwd() / "data" / "custom_images" / p.name,
Path.cwd() / "data" / "img_cache" / p.name,
]
for cand in candidates:
if cand.exists() and cand.is_file():
return cand
return None
# ── DOCX Export ───────────────────────────────────────────────────────────────
def export_to_docx(markdown_text: str, title: str = "Blog Article", default_title: str = "Blog Article") -> bytes:
"""
Converts markdown blog text into a styled Microsoft Word (.docx) document.
Returns bytes suitable for downloading via Streamlit.
"""
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
doc_title = title or default_title or "Blog Article"
cleaned = clean_blog_markdown(markdown_text)
doc = Document()
# Set standard margins (1 inch)
for section in doc.sections:
section.top_margin = Inches(1.0)
section.bottom_margin = Inches(1.0)
section.left_margin = Inches(1.0)
section.right_margin = Inches(1.0)
# Palette
COLOR_PRIMARY = RGBColor(15, 23, 42) # Slate 900
COLOR_SECONDARY = RGBColor(30, 41, 59) # Slate 800
COLOR_MUTED = RGBColor(100, 116, 139) # Slate 500
COLOR_BODY = RGBColor(30, 41, 59)
# Configure Normal Style
normal_style = doc.styles["Normal"]
normal_style.font.name = "Calibri"
normal_style.font.size = Pt(11)
normal_style.font.color.rgb = COLOR_BODY
lines = cleaned.splitlines()
i = 0
in_code_block = False
code_lines = []
def _add_styled_inline(paragraph, text: str, italic: bool = False):
"""Parse basic bold/italic inline markdown in paragraph."""
tokens = re.split(r"(\*\*.*?\*\*|\*.*?\*|`.*?`)", text)
for tok in tokens:
if not tok:
continue
if tok.startswith("**") and tok.endswith("**") and len(tok) >= 4:
run = paragraph.add_run(tok[2:-2])
run.bold = True
if italic:
run.italic = True
elif tok.startswith("*") and tok.endswith("*") and len(tok) >= 2:
run = paragraph.add_run(tok[1:-1])
run.italic = True
elif tok.startswith("`") and tok.endswith("`") and len(tok) >= 2:
run = paragraph.add_run(tok[1:-1])
run.font.name = "Consolas"
run.font.size = Pt(10)
run.font.color.rgb = RGBColor(180, 83, 9)
else:
run = paragraph.add_run(tok)
if italic:
run.italic = True
while i < len(lines):
line = lines[i]
stripped = line.strip()
# Handle Code blocks
if stripped.startswith("```"):
if in_code_block:
code_text = "\n".join(code_lines)
p = doc.add_paragraph()
p.paragraph_format.space_before = Pt(4)
p.paragraph_format.space_after = Pt(6)
p.paragraph_format.left_indent = Inches(0.3)
run = p.add_run(code_text)
run.font.name = "Consolas"
run.font.size = Pt(9.5)
run.font.color.rgb = RGBColor(51, 65, 85)
in_code_block = False
code_lines = []
else:
in_code_block = True
code_lines = []
i += 1
continue
if in_code_block:
code_lines.append(line)
i += 1
continue
# Skip empty lines
if not stripped:
i += 1
continue
# Image detection: ![alt](url)
img_match = re.search(r"^!\[(?P<alt>[^\]]*)\]\((?P<url>[^)]+)\)", stripped)
if img_match:
alt_text = img_match.group("alt")
img_target = img_match.group("url")
img_path = _resolve_image_path(img_target)
if img_path:
try:
p_img = doc.add_paragraph()
p_img.alignment = WD_ALIGN_PARAGRAPH.CENTER
p_img.paragraph_format.space_before = Pt(8)
p_img.paragraph_format.space_after = Pt(2)
run_img = p_img.add_run()
run_img.add_picture(str(img_path), width=Inches(5.2))
except Exception:
pass
caption_text = alt_text
if i + 1 < len(lines) and lines[i+1].strip().startswith("*") and lines[i+1].strip().endswith("*"):
i += 1
caption_text = lines[i].strip().strip("*").strip()
if caption_text:
p_cap = doc.add_paragraph()
p_cap.alignment = WD_ALIGN_PARAGRAPH.CENTER
p_cap.paragraph_format.space_before = Pt(0)
p_cap.paragraph_format.space_after = Pt(8)
run_cap = p_cap.add_run(caption_text)
run_cap.italic = True
run_cap.font.size = Pt(9.5)
run_cap.font.color.rgb = COLOR_MUTED
i += 1
continue
# Headings
if stripped.startswith("# "):
h = doc.add_heading(level=1)
h.paragraph_format.space_before = Pt(16)
h.paragraph_format.space_after = Pt(6)
h.paragraph_format.keep_with_next = True
run = h.add_run(stripped[2:].strip())
run.font.name = "Calibri"
run.font.size = Pt(20)
run.font.bold = True
run.font.color.rgb = COLOR_PRIMARY
i += 1
continue
if stripped.startswith("## "):
h = doc.add_heading(level=2)
h.paragraph_format.space_before = Pt(14)
h.paragraph_format.space_after = Pt(4)
h.paragraph_format.keep_with_next = True
run = h.add_run(stripped[3:].strip())
run.font.name = "Calibri"
run.font.size = Pt(15)
run.font.bold = True
run.font.color.rgb = COLOR_SECONDARY
i += 1
continue
if stripped.startswith("### "):
h = doc.add_heading(level=3)
h.paragraph_format.space_before = Pt(10)
h.paragraph_format.space_after = Pt(3)
h.paragraph_format.keep_with_next = True
run = h.add_run(stripped[4:].strip())
run.font.name = "Calibri"
run.font.size = Pt(13)
run.font.bold = True
run.font.color.rgb = COLOR_SECONDARY
i += 1
continue
# Bullet List Items
if stripped.startswith(("- ", "* ", "+ ")):
p = doc.add_paragraph(style="List Bullet")
p.paragraph_format.space_before = Pt(0)
p.paragraph_format.space_after = Pt(3)
_add_styled_inline(p, stripped[2:].strip())
i += 1
continue
# Numbered List Items
num_match = re.match(r"^(\d+)\.\s+(.*)", stripped)
if num_match:
p = doc.add_paragraph(style="List Number")
p.paragraph_format.space_before = Pt(0)
p.paragraph_format.space_after = Pt(3)
_add_styled_inline(p, num_match.group(2).strip())
i += 1
continue
# Blockquote
if stripped.startswith(">"):
p = doc.add_paragraph()
p.paragraph_format.left_indent = Inches(0.4)
p.paragraph_format.space_before = Pt(4)
p.paragraph_format.space_after = Pt(6)
_add_styled_inline(p, stripped[1:].strip(), italic=True)
i += 1
continue
# Regular Paragraph
p = doc.add_paragraph()
p.paragraph_format.space_before = Pt(0)
p.paragraph_format.space_after = Pt(6)
p.paragraph_format.line_spacing = 1.15
_add_styled_inline(p, stripped)
i += 1
buffer = io.BytesIO()
doc.save(buffer)
buffer.seek(0)
return buffer.getvalue()
# ── PDF Export ────────────────────────────────────────────────────────────────
def export_to_pdf(markdown_text: str, title: str = "Blog Article", default_title: str = "Blog Article") -> bytes:
"""
Converts markdown blog text into a publication-quality PDF document.
Returns bytes suitable for downloading via Streamlit.
"""
from reportlab.lib.pagesizes import letter
from reportlab.lib import colors
from reportlab.platypus import (
SimpleDocTemplate, Paragraph, Spacer, Image as RLImage, KeepTogether
)
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from reportlab.pdfgen import canvas
doc_title = title or default_title or "Blog Article"
cleaned = clean_blog_markdown(markdown_text)
class NumberedCanvas(canvas.Canvas):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._saved_page_states = []
def showPage(self):
self._saved_page_states.append(dict(self.__dict__))
self._startPage()
def save(self):
num_pages = len(self._saved_page_states)
for state in self._saved_page_states:
self.__dict__.update(state)
self.draw_page_number(num_pages)
super().showPage()
super().save()
def draw_page_number(self, page_count):
self.saveState()
self.setFont("Helvetica", 8.5)
self.setFillColor(colors.HexColor("#64748B"))
# Header rule & title
self.setLineWidth(0.5)
self.setStrokeColor(colors.HexColor("#E2E8F0"))
self.line(54, 792 - 40, 612 - 54, 792 - 40)
self.drawString(54, 792 - 34, default_title[:60])
# Footer
self.line(54, 45, 612 - 54, 45)
page_text = f"Page {self._pageNumber} of {page_count}"
self.drawRightString(612 - 54, 32, page_text)
self.restoreState()
buffer = io.BytesIO()
doc = SimpleDocTemplate(
buffer,
pagesize=letter,
leftMargin=54,
rightMargin=54,
topMargin=54,
bottomMargin=54,
)
styles = getSampleStyleSheet()
style_title = ParagraphStyle(
"BlogTitle",
parent=styles["Heading1"],
fontName="Helvetica-Bold",
fontSize=20,
leading=24,
textColor=colors.HexColor("#0F172A"),
spaceBefore=10,
spaceAfter=10,
alignment=TA_LEFT,
)
style_h2 = ParagraphStyle(
"BlogH2",
parent=styles["Heading2"],
fontName="Helvetica-Bold",
fontSize=14,
leading=18,
textColor=colors.HexColor("#1E293B"),
spaceBefore=12,
spaceAfter=5,
keepWithNext=True,
)
style_h3 = ParagraphStyle(
"BlogH3",
parent=styles["Heading3"],
fontName="Helvetica-Bold",
fontSize=11.5,
leading=15,
textColor=colors.HexColor("#334155"),
spaceBefore=9,
spaceAfter=3,
keepWithNext=True,
)
style_body = ParagraphStyle(
"BlogBody",
parent=styles["Normal"],
fontName="Helvetica",
fontSize=10,
leading=14.5,
textColor=colors.HexColor("#1E293B"),
spaceBefore=0,
spaceAfter=6,
alignment=TA_LEFT,
)
style_bullet = ParagraphStyle(
"BlogBullet",
parent=style_body,
leftIndent=15,
firstLineIndent=-10,
spaceAfter=3,
)
style_caption = ParagraphStyle(
"BlogCaption",
parent=styles["Italic"],
fontName="Helvetica-Oblique",
fontSize=8.5,
leading=11,
textColor=colors.HexColor("#64748B"),
alignment=TA_CENTER,
spaceBefore=2,
spaceAfter=8,
)
style_blockquote = ParagraphStyle(
"BlogQuote",
parent=style_body,
fontName="Helvetica-Oblique",
leftIndent=20,
rightIndent=20,
textColor=colors.HexColor("#475569"),
spaceBefore=4,
spaceAfter=6,
)
def _md_to_rl_xml(text: str) -> str:
"""Convert markdown bold/italic/code syntax to ReportLab XML tags."""
t = text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
t = re.sub(r"\*\*(.*?)\*\*", r"<b>\1</b>", t)
t = re.sub(r"\*(.*?)\*", r"<i>\1</i>", t)
t = re.sub(r"`(.*?)`", r"<font face='Courier' color='#B45309'>\1</font>", t)
return t
story = []
lines = cleaned.splitlines()
i = 0
in_code_block = False
code_lines = []
while i < len(lines):
line = lines[i]
stripped = line.strip()
# Handle Code blocks
if stripped.startswith("```"):
if in_code_block:
code_text = "\n".join(code_lines)
xml_code = _md_to_rl_xml(code_text)
style_code = ParagraphStyle(
"BlogCode",
parent=styles["Normal"],
fontName="Courier",
fontSize=8.5,
leading=11.5,
textColor=colors.HexColor("#334155"),
backColor=colors.HexColor("#F8FAFC"),
borderPadding=6,
spaceBefore=4,
spaceAfter=6,
)
story.append(Paragraph(xml_code.replace("\n", "<br/>"), style_code))
in_code_block = False
code_lines = []
else:
in_code_block = True
code_lines = []
i += 1
continue
if in_code_block:
code_lines.append(line)
i += 1
continue
if not stripped:
i += 1
continue
# Image detection
img_match = re.search(r"^!\[(?P<alt>[^\]]*)\]\((?P<url>[^)]+)\)", stripped)
if img_match:
alt_text = img_match.group("alt")
img_target = img_match.group("url")
img_path = _resolve_image_path(img_target)
caption_text = alt_text
if i + 1 < len(lines) and lines[i+1].strip().startswith("*") and lines[i+1].strip().endswith("*"):
i += 1
caption_text = lines[i].strip().strip("*").strip()
if img_path:
try:
with PILImage.open(str(img_path)) as pil_img:
orig_w, orig_h = pil_img.size
max_w = 460
max_h = 260
scale = min(max_w / orig_w, max_h / orig_h, 1.0)
target_w = orig_w * scale
target_h = orig_h * scale
img_flow = RLImage(str(img_path), width=target_w, height=target_h)
img_flow.hAlign = "CENTER"
img_elements = [Spacer(1, 4), img_flow]
if caption_text:
img_elements.append(Paragraph(_md_to_rl_xml(caption_text), style_caption))
story.append(KeepTogether(img_elements))
except Exception:
pass
elif caption_text:
story.append(Paragraph(_md_to_rl_xml(f"[{caption_text}]"), style_caption))
i += 1
continue
# Headings
if stripped.startswith("# "):
story.append(Paragraph(_md_to_rl_xml(stripped[2:].strip()), style_title))
i += 1
continue
if stripped.startswith("## "):
story.append(Paragraph(_md_to_rl_xml(stripped[3:].strip()), style_h2))
i += 1
continue
if stripped.startswith("### "):
story.append(Paragraph(_md_to_rl_xml(stripped[4:].strip()), style_h3))
i += 1
continue
# Bullet List Items
if stripped.startswith(("- ", "* ", "+ ")):
item_text = f"&bull;&nbsp; {_md_to_rl_xml(stripped[2:].strip())}"
story.append(Paragraph(item_text, style_bullet))
i += 1
continue
# Numbered List Items
num_match = re.match(r"^(\d+)\.\s+(.*)", stripped)
if num_match:
item_text = f"{num_match.group(1)}.&nbsp; {_md_to_rl_xml(num_match.group(2).strip())}"
story.append(Paragraph(item_text, style_bullet))
i += 1
continue
# Blockquote
if stripped.startswith(">"):
story.append(Paragraph(_md_to_rl_xml(stripped[1:].strip()), style_blockquote))
i += 1
continue
# Normal Paragraph
story.append(Paragraph(_md_to_rl_xml(stripped), style_body))
i += 1
doc.build(story, canvasmaker=NumberedCanvas)
buffer.seek(0)
return buffer.getvalue()
+5
View File
@@ -0,0 +1,5 @@
import uuid
def unique_id():
return str(uuid.uuid4())
+103
View File
@@ -0,0 +1,103 @@
import re
def ensure_exact_images_in_markdown(text: str, image_output: list[dict]) -> str:
"""
Guarantees that:
1. Zero duplicate images exist in the markdown article (same URL or duplicate embed removed).
2. Exactly all N images in image_output are contextually embedded in distinct body sections.
3. Missing images from LLM output are automatically inserted into relevant sections.
"""
if not text or not image_output:
return text
# 1. Deduplicate any repeated image embeds in text
seen_urls = set()
def _dedup_img(match):
alt = match.group(1)
url = match.group(2)
if url in seen_urls:
return "" # strip duplicate
seen_urls.add(url)
return match.group(0)
text = re.sub(r"!\[(.*?)\]\((.*?)\)", _dedup_img, text)
# 2. Check which images from image_output are missing
missing = []
for idx, img in enumerate(image_output):
u = img.get("url", "")
lp = img.get("local_path", "")
ru = img.get("remote_url", "") or img.get("source_url", "")
found = False
for target in [u, lp, ru]:
if target and target in text:
found = True
break
if not found:
missing.append((idx, img))
if not missing:
return text
# 3. Insert missing images into distinct body sections
sections = re.split(r"(?=\n##\s+)", text)
if len(sections) > 1:
sec_idx = 1
for idx, img in missing:
alt = img.get("alt") or img.get("section") or f"Visual Analysis {idx+1}"
img_url = img.get("url") or img.get("local_path") or img.get("remote_url")
cap = img.get("caption") or alt
is_custom = img.get("is_custom", False)
src = img.get("source_url") or img.get("remote_url") or ""
if is_custom or src == "Custom Image" or src == "Custom Upload":
caption_line = f"\n\n*Figure {idx+1}: {cap} (Source: Custom Upload)*\n"
elif src and "http" in src:
src_domain = src.split("/")[2] if "//" in src else src
caption_line = f"\n\n*Figure {idx+1}: {cap} (Source: [{src_domain}]({src}))*\n"
else:
caption_line = f"\n\n*Figure {idx+1}: {cap}*\n"
img_md = f"\n\n![{alt}]({img_url})" + caption_line
# Find a body section that matches image section or doesn't have an image
target_sec = None
target_heading = (img.get("section") or "").lower()
# First priority: matching section heading
if target_heading:
for s_i in range(1, len(sections)):
sec_header = sections[s_i].splitlines()[0].lower() if sections[s_i].splitlines() else ""
if target_heading in sec_header or any(w in sec_header for w in target_heading.split() if len(w) > 3):
target_sec = s_i
break
# Second priority: any section without an image (avoiding FAQ and Conclusion)
if target_sec is None:
for s_i in range(1, len(sections)):
sec_header = sections[s_i].splitlines()[0].lower() if sections[s_i].splitlines() else ""
if "![" not in sections[s_i] and "faq" not in sec_header and "conclusion" not in sec_header:
target_sec = s_i
break
if target_sec is None:
target_sec = min(sec_idx, len(sections) - 1)
sec_idx += 1
paragraphs = sections[target_sec].split("\n\n")
if len(paragraphs) >= 2:
paragraphs.insert(2, img_md.strip())
else:
paragraphs.append(img_md.strip())
sections[target_sec] = "\n\n".join(paragraphs)
text = "".join(sections)
else:
for idx, img in missing:
alt = img.get("alt") or f"Visual Analysis {idx+1}"
img_url = img.get("url") or img.get("local_path") or img.get("remote_url")
text += f"\n\n![{alt}]({img_url})\n"
return text
+96
View File
@@ -0,0 +1,96 @@
"""
job_writer.py — writes live generation progress to SQLite.
The background thread calls JobWriter.tick() every ~0.5 s and
JobWriter.append_stream() on every token. The UI reads from
the jobs table via BlogDatabase so it survives page refreshes.
"""
from __future__ import annotations
import threading
import time
from typing import Optional
class JobWriter:
"""
Thread-safe progress writer for a single generation job.
Usage:
jw = JobWriter(db, job_id)
jw.start() # starts background flush thread
jw.set_agent("supervisor", 17) # update active agent + progress %
jw.append_stream("token") # accumulate streamed text
jw.stop(run_id=42) # mark complete, stop flush thread
jw.stop(error="something went wrong") # mark failed
"""
_FLUSH_INTERVAL = 0.8 # seconds between DB writes
def __init__(self, db, job_id: int):
self._db = db
self._job_id = job_id
self._agent = ""
self._pct = 0
self._stream = ""
self._title = ""
self._lock = threading.Lock()
self._running = False
self._thread: Optional[threading.Thread] = None
# ── Public API ────────────────────────────────────────────────────────────
@property
def job_id(self) -> int:
return self._job_id
def start(self) -> None:
self._running = True
self._thread = threading.Thread(target=self._flush_loop, daemon=True)
self._thread.start()
def set_agent(self, agent: str, pct: int) -> None:
with self._lock:
self._agent = agent
self._pct = pct
def set_title(self, title: str) -> None:
with self._lock:
self._title = title
def append_stream(self, token: str) -> None:
with self._lock:
self._stream += token
def is_cancel_requested(self) -> bool:
return self._db.is_cancel_requested(self._job_id)
def stop(self, run_id: Optional[int] = None, error: str = "") -> None:
self._running = False
if self._thread:
self._thread.join(timeout=3)
# Final flush
with self._lock:
agent, pct, stream, title = self._agent, self._pct, self._stream, self._title
self._db.update_job(self._job_id,
active_agent=agent,
progress_pct=pct,
streamed_text=stream,
title=title)
self._db.finish_job(self._job_id, run_id=run_id, error=error)
# ── Internal ─────────────────────────────────────────────────────────────
def _flush_loop(self) -> None:
while self._running:
with self._lock:
agent, pct, stream, title = self._agent, self._pct, self._stream, self._title
try:
self._db.update_job(self._job_id,
active_agent=agent,
progress_pct=pct,
streamed_text=stream,
title=title)
except Exception:
pass
time.sleep(self._FLUSH_INTERVAL)
+105
View File
@@ -0,0 +1,105 @@
"""
Robust JSON extraction utility.
Models sometimes wrap JSON in markdown fences, add preamble text, or return
partial JSON. This module strips all of that and falls back gracefully rather
than raising an OutputParserException.
"""
import json
import re
def _strip_fences(text: str) -> str:
"""Remove ```json ... ``` or ``` ... ``` wrappers."""
# Match ```json\n...\n``` or ```\n...\n```
fenced = re.search(r"```(?:json)?\s*\n?(.*?)\n?```", text, re.DOTALL)
if fenced:
return fenced.group(1).strip()
return text.strip()
def _extract_json_object(text: str) -> str:
"""
Find the first {...} block in text, handling nested braces.
Returns the raw JSON string, or the original text if no block found.
"""
start = text.find("{")
if start == -1:
return text
depth = 0
in_string = False
escape_next = False
for i, ch in enumerate(text[start:], start=start):
if escape_next:
escape_next = False
continue
if ch == "\\" and in_string:
escape_next = True
continue
if ch == '"':
in_string = not in_string
continue
if in_string:
continue
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
return text[start : i + 1]
return text[start:]
def load_json(text) -> dict:
"""
Parse JSON from an LLM response string or structured content list.
Handles:
- Plain JSON
- JSON wrapped in ```json ... ``` fences
- JSON with leading/trailing prose
- Partial or malformed JSON (returns {} instead of raising)
"""
if isinstance(text, list):
extracted = []
for item in text:
if isinstance(item, dict) and "text" in item:
extracted.append(item["text"])
elif isinstance(item, str):
extracted.append(item)
text = "\n".join(extracted)
elif not isinstance(text, str):
text = str(text)
if not text or not text.strip():
return {}
# Try the raw text first (cheapest path)
try:
return json.loads(text.strip())
except json.JSONDecodeError:
pass
# Strip markdown fences and retry
stripped = _strip_fences(text)
try:
return json.loads(stripped)
except json.JSONDecodeError:
pass
# Extract the first {...} block and retry
extracted = _extract_json_object(stripped)
try:
return json.loads(extracted)
except json.JSONDecodeError:
pass
# Last resort: try the raw extracted block from original text
extracted_raw = _extract_json_object(text)
try:
return json.loads(extracted_raw)
except json.JSONDecodeError:
return {}
+5
View File
@@ -0,0 +1,5 @@
from markdownify import markdownify
def html_to_markdown(html):
return markdownify(html)
+247
View File
@@ -0,0 +1,247 @@
from __future__ import annotations
import hashlib
import json
from datetime import datetime
from pathlib import Path
from typing import Any
MEMORY_DIR = Path(__file__).resolve().parents[1] / ".memory"
RESEARCH_CACHE_PATH = MEMORY_DIR / "research_cache.json"
BLOG_PROMPT_LIMIT = 6000
RESEARCH_PROMPT_LIMIT = 3500
MEMORY_PROMPT_LIMIT = 1800
AGENT_OUTPUT_PROMPT_LIMIT = 2200
PLAN_PROMPT_LIMIT = 1600
def _now():
return datetime.utcnow().isoformat(timespec="seconds") + "Z"
def compact_text(value: Any, limit: int = 1800):
if value is None:
return ""
if isinstance(value, str):
text = value
else:
try:
text = json.dumps(value, ensure_ascii=True, indent=2)
except TypeError:
text = str(value)
text = " ".join(text.split())
if len(text) <= limit:
return text
return f"{text[:limit].rstrip()}..."
def memory_brief(state: Any, agent: str | None = None):
agent_issues = unresolved_issues(state, agent) if agent else unresolved_issues(state)
sections = [
("Context Memory", state.context_memory),
("Research Memory", state.research_memory),
("Working Memory", state.working_memory),
("Evaluation Memory", state.evaluation_memory[-3:]),
("Retry History", state.retry_history),
("Open Issues", agent_issues),
]
lines = []
for label, value in sections:
brief = compact_text(value, 1200)
if brief:
lines.append(f"{label}: {brief}")
return "\n".join(lines) or "No memory recorded yet."
def prompt_inputs(state: Any, agent: str | None = None):
return {
"blog": compact_text(state.cleaned_blog, BLOG_PROMPT_LIMIT),
"research": compact_text(state.research_output, RESEARCH_PROMPT_LIMIT),
"plan": compact_text(state.planner_output, PLAN_PROMPT_LIMIT),
"memory": compact_text(memory_brief(state, agent), MEMORY_PROMPT_LIMIT),
}
def build_context_memory(learner_output: dict[str, Any]):
fields = [
"title",
"summary",
"audience",
"intent",
"tone",
"writing_style",
"seo_intent",
"primary_keywords",
"secondary_keywords",
"structure",
]
return {
key: learner_output.get(key)
for key in fields
if learner_output.get(key) not in (None, "", [], {})
}
def record_working_memory(state: Any, agent: str, observations: Any):
entries = state.working_memory.setdefault(agent, [])
entries.append(
{
"iteration": state.iteration,
"created_at": _now(),
"observations": compact_text(observations, 1200),
}
)
state.working_memory[agent] = entries[-5:]
def add_evaluation_memory(state: Any, result: dict[str, Any]):
scores = {
"language": state.language_score,
"facts": state.facts_score,
"structure": state.structure_score,
"seo": state.seo_score,
"geo": state.geo_score,
"freshness": state.freshness_score,
"overall": state.overall_score,
}
feedback = {
"language": state.language_feedback,
"facts": state.facts_feedback,
"structure": state.structure_feedback,
"seo": state.seo_feedback,
"geo": state.geo_feedback,
"freshness": state.freshness_feedback,
}
state.evaluation_memory.append(
{
"iteration": state.iteration,
"created_at": _now(),
"scores": scores,
"feedback": feedback,
"raw_result": result,
}
)
state.evaluation_memory = state.evaluation_memory[-8:]
def build_issue_memory(state: Any, result: dict[str, Any]):
issues = result.get("issues") or result.get("issue_memory") or []
if isinstance(issues, dict):
issues = list(issues.values())
normalized = []
if isinstance(issues, list):
for index, issue in enumerate(issues, start=1):
if not isinstance(issue, dict):
continue
agent = str(issue.get("agent") or issue.get("category") or "").lower()
agent = agent.replace("_agent", "").replace(" agent", "").strip()
if agent not in {"language", "facts", "structure", "seo", "geo", "freshness", "researcher"}:
agent = "researcher" if agent == "research" else agent
normalized.append(
{
"id": issue.get("id") or issue.get("issue_id") or f"ISSUE-{index:03d}",
"agent": agent or "optimizer",
"severity": issue.get("severity") or "medium",
"location": issue.get("location") or "",
"problem": issue.get("problem") or issue.get("feedback") or issue.get("description") or "",
"status": issue.get("status") or "open",
"iteration": state.iteration,
}
)
feedback_by_agent = {
"language": (state.language_score, state.language_feedback),
"facts": (state.facts_score, state.facts_feedback),
"structure": (state.structure_score, state.structure_feedback),
"seo": (state.seo_score, state.seo_feedback),
"geo": (state.geo_score, state.geo_feedback),
"researcher": (state.freshness_score, state.freshness_feedback),
}
existing_agents = {issue["agent"] for issue in normalized if issue.get("status") == "open"}
for agent, (score, feedback) in feedback_by_agent.items():
if score and score < 70 and feedback and agent not in existing_agents:
normalized.append(
{
"id": f"{agent.upper()}-{state.iteration + 1:03d}",
"agent": agent,
"severity": "high" if score < 50 else "medium",
"location": "",
"problem": feedback,
"status": "open",
"iteration": state.iteration,
}
)
return normalized
def unresolved_issues(state: Any, agent: str | None = None):
issues = [
issue
for issue in state.issue_memory
if str(issue.get("status", "open")).lower() == "open"
]
if agent:
issues = [
issue
for issue in issues
if str(issue.get("agent", "")).lower() == agent.lower()
]
return issues
def increment_retry(state: Any, agent: str):
state.retry_history[agent] = int(state.retry_history.get(agent, 0)) + 1
def research_cache_key(query: str):
return hashlib.sha256(query.strip().lower().encode("utf-8")).hexdigest()
def _load_research_cache():
try:
return json.loads(RESEARCH_CACHE_PATH.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return {}
def get_cached_research(query: str):
cache = _load_research_cache()
return cache.get(research_cache_key(query))
def set_cached_research(query: str, value: dict[str, Any]):
MEMORY_DIR.mkdir(parents=True, exist_ok=True)
cache = _load_research_cache()
cache[research_cache_key(query)] = {
**value,
"query": query,
"cached_at": _now(),
}
RESEARCH_CACHE_PATH.write_text(
json.dumps(cache, ensure_ascii=True, indent=2),
encoding="utf-8",
)
+25
View File
@@ -0,0 +1,25 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
from langchain_core.output_parsers import JsonOutputParser
from utilis.schemas import *
learner_parser = JsonOutputParser(
pydantic_object=LearnerSchema
)
planner_parser = JsonOutputParser(
pydantic_object=PlannerSchema
)
research_parser = JsonOutputParser(
pydantic_object=ResearchSchema
)
evaluation_parser = JsonOutputParser(
pydantic_object=EvaluationSchema
)
+14
View File
@@ -0,0 +1,14 @@
from pathlib import Path
import sys
if __package__ is None or __package__ == "":
sys.path.append(str(Path(__file__).resolve().parents[1]))
PROMPT_DIR = Path(__file__).resolve().parents[1] / "prompts"
def load_prompt(filename: str):
with open(PROMPT_DIR / filename, "r", encoding="utf8") as f:
return f.read()
+151
View File
@@ -0,0 +1,151 @@
"""
research_cache.py — in-process semantic research cache.
Caches the full LLM-synthesised research brief keyed on a normalised hash
of the search query. A cosine-similarity check on a lightweight TF-IDF
vector catches near-duplicate queries (e.g. "best AI tools for startups" vs
"top AI software for startups") and reuses the cached result.
Cache is in-memory and process-scoped. Entries expire after TTL_SECONDS
(default 6 hours). No external dependencies — just stdlib + math.
Usage:
from utilis.research_cache import ResearchCache
cache = ResearchCache() # one instance per agent is fine
hit = cache.get(query)
if hit:
return hit
result = ... expensive call ...
cache.set(query, result)
return result
"""
from __future__ import annotations
import hashlib
import math
import re
import time
from collections import defaultdict
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
TTL_SECONDS = 6 * 3600 # cached results live for 6 hours
SIM_THRESHOLD = 0.82 # cosine similarity above this → cache hit
# ---------------------------------------------------------------------------
# Lightweight TF-IDF helpers (no external deps)
# ---------------------------------------------------------------------------
_STOPWORDS = frozenset(
"a an the is are was were be been for of in on at to by and or with "
"this that it its as from how what when where who which will can do "
"does did not no so but if then than".split()
)
def _tokenize(text: str) -> list[str]:
text = text.lower()
text = re.sub(r"[^a-z0-9\s]", " ", text)
return [t for t in text.split() if t and t not in _STOPWORDS]
def _tf(tokens: list[str]) -> dict[str, float]:
counts: dict[str, int] = defaultdict(int)
for t in tokens:
counts[t] += 1
total = len(tokens) or 1
return {k: v / total for k, v in counts.items()}
def _cosine(a: dict[str, float], b: dict[str, float]) -> float:
keys = set(a) | set(b)
dot = sum(a.get(k, 0.0) * b.get(k, 0.0) for k in keys)
na = math.sqrt(sum(v * v for v in a.values()))
nb = math.sqrt(sum(v * v for v in b.values()))
if na == 0 or nb == 0:
return 0.0
return dot / (na * nb)
def _query_vector(query: str) -> dict[str, float]:
return _tf(_tokenize(query))
def _query_hash(query: str) -> str:
norm = " ".join(_tokenize(query))
return hashlib.sha256(norm.encode()).hexdigest()[:16]
# ---------------------------------------------------------------------------
# Cache implementation
# ---------------------------------------------------------------------------
class ResearchCache:
"""
Thread-safe in-memory cache for LLM research briefs.
Each entry stores:
- the normalised query vector (for similarity matching)
- the cached result string
- the expiry timestamp
"""
def __init__(self, ttl: int = TTL_SECONDS, sim_threshold: float = SIM_THRESHOLD):
self._ttl = ttl
self._threshold = sim_threshold
# { hash_key: {"vec": dict, "result": str, "expires": float} }
self._store: dict[str, dict] = {}
def _evict_expired(self) -> None:
now = time.time()
expired = [k for k, v in self._store.items() if v["expires"] < now]
for k in expired:
del self._store[k]
def get(self, query: str) -> str | None:
"""
Return a cached result if a sufficiently similar query was seen recently,
otherwise return None.
"""
self._evict_expired()
if not self._store:
return None
qvec = _query_vector(query)
for entry in self._store.values():
sim = _cosine(qvec, entry["vec"])
if sim >= self._threshold:
return entry["result"]
return None
def set(self, query: str, result: str) -> None:
"""Store a result for the given query."""
key = _query_hash(query)
self._store[key] = {
"vec": _query_vector(query),
"result": result,
"expires": time.time() + self._ttl,
}
def clear(self) -> None:
self._store.clear()
# ---------------------------------------------------------------------------
# Module-level singletons — one cache per agent type so they don't
# cross-contaminate (research brief vs targeted research brief).
# ---------------------------------------------------------------------------
_researcher_cache = ResearchCache()
_targeted_researcher_cache = ResearchCache()
def get_researcher_cache() -> ResearchCache:
return _researcher_cache
def get_targeted_cache() -> ResearchCache:
return _targeted_researcher_cache
+92
View File
@@ -0,0 +1,92 @@
"""
invoke_with_retry — the single call-site for all agent LLM calls.
Works with both RotatingChatGroq (config/llm.py) and OpenAIChatLLM
(config/openai_llm.py). Both expose the same interface:
- ._client : raw LangChain chat model (used to build the chain)
- ._invoke_chain() : rate-limit-aware invocation
Rebuilds the chain on every call so model rotation is always reflected.
Handles the _RotationOccurred sentinel from RotatingChatGroq by rebuilding
the chain with the new active model and retrying.
"""
import logging
logger = logging.getLogger(__name__)
_MAX_ROTATIONS = 3 # maximum model switches before giving up
def invoke_with_retry(prompt, llm, inputs: dict):
"""
Build a fresh chain from prompt + llm._client and invoke it.
Compatible with any LLM wrapper that exposes:
- llm._client (the raw LangChain chat model)
- llm._invoke_chain() (rate-limit + rotation aware invoke)
On TPD/rotation exhaustion (Groq):
- RotatingChatGroq raises _RotationOccurred
- invoke_with_retry catches it, rebuilds the chain, retries on
the new model — up to _MAX_ROTATIONS times
On TPM exhaustion (Groq):
- RotatingChatGroq sleeps internally and retries — nothing to do here
On 429 rate-limit (OpenAI):
- OpenAIChatLLM handles exponential back-off internally
Args:
prompt: LangChain ChatPromptTemplate
llm: RotatingChatGroq or OpenAIChatLLM instance from make_llm()
inputs: Dict of template variables
Returns:
LangChain AIMessage
"""
# Import lazily to avoid circular imports; _RotationOccurred only exists
# in the Groq path, so we guard with a fallback sentinel.
try:
from config.llm import _RotationOccurred
except ImportError:
_RotationOccurred = type("_RotationOccurred", (Exception,), {})
for rotation_attempt in range(_MAX_ROTATIONS + 1):
chain = prompt | llm._client
try:
response = llm._invoke_chain(chain, inputs)
if hasattr(response, "content") and isinstance(response.content, list):
extracted = []
for item in response.content:
if isinstance(item, dict) and "text" in item:
extracted.append(item["text"])
elif isinstance(item, str):
extracted.append(item)
response.content = "\n".join(extracted)
try:
from utilis.token_counter import add_tokens
usage = getattr(response, "usage_metadata", None)
if isinstance(usage, dict):
p_tok = usage.get("input_tokens", 0)
c_tok = usage.get("output_tokens", 0)
add_tokens(p_tok, c_tok)
else:
p_tok = len(str(inputs)) // 4
c_tok = len(getattr(response, "content", "")) // 4
add_tokens(p_tok, c_tok)
except Exception:
pass
return response
except _RotationOccurred:
if rotation_attempt >= _MAX_ROTATIONS:
raise RuntimeError(
"All Groq models exhausted their daily quota. "
"Try again tomorrow or upgrade your plan."
)
logger.info(
"Model rotated (attempt %d/%d). Rebuilding chain.",
rotation_attempt + 1, _MAX_ROTATIONS,
)
# Loop: chain will be rebuilt with llm._client pointing
# to the new active model at the top of the next iteration.
+75
View File
@@ -0,0 +1,75 @@
from pydantic import BaseModel
class LearnerSchema(BaseModel):
title: str
summary: str
audience: str
intent: str
tone: str
writing_style: str
seo_intent: str
primary_keywords: list[str]
secondary_keywords: list[str]
structure: list[str]
class PlannerSchema(BaseModel):
strengths: list[str]
weaknesses: list[str]
missing_topics: list[str]
seo_improvements: list[str]
research_query: str
missing_statistics: list[str]
missing_examples: list[str]
missing_sections: list[str]
class ResearchSchema(BaseModel):
updated_facts: list[str]
statistics: list[str]
examples: list[str]
seo_keywords: list[str]
lsi_keywords: list[str]
faqs: list[str]
references: list[str]
class EvaluationSchema(BaseModel):
language: int
facts: int
structure: int
language_feedback: str
facts_feedback: str
structure_feedback: str
+20
View File
@@ -0,0 +1,20 @@
import threading
_local = threading.local()
def reset_token_counter():
_local.prompt_tokens = 0
_local.completion_tokens = 0
_local.total_tokens = 0
def add_tokens(prompt: int, completion: int):
if not hasattr(_local, "prompt_tokens"):
reset_token_counter()
_local.prompt_tokens += prompt
_local.completion_tokens += completion
_local.total_tokens += (prompt + completion)
def get_tokens():
if not hasattr(_local, "prompt_tokens"):
return 0, 0, 0
return _local.prompt_tokens, _local.completion_tokens, _local.total_tokens
+12
View File
@@ -0,0 +1,12 @@
import functools
def traceable(func=None, **decorator_kwargs):
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
return f(*args, **kwargs)
return wrapper
if func is not None:
return decorator(func)
return decorator