Skip to content

Latest commit

Β 

History

3 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Content Discovery Agent

A FastAPI + LangGraph project for automated content discovery, link building opportunity identification, and topic discovery using AI-powered workflows.

Project Structure

This project follows a modular, agentic architecture:

blog_automation/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ main.py                    # FastAPI application entry point
β”‚   β”‚
β”‚   β”œβ”€β”€ api/                       # API Layer
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ link_creator_routes.py      # Link Creator Discovery API routes
β”‚   β”‚   β”œβ”€β”€ topic_discovery_routes.py   # Topic Discovery API routes
β”‚   β”‚   β”œβ”€β”€ common_routes.py            # Common endpoints (health check)
β”‚   β”‚   └── routes.py                   # Deprecated (backwards compatibility)
β”‚   β”‚
β”‚   β”œβ”€β”€ config/                    # Configuration
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   └── settings.py            # Environment-based settings
β”‚   β”‚
β”‚   β”œβ”€β”€ models/                    # Data Models (Pydantic & TypedDict)
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ agent_state.py         # Link Creator workflow state schema
β”‚   β”‚   β”œβ”€β”€ topic_discovery_state.py  # Topic Discovery workflow state schema
β”‚   β”‚   β”œβ”€β”€ request_models.py      # API request models
β”‚   β”‚   β”œβ”€β”€ response_models.py     # API response models
β”‚   β”‚   β”œβ”€β”€ domain_models.py       # Domain-specific models
β”‚   β”‚   └── mongodb_models.py      # MongoDB document models
β”‚   β”‚
β”‚   β”œβ”€β”€ services/                  # Business Logic Layer
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   β”œβ”€β”€ orchestration_service.py          # Link Creator workflow orchestrator
β”‚   β”‚   β”œβ”€β”€ topic_discovery_orchestration_service.py  # Topic Discovery orchestrator
β”‚   β”‚   β”œβ”€β”€ llm_service.py            # Google Gemini LLM wrapper
β”‚   β”‚   β”œβ”€β”€ mongo_service.py          # MongoDB service
β”‚   β”‚   β”œβ”€β”€ google_search_service.py  # Google Search API integration
β”‚   β”‚   β”œβ”€β”€ crawler_service.py        # Web scraping service
β”‚   β”‚   β”œβ”€β”€ agent/                 # Workflow Nodes
β”‚   β”‚   β”‚   β”œβ”€β”€ link_creator/      # Link Creator Discovery nodes
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ generate_search_query.py
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ google_search.py
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ social_page.py
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ skip.py
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ scrape_pages.py
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ verify_blog_page.py
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ validate_link_creator.py
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ store_results.py
β”‚   β”‚   β”‚   β”‚   └── prompt_builders.py
β”‚   β”‚   β”‚   └── topic_discovery/   # Topic Discovery nodes
β”‚   β”‚   β”‚       β”œβ”€β”€ fetch_link_creators.py
β”‚   β”‚   β”‚       β”œβ”€β”€ process_link_creators.py
β”‚   β”‚   β”‚       β”œβ”€β”€ find_common_topics.py
β”‚   β”‚   β”‚       β”œβ”€β”€ analyze_meta_trends.py
β”‚   β”‚   β”‚       └── save_topic_discovery.py
β”‚   β”‚   └── utils/                 # Service Utilities
β”‚   β”‚       β”œβ”€β”€ __init__.py
β”‚   β”‚       β”œβ”€β”€ parsers.py
β”‚   β”‚       └── validators.py
β”‚   β”‚
β”‚   β”œβ”€β”€ compat/                    # Compatibility Layer
β”‚   β”‚   └── __init__.py
β”‚   β”‚
β”‚   └── utils/                     # General Utilities
β”‚       β”œβ”€β”€ __init__.py
β”‚       └── visualization.py
β”‚
β”œβ”€β”€ main.py                        # Application entry point (wrapper)
β”œβ”€β”€ requirements.txt               # Python dependencies
β”œβ”€β”€ .env.example                   # Environment variable template
β”œβ”€β”€ .gitignore                     # Git ignore patterns
└── README.md                      # This file

Features

  • FastAPI: Modern, fast web framework for REST API
  • LangGraph: Stateful workflow orchestration for agentic AI
  • Google Gemini: LLM integration for intelligent query generation, content analysis, and topic extraction
  • MongoDB: Full database integration with persistence for discovery results and topic analysis
  • Pydantic: Type-safe data validation
  • Modular Architecture: Separation of concerns with clear layer boundaries
  • Two Workflows:
    • Link Creator Discovery: Finds and validates link building opportunities
    • Topic Discovery: Analyzes discovered content to find common topics and trends

Workflow Overview

Link Creator Discovery Workflow

  1. Generate Search Query: Creates optimized search queries based on business context
  2. Google Search: Performs search using generated queries
  3. Social Page Detection: Identifies and routes social media pages
  4. Skip & Feedback Loop: Skips social pages and refines queries (up to MAX_SKIP_COUNT iterations)
  5. Scrape Pages: Extracts content from search results
  6. Verify Blog Page: Validates if pages are actual blog posts (/blog, /blogs patterns)
  7. Validate Link Creator: Extracts and validates contact information from blog pages
  8. Store Results: Saves validated opportunities to MongoDB

Topic Discovery Workflow

  1. Fetch Link Creators: Retrieves previously discovered link creators from MongoDB
  2. Process Link Creators: Analyzes blog content from link creators to extract topics per domain
  3. Find Common Topics: Aggregates topics across domains, deduplicates similar topics, and identifies common themes
  4. Analyze Meta Trends: (Optional) Performs advanced trend analysis on discovered topics
  5. Save Results: Persists topic discovery results to MongoDB with metadata and statistics

Setup

  1. Clone the repository:

    git clone <repository-url>
    cd blog_automation
  2. Create a virtual environment (recommended):

    python -m venv venv
    # On Windows:
    venv\Scripts\activate
    # On macOS/Linux:
    source venv/bin/activate
  3. Install dependencies:

    pip install -r requirements.txt
  4. Set up environment variables:

    • Copy the example environment file:
      # On Windows:
      copy .env.example .env
      # On macOS/Linux:
      cp .env.example .env
    • Edit .env and add your actual values (see .env.example for all options)
    • Required variables:
      • GOOGLE_API_KEY: Your Google Gemini API key (get from Google AI Studio)
      • MONGODB_URL: MongoDB connection string (default: mongodb://localhost:27017)
    • Optional but recommended:
      • GOOGLE_SEARCH_API_KEY + GOOGLE_SEARCH_ENGINE_ID: For better search results
  5. Start MongoDB (if running locally):

    # Make sure MongoDB is running on your system
    # On Windows (if installed as service):
    # MongoDB should start automatically
    # On macOS (with Homebrew):
    brew services start mongodb-community
    # On Linux:
    sudo systemctl start mongod
  6. Run the application:

    python main.py

    Or using uvicorn directly:

    uvicorn app.main:app --reload --port 8001
  7. Access the API:

API Endpoints

POST /api/v1/content-discovery

Execute the Link Creator Discovery workflow to find link building opportunities.

Request:

{
  "userId": "user123",
  "size": "medium",
  "companyName": "Example Corp",
  "industry": "Technology",
  "niche": "SaaS",
  "websiteUrl": "https://example.com",
  "offer": "Free trial for 30 days"
}

Response:

{
  "success": true,
  "message": "Content discovery completed successfully",
  "results": [
    {
      "url": "https://example.com/blog/post",
      "name": "John Doe",
      "email": "john@example.com",
      "domain": "example.com",
      "title": "Blog Post Title",
      "description": "Blog post description..."
    }
  ],
  "total_results": 5,
  "execution_time_ms": 1234.56,
  "request_id": "uuid-here"
}

POST /api/v1/topic-discovery

Execute the Topic Discovery workflow to analyze discovered link creators and find common topics.

Request:

{
  "userId": "user123"
}

Response:

{
  "success": true,
  "message": "Topic discovery completed successfully",
  "data": {
    "userId": "user123",
    "totalLinkCreators": 10,
    "totalDomains": 8,
    "commonTopics": [
      {
        "topic": "AI-powered content creation",
        "count": 5,
        "domains": ["domain1.com", "domain2.com"]
      }
    ],
    "executionTimeMs": 2345.67,
    "timestamp": "2024-01-01T00:00:00Z"
  },
  "execution_time_ms": 2345.67,
  "request_id": "uuid-here"
}

GET /api/v1/health

Health check endpoint.

Response:

{
  "status": "healthy",
  "service": "Content Discovery Agent"
}

GET /

Root endpoint with API information and available endpoints.

Configuration

All configuration is managed through environment variables. See .env.example for a complete template with all available options and descriptions.

Required Variables

  • GOOGLE_API_KEY: Your Google Gemini API key (required for LLM operations)

MongoDB Configuration

  • MONGODB_URL: MongoDB connection string (default: mongodb://localhost:27017)
  • MONGODB_DATABASE: Database name (default: blog_automation)
  • MONGODB_COLLECTION: Collection for link creator results (default: discovery_results)
  • MONGODB_TOPIC_DISCOVERY_COLLECTION: Collection for topic discovery results (default: topicDiscovery)

Optional Variables

  • GOOGLE_SEARCH_API_KEY + GOOGLE_SEARCH_ENGINE_ID: For enhanced Google Search API results
  • MODEL_NAME: LLM model name (default: gemini-2.0-flash-lite)
  • TEMPERATURE: LLM temperature 0.0-1.0 (default: 0.7)
  • MAX_SCRAPE_ITERATIONS: Maximum pages to scrape (default: 10, lower for testing)
  • MAX_SKIP_COUNT: Maximum social page skip iterations (default: 10)
  • LOG_LEVEL: Logging level - DEBUG, INFO, WARNING, ERROR (default: INFO)

Features & Capabilities

Link Creator Discovery

  • βœ… Automated search query generation using AI
  • βœ… Google Search integration (with Custom Search API support)
  • βœ… Social media page detection and filtering
  • βœ… Web scraping with content extraction
  • βœ… Blog page verification (URL pattern matching)
  • βœ… Contact information extraction and validation
  • βœ… MongoDB persistence with full document storage

Topic Discovery

  • βœ… Link creator data retrieval from MongoDB
  • βœ… AI-powered topic extraction from blog content
  • βœ… Domain-level topic analysis
  • βœ… Intelligent topic deduplication (merges similar/subset topics)
  • βœ… Common topic aggregation across domains
  • βœ… Metadata and statistics tracking
  • βœ… MongoDB persistence with structured topic data

Technical Features

  • βœ… LangGraph workflow orchestration with state management
  • βœ… Type-safe models with Pydantic validation
  • βœ… Comprehensive error handling and logging
  • βœ… Async/await support for better performance
  • βœ… CORS middleware for API access
  • βœ… Interactive API documentation (Swagger/ReDoc)

Architecture Principles

  • Separation of Concerns: Clear boundaries between Models, Services, Nodes, and API layers
  • Dependency Injection: Factory functions for node creation with dependency injection
  • Type Safety: Pydantic models for API validation, TypedDict for LangGraph state management
  • Modularity: Each component has a single, well-defined responsibility
  • State-Driven: Central state flows through all nodes in the workflow
  • Error Resilience: Comprehensive error handling with graceful degradation
  • Scalability: Async/await patterns for better performance and resource utilization

Testing

Using Postman or cURL

  1. Link Creator Discovery:

    curl -X POST http://localhost:8001/api/v1/content-discovery \
      -H "Content-Type: application/json" \
      -d '{
        "userId": "test123",
        "size": "medium",
        "companyName": "Example Corp",
        "industry": "Technology",
        "niche": "SaaS",
        "websiteUrl": "https://example.com",
        "offer": "Free trial for 30 days"
      }'
  2. Topic Discovery (after link creators are discovered):

    curl -X POST http://localhost:8001/api/v1/topic-discovery \
      -H "Content-Type: application/json" \
      -d '{
        "userId": "test123"
      }'

Troubleshooting

Common Issues

  1. MongoDB Connection Error:

    • Ensure MongoDB is running: mongosh or check service status
    • Verify MONGODB_URL in .env is correct
    • Check database name (will be normalized to lowercase)
  2. Google API Key Error:

    • Verify GOOGLE_API_KEY is set in .env
    • Check API key is valid and has quota remaining
    • Ensure key has access to Gemini API
  3. Empty Results from Topic Discovery:

    • Make sure Link Creator Discovery has been run first for the same userId
    • Check MongoDB to verify data was saved correctly
    • Review logs for any errors during topic extraction
  4. Port Already in Use:

    • Default port is 8001 (to avoid conflict with crawler on 8000)
    • Change FASTAPI_PORT in .env or modify main.py

Notes

  • Database names are automatically normalized to lowercase in MongoDB
  • Topic deduplication uses intelligent similarity matching (80% threshold)
  • Set MAX_SCRAPE_ITERATIONS=3 for faster testing during development
  • All API endpoints support CORS (configure appropriately for production)
  • Interactive API docs available at /docs endpoint

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages