Skip to content

Latest commit

 

History

History
402 lines (304 loc) · 10.7 KB

File metadata and controls

402 lines (304 loc) · 10.7 KB

Agentic AI Blog Generation

A sophisticated AI-powered blog generation system that leverages LangGraph and Google Gemini AI to automatically generate, optimize, and translate blog content across multiple languages.

🎯 Project Overview

This project implements an agentic workflow using LangGraph state graphs to orchestrate a multi-step blog generation pipeline. It features:

  • Intelligent Blog Generation: Generates engaging blog titles and content based on user-provided topics
  • Multi-Language Support: Automatically translates generated blogs into Hindi and Marathi
  • REST API Interface: FastAPI-based HTTP endpoints for easy integration
  • LangSmith Integration: Built-in support for debugging and monitoring via LangSmith
  • Production-Ready: Comprehensive error handling, validation, and logging

🏗️ Architecture

Technology Stack

Component Technology
LLM Google Gemini 2.5 Flash
Orchestration LangGraph
API Framework FastAPI
Server Uvicorn
Language Framework LangChain
Environment Management Python dotenv

Project Structure

agentic-ai-blog-generation/
├── app.py                          # FastAPI application with REST endpoints
├── main.py                         # Entry point
├── requirements.txt                # Project dependencies
├── pyproject.toml                  # Project configuration
├── langgraph.json                  # LangGraph configuration
├── .env.example                    # Environment variables template
└── src/
    ├── llms/
    │   └── gemini_llm.py          # Google Gemini LLM wrapper
    ├── graphs/
    │   └── graph_builder.py        # LangGraph state graph builder
    ├── nodes/
    │   └── blog_node.py            # Blog generation node implementations
    └── states/
        └── blogstate.py            # State definitions using TypedDict

🔄 Workflow Architecture

The system uses LangGraph to orchestrate a multi-step blog generation workflow:

Two Workflow Modes

1. Topic-Based Generation

Generates blog content in English based on the provided topic:

alt text

2. Language-Aware Generation

Generates blog in English, then translates to requested language:

alt text

Processing Nodes

Node Function Description
title_creation Generates catchy, SEO-friendly blog titles Uses Gemini to create compelling titles
content_generation Creates detailed blog content Generates 250-word markdown-formatted content
route Extracts language for conditional routing Determines translation path
hindi_translation Translates to Hindi Uses structured output for accuracy
marathi_translation Translates to Marathi Preserves formatting and tone

🚀 Features

1. Blog Generation

  • Title Generation: Catchy, SEO-optimized blog titles
  • Content Creation: Detailed, engaging blog content with markdown formatting
  • Smart Prompting: Expert-crafted prompts for high-quality outputs

2. Multi-Language Support

  • Native Languages: Hindi and Marathi translations
  • Structured Output: Pydantic models for consistent blog structure
  • Cultural Adaptation: Translates with cultural sensitivity

3. API Endpoints

  • POST /generate_blog/ - Generate and optionally translate blogs
  • GET /health/ - Health check endpoint

4. Error Handling

  • Comprehensive input validation
  • Detailed error messages and logging
  • Graceful failure handling

📋 Prerequisites

  • Python 3.13 or higher
  • Google Gemini API Key (Get one here)
  • LangChain API Key (optional, for debugging)

🔧 Installation & Setup

1. Clone the Repository

git clone <repository-url>
cd agentic-ai-blog-generation

2. Create Virtual Environment

python -m venv .venv

3. Activate Virtual Environment

# Windows
.venv\Scripts\activate

# macOS/Linux
source .venv/bin/activate

4. Install Dependencies

uv add -r requirements.txt

5. Configure Environment Variables

Create a .env file in the project root:

cp .env.example .env

Edit .env and add your credentials:

# Required
GEMINI_API_KEY=your_gemini_api_key_here

# Optional (for LangSmith debugging)
LANGCHAIN_API_KEY=your_langchain_api_key
LANGCHAIN_PROJECT=your_project_name

💻 Usage

Running the API Server

python app.py

The API will be available at http://localhost:8000

API Documentation

  • Interactive Swagger UI: http://localhost:8000/docs
  • ReDoc documentation: http://localhost:8000/redoc

Making API Requests

Generate Blog in English

curl -X POST "http://localhost:8000/generate_blog/" \
  -H "Content-Type: application/json" \
  -d '{"topic": "Machine Learning in Healthcare"}'

Generate Blog with Translation

curl -X POST "http://localhost:8000/generate_blog/" \
  -H "Content-Type: application/json" \
  -d '{
    "topic": "Artificial Intelligence",
    "language": "Hindi"
  }'

Health Check

curl http://localhost:8000/health/

Python Example

import requests

# API endpoint
url = "http://localhost:8000/generate_blog/"

# Generate blog in Hindi
payload = {
    "topic": "Blockchain Technology",
    "language": "Hindi"
}

response = requests.post(url, json=payload)
result = response.json()

print(f"Title: {result['data']['blog']['title']}")
print(f"Content: {result['data']['blog']['content']}")

📚 API Request/Response Examples

Request

{
  "topic": "Cloud Computing Benefits",
  "language": "Marathi"
}

Success Response (200 OK)

{
  "status": "success",
  "data": {
    "topic": "Cloud Computing Benefits",
    "language": "Marathi",
    "blog": {
      "title": "क्लाउड कंप्यूटिंग के लाभ",
      "content": "# क्लाउड कंप्यूटिंग के लाभ\n\n..."
    }
  }
}

Error Response (400 Bad Request)

{
  "status": "error",
  "error": "Language must be one of ['Hindi', 'Marathi']"
}

🧪 Development

Project Dependencies

Package Version Purpose
fastapi >=0.128.0 Web framework
langchain >=1.2.0 LLM orchestration
langchain-google-genai >=4.1.2 Gemini integration
langgraph >=1.0.5 State graph orchestration
langchain-core >=1.2.6 Core LangChain components
python-dotenv >=1.2.1 Environment variable management
uvicorn >=0.40.0 ASGI server

Development Workflow

  1. Install in Development Mode

    uv sync
  2. Enable LangSmith Debugging Set LANGCHAIN_TRACING_V2=true in .env

  3. View Execution Traces

  4. LangGraph Studio Integration The project is configured for LangGraph Studio via langgraph.json

🔍 Key Classes & Methods

GeminiLLM (src/llms/gemini_llm.py)

Wrapper for Google Gemini LLM initialization

  • get_llm(): Returns configured ChatGoogleGenerativeAI instance

BlogNode (src/nodes/blog_node.py)

Implements blog generation nodes

  • title_creation(): Generates blog title
  • content_generation(): Generates blog content
  • translation(): Translates blog to target language
  • route(): Routes based on language selection
  • route_decision(): Determines translation path

GraphBuilder (src/graphs/graph_builder.py)

Orchestrates LangGraph workflows

  • build_topic_graph(): Simple English-only workflow
  • build_language_graph(): Multi-language workflow
  • setup_graph(): Compiles and returns executable graph

BlogState (src/states/blogstate.py)

Type-safe state definition using TypedDict

  • topic: Input blog topic
  • blog: Generated blog object
  • language: Target language for translation

🛠️ Configuration

Environment Variables

# Google Gemini API Configuration
GEMINI_API_KEY=your_api_key_here

# Optional: LangSmith debugging
LANGCHAIN_API_KEY=your_api_key_here
LANGCHAIN_PROJECT=your_project_name
LANGCHAIN_TRACING_V2=true

API Server Configuration

Edit app.py to modify:

  • Host: Change localhost to 0.0.0.0 for production
  • Port: Modify from 8000 to desired port
  • Reload: Set to False in production
if __name__ == "__main__":
    uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=False)

📖 Supported Languages

Currently supported for blog translation:

  • Hindi (hi)
  • Marathi (mr)

To add more languages:

  1. Add to SUPPORTED_LANGUAGES in app.py
  2. Add corresponding node in GraphBuilder.build_language_graph()

🚨 Error Handling

The application includes comprehensive error handling:

Error Type Status Code Scenario
Validation Error 400 Invalid topic or language
LLM Error 500 Gemini API issues
Missing Config 500 Missing GEMINI_API_KEY
Rate Limit 429 API rate exceeded
Unexpected Error 500 Unforeseen issues

Use Cases

  1. Content Marketing: Automatically generate blog posts for websites
  2. Multi-Language Blogs: Create content in multiple Indian languages
  3. SEO Optimization: Generate SEO-friendly titles and content
  4. Content Curation: Quickly prototype blog content ideas
  5. AI Learning: Understand LangGraph and agentic workflows

🐛 Troubleshooting

Issue: GEMINI_API_KEY not found

Solution:

  • Ensure .env file exists in project root
  • Verify API key is correctly set
  • Check file is not in .gitignore

Issue: ModuleNotFoundError

Solution:

uv add -r requirements.txt

Issue: Connection errors to Gemini API

Solution:

  • Verify internet connection
  • Check API key validity
  • Ensure quota not exceeded in Google Cloud Console

Issue: LangSmith tracing not working

Solution:

# Add to .env
LANGCHAIN_API_KEY=your_api_key
LANGCHAIN_TRACING_V2=true
LANGCHAIN_PROJECT=your_project_name

📚 Resources

🤝 Contributing

Contributions are welcome! To contribute:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/new-feature)
  3. Commit changes (git commit -m 'Add new feature')
  4. Push to branch (git push origin feature/new-feature)
  5. Open a Pull Request

📄 License

This project is open source and available under the MIT License.