Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

63 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Blog Agent Logo

An Autonomous, Multi-Agent Technical Blog Generation Engine Powered by LangGraph, Groq and Streamlit.

Python LangGraph LangSmith Groq Streamlit PostgreSQL


📌 Overview

Blog Agent is an enterprise-grade, multi-agent AI system designed to automate deep research, structured outline planning, parallel section drafting, dynamic citation grounding, and technical diagram synthesis for publication-ready blog posts.

Unlike single-prompt LLM wrappers, Blog Agent models technical writing as a stateful, cyclical graph execution workflow using LangGraph. It routes content requirements dynamically, executes parallel web searches, fans out task workers across structured sub-sections, synthesizes AI visuals or frosted-glass diagrams, and persists all assets to PostgreSQL with a secure multi-user architecture.


✨ Key Features

  • 🧠 Adaptive Intelligence Routing:

    • Dynamically classifies user topics into three operational modes:
      • closed_book: For evergreen concepts without external dependency.
      • hybrid: Merges internal knowledge with targeted, up-to-date web research.
      • open_book: Enforces strict temporal bounds (e.g. 7-day recency cutoff) for news & tech roundups.
  • Parallel Web Research Engine:

    • Leverages concurrent Tavily search workers (ThreadPoolExecutor) to gather authoritative evidence items.
    • Normalizes metadata, deduplicates canonical URLs, and computes published dates against recency thresholds.
  • 🔀 Parallel Map-Reduce Worker Fan-Out:

    • Orchestrator: Deconstructs topics into 5–9 granular task modules with word-count targets, tags, and citation flags.
    • Worker Nodes: Uses LangGraph's dynamic Send API to parallelize section drafting, enforcing scope bounds and inline URL citations.
    • Reducer Subgraph: Merges draft sections, evaluates image needs, generates visual specs, and replaces placeholders with finalized images.
  • 🎨 Visual Asset Synthesis & Resilient Fallback Engine:

    • Integrates Hugging Face (FLUX.1-schnell) for high-fidelity technical diagrams and AI artwork.
    • Includes a zero-downtime fallback engine using Pillow to render custom dark-mode glassmorphic architecture diagrams when API limits occur.
  • 🔒 Secure User Management & PostgreSQL Persistence:

    • Built-in multi-user database storage with bcrypt password hashing and ThreadedConnectionPool.
    • Signed HMAC-SHA256 session cookies for seamless session persistence across refreshes.
    • User analytics: tracks document counts, image output, registration metrics, and interactive blog loading/deletion.
  • 💎 Cybernetic Glassmorphism Interface:

    • Custom dark theme UI (#060810 palette) built with Streamlit and styled via modular CSS (styles/style.css).
    • Real-time agent telemetry stream dashboard providing visibility into node state transitions, search queries, active workers, and generated images.
    • One-click downloads for standalone Markdown files or complete ZIP archives (Markdown + image assets).
  • 📊 Observability & Real-Time Tracing:

    • Native integration with LangSmith for full execution graph tracing, prompt performance monitoring, token usage analytics, and latency debugging across all nodes.

🏗️ System Architecture

graph TD
    %% Nodes
    User([User Prompt]) --> Router[📡 Router Node]
    
    Router -->|closed_book| Orch[📋 Orchestrator Node]
    Router -->|hybrid / open_book| Research[🔎 Research Node - Tavily API]
    Research --> Orch
    
    Orch -->|Dynamic Fan-Out via Send API| Workers[👷 Worker Nodes - Parallel Section Writers]
    
    subgraph Reducer Subgraph ["⚙️ Reducer Subgraph"]
        Merge[📝 Merge Content] --> DecideImg[🖼️ Decide Image Specs]
        DecideImg --> GenImg[⚡ Generate & Place Images]
    end
    
    Workers --> Merge
    GenImg --> DB[(🗄️ PostgreSQL Persistence)]
    GenImg --> UI[💻 Streamlit UI]
Loading

📊 LangSmith Observability & Tracing

Blog Agent natively integrates LangSmith to provide enterprise-grade telemetry, observability, and debugging for complex agentic workflows. Because multi-agent graph execution involves non-deterministic LLM calls, conditional routing, and parallel worker fan-out, LangSmith acts as the core control plane for system diagnostics.

🔍 How LangSmith is Used in Blog Agent:

  1. State Graph Execution Tracing:

    • Captures the complete execution tree of the LangGraph state machine from START to END.
    • Tracks state payload mutations (topic, mode, evidence, plan, sections, merged_md) as data flows across nodes.
  2. Conditional Route Debugging:

    • Monitors the Router Node decision outputs (closed_book, hybrid, open_book).
    • Verifies whether search query generation and recency cutoff calculations behave as expected before invoking Tavily research.
  3. Parallel Map-Reduce Worker Monitoring:

    • Inspects concurrent Send dispatches to parallel Worker Nodes.
    • Allows side-by-side comparison of individual section drafts, target word compliance, and URL citation grounding.
  4. Structured Schema Validation:

    • Traces Pydantic structured outputs (RouterDecision, Plan, EvidencePack, GlobalImagePlan) generated by Groq (llama-3.3-70b-versatile).
    • Detects parsing failures, retry loops, or invalid schema field responses instantly.
  5. Performance & Latency Optimization:

    • Measures time-to-first-token and total execution latency for each agent node.
    • Monitors token usage metrics (prompt vs. completion tokens) across all parallel LLM calls to optimize API consumption.

📂 Project Structure

blog_agent/
├── backend.py                    # LangGraph multi-agent backend state machine & node logic
├── frontend.py                   # Streamlit UI, real-time telemetry dashboard & rendering
├── auth.py                       # Database pool, bcrypt authentication, cookie tokens & profile stats
├── styles/
│   ├── style.css                 # Frosted glassmorphism dark aesthetic stylesheet
│   └── images/
│       ├── favicon.png           # App favicon icon              
│       └── logo.png              # Main application logo header (16:9 landscape)
├── images/
│   ├── ss1.png                   # UI telemetry interface screenshot
│   └── ss2.png                   # Generated markdown & image preview screenshot
├── requirements.txt              # Project dependencies
├── .env                          # Environment key configuration
└── README.md                     # Project documentation

🛠️ Tech Stack


🚀 Quickstart Guide

1. Prerequisites

  • Python: 3.10 or higher
  • PostgreSQL: Local or hosted database instance (e.g., Supabase, Neon or local Postgres)

2. Installation

Clone the repository and enter the project directory:

git clone https://github.com/Raman7072/blog_agent.git
cd GraphLoom

Create and activate a virtual environment:

python3 -m venv .venv
source .venv/bin/activate

Install required dependencies:

pip install -r requirements.txt

3. Environment Configuration

Create a .env file in the root directory:

# LLM & Search APIs
GROQ_API_KEY=your_groq_api_key_here
TAVILY_API_KEY=your_tavily_api_key_here
HF_TOKEN=your_huggingface_token_here

# Database Configuration
DB_URL=postgresql://user:password@localhost:5432/blog_agent_db

# Security & Session Secrets
SESSION_SECRET=your_random_hmac_secret_key_here
ENVIRONMENT=development

# LangSmith Tracking
LANGSMITH_TRACING=true
LANGSMITH_ENDPOINT="https://api.smith.langchain.com"
LANGSMITH_API_KEY=your_langsmith_api_key_here
LANGSMITH_PROJECT='BlogAgent'

4. Database Setup

Blog Agent automatically initializes the required tables (users, blogs, blog_images) on first startup via auth.init_db(). Ensure your PostgreSQL database is reachable at the DB_URL provided in .env.


5. Running the Application

Launch the Streamlit web application:

streamlit run frontend.py

Open your browser at http://localhost:8501 to access Blog Agent.


🖥️ UI Screenshots

Real-Time Telemetry Stream Generated Article & Diagrams
Telemetry Interface Markdown & Visual Preview

🔒 Security Best Practices

  • Password hashes are stored using standard bcrypt key derivation with random salt.
  • Session cookies use base64 HMAC-SHA256 signatures with timestamp expiration.
  • Input fields sanitize database query parameters using psycopg2 parameterized queries.
  • Environment variables isolate private keys (GROQ_API_KEY, TAVILY_API_KEY, HF_TOKEN, DB_URL, LANGSMITH_API_KEY).

Releases

Packages

Contributors

Languages