Skip to content

rohit267/ai-article-generator

Repository files navigation

AI News Article Generator

A sophisticated AI-powered tool that generates professional news articles through a multi-stage process including research, drafting, editing, and finalization.

Features

  • Multi-stage Article Generation:

    • Research: AI-powered web browsing for real-time information gathering
    • Drafting: Initial article creation based on research
    • Editing: Content refinement and structure improvement
    • Finalizing: SEO optimization and final polish
  • Advanced Web Browsing & Research:

    • Real-time web search across multiple search engines
    • Content extraction from web pages with full text analysis
    • Fact verification using multiple sources
    • Expert source identification and credibility scoring
    • AI-powered insight extraction and analysis
    • Comprehensive research synthesis
    • Configurable time range filtering (day/week/month/year/all)
    • Adjustable source limits (1-15 sources)
    • Source verification and reliability assessment
  • Multiple AI Models: Support for various AI models including:

    • OpenAI GPT-4o Mini & GPT-4.1 Mini
    • Anthropic Claude Sonnet 4 & Claude 3.7 Sonnet
    • Google Gemini 2.5 Flash & Gemini 2.5 Pro
    • X.AI Grok 4 Fast
  • Customizable Output:

    • News styles (investigative, feature, breaking news, opinion, interview, profile)
    • Tones (formal, casual, humorous, authoritative, conversational, academic)
    • Lengths (short, medium, long)
  • SEO Optimization:

    • Keyword integration
    • Meta information generation
    • Source citation
  • Real-time Progress: Live updates during article generation

  • Source Management: Automatic source gathering and citation

  • MongoDB Integration: Article storage and retrieval

Installation

  1. Clone the repository:

    git clone <repository-url>
    cd ai-news-article-generator
  2. Install dependencies:

    bun install
  3. Set up environment variables:

    cp .env.example .env

    Edit .env and add your configuration:

    OPENROUTER_API_KEY=your_openrouter_api_key_here
    MONGODB_URI=mongodb://localhost:27017/article-generator
    PORT=3000
    NODE_ENV=development
  4. Start MongoDB (if running locally):

    mongod

Usage

Development Mode

bun run dev

This starts the server with hot reloading on http://localhost:3000.

Production Mode

bun run build
bun run start

Web Interface

Open http://localhost:3000 in your browser to access the web interface where you can:

  1. Enter your article topic and summary
  2. Select style, tone, and length preferences
  3. Choose your preferred AI model
  4. Add SEO keywords (optional)
  5. Generate the article with real-time progress updates

API Endpoints

Generate Article (Server-Sent Events)

Generates a complete article with real-time progress updates via Server-Sent Events (SSE).

POST /api/articles/generate
Content-Type: application/json

{
  "topic": "Climate Change Impact on Agriculture",
  "summary": "Exploring how climate change affects farming practices worldwide",
  "style": "feature",           // Optional: investigative, feature, breaking-news, opinion, interview, profile
  "tone": "formal",             // Optional: formal, casual, humorous, authoritative, conversational, academic
  "length": "medium",           // Optional: short, medium, long
  "model": "openai/gpt-4-turbo-preview", // Optional: any available model
  "keywords": ["climate change", "agriculture", "farming"] // Optional: array of SEO keywords
}

Response: Server-Sent Events stream with progress updates and final article data.

Enhanced Research Only

Performs comprehensive web-based research without generating an article.

POST /api/articles/research
Content-Type: application/json

{
  "topic": "Renewable Energy Trends 2024",
  "summary": "Current developments in renewable energy sector", // Optional
  "model": "openai/gpt-4-turbo-preview",                     // Optional
  "maxSources": 8,                                           // Optional: 1-15, default 8
  "includeFullContent": true,                                // Optional: default true
  "timeRange": "month"                                       // Optional: day, week, month, year, all
}

Response: JSON object with research results, sources, and AI-generated insights.

Get Available Models

Lists all available AI models and the default model.

GET /api/articles/models

Response:

{
  "models": ["openai/gpt-4-turbo-preview", "anthropic/claude-3-opus", "..."],
  "default": "openai/gpt-4-turbo-preview"
}

Get Article by ID

Retrieves a specific article by its MongoDB ObjectId.

GET /api/articles/:id

Parameters:

  • id: MongoDB ObjectId (24-character hexadecimal string)

List Articles (Paginated)

Retrieves a paginated list of articles.

GET /api/articles?limit=10&offset=0

Query Parameters:

  • limit: Number of articles to return (default: 10, max: 50)
  • offset: Number of articles to skip (default: 0)

Response:

{
  "articles": [...],
  "pagination": {
    "limit": 10,
    "offset": 0,
    "hasMore": true
  }
}

Health Check

Returns service health status and metrics.

GET /api/articles/health

Response:

{
  "status": "healthy",
  "timestamp": "2024-01-01T00:00:00.000Z",
  "service": "Article Generator API",
  "availableModels": 8
}

Project Structure

src/
├── config/
│   └── database.ts          # MongoDB connection
├── middleware/
│   └── errorHandler.ts      # Error handling middleware
├── models/
│   └── Article.ts           # Article data model
├── routes/
│   └── articles.ts          # API routes
├── services/
│   ├── ArticleGeneratorService.ts    # Main article generation logic
│   ├── EnhancedResearchService.ts    # Advanced web research with AI insights
│   ├── OpenRouterService.ts          # AI model integration
│   └── WebBrowsingService.ts         # Web content extraction and browsing
├── types/
│   ├── article.ts          # Article-related type definitions
│   └── api.ts              # API-related type definitions
├── utils/
│   └── helpers.ts          # Utility functions
└── index.ts                # Application entry point

Configuration

Environment Variables

Variable Description Default
OPENROUTER_API_KEY Your OpenRouter API key Required
MONGODB_URI MongoDB connection string mongodb://localhost:27017/article-generator
PORT Server port 3000
NODE_ENV Environment mode development
DEBUG Enable debug logging (1 or 0) 0
OPENROUTER_BASE_URL OpenRouter API base URL https://openrouter.ai/api/v1
DEFAULT_MODEL Default AI model openai/gpt-4o-mini
AVAILABLE_MODELS Comma-separated list of models See current model list below
RATE_LIMIT_WINDOW_MS Rate limit window (milliseconds) 900000 (15 minutes)
RATE_LIMIT_MAX_REQUESTS Max requests per window 100

Available AI Models

The following models are currently supported (as of default configuration):

  • openai/gpt-4o-mini (default)
  • google/gemini-2.5-flash
  • anthropic/claude-sonnet-4
  • anthropic/claude-3.7-sonnet
  • google/gemini-2.5-pro
  • x-ai/grok-4-fast
  • openai/gpt-4.1-mini

You can customize available models by setting the AVAILABLE_MODELS environment variable with a comma-separated list.

Article Styles

  • Feature: In-depth, magazine-style articles
  • Breaking News: Fast, factual reporting
  • Investigative: Deep-dive analysis with multiple sources
  • Opinion: Editorial and commentary pieces
  • Interview: Q&A format articles
  • Profile: Biographical or company profiles

Article Tones

  • Formal: Professional, business-like tone
  • Conversational: Friendly, accessible language
  • Authoritative: Expert, confident voice
  • Casual: Relaxed, informal style
  • Academic: Scholarly, research-oriented
  • Humorous: Light-hearted, entertaining

Article Lengths

  • Short: 300-600 words
  • Medium: 600-1200 words
  • Long: 1200-2500 words
  • Long-form: 2500+ words

API Integration

The application integrates with OpenRouter API to access multiple AI models. You'll need to:

  1. Sign up at OpenRouter
  2. Get your API key
  3. Add credits to your account
  4. Configure the API key in your .env file

Development

Type Checking

bun run type-check

File Structure

  • TypeScript: Strict typing enabled
  • ESM: Modern ES modules
  • Path Mapping: Convenient imports with @/ prefix
  • Error Handling: Comprehensive error management
  • Validation: Request validation with Zod

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests if applicable
  5. Submit a pull request

Deployment

Using Docker (Recommended)

FROM oven/bun:latest

WORKDIR /app
COPY package.json bun.lockb ./
RUN bun install --frozen-lockfile

COPY . .
RUN bun run build

EXPOSE 3000
CMD ["bun", "start"]

Manual Deployment

  1. Set up MongoDB on your server
  2. Configure environment variables
  3. Build the application: bun run build
  4. Start the application: bun start

Monitoring and Logging

The application includes:

  • Request logging
  • Error tracking
  • Performance monitoring
  • Health check endpoints
  • Rate limiting
  • CORS configuration
  • Security headers (Helmet)

Troubleshooting

Common Issues

  1. MongoDB Connection Failed: Check your MongoDB URI and ensure MongoDB is running
  2. OpenRouter API Errors: Verify your API key and account credits
  3. Rate Limiting: Reduce request frequency or increase limits
  4. Memory Issues: For long articles, consider increasing Node.js memory limit

Logs

Check console output for detailed error messages and debugging information.

License

MIT License - see LICENSE file for details.

Support

For issues and questions:

  1. Check the troubleshooting section
  2. Review the API documentation
  3. Create an issue on GitHub
  4. Contact support team

Built with ❤️ using Bun, TypeScript, Express, and MongoDB.

About

AI-powered article generator with research, drafting, editing, and finalizing stages

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published