A FastAPI + LangGraph project for automated content discovery, link building opportunity identification, and topic discovery using AI-powered workflows.
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
- 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
- Generate Search Query: Creates optimized search queries based on business context
- Google Search: Performs search using generated queries
- Social Page Detection: Identifies and routes social media pages
- Skip & Feedback Loop: Skips social pages and refines queries (up to MAX_SKIP_COUNT iterations)
- Scrape Pages: Extracts content from search results
- Verify Blog Page: Validates if pages are actual blog posts (/blog, /blogs patterns)
- Validate Link Creator: Extracts and validates contact information from blog pages
- Store Results: Saves validated opportunities to MongoDB
- Fetch Link Creators: Retrieves previously discovered link creators from MongoDB
- Process Link Creators: Analyzes blog content from link creators to extract topics per domain
- Find Common Topics: Aggregates topics across domains, deduplicates similar topics, and identifies common themes
- Analyze Meta Trends: (Optional) Performs advanced trend analysis on discovered topics
- Save Results: Persists topic discovery results to MongoDB with metadata and statistics
-
Clone the repository:
git clone <repository-url> cd blog_automation
-
Create a virtual environment (recommended):
python -m venv venv # On Windows: venv\Scripts\activate # On macOS/Linux: source venv/bin/activate
-
Install dependencies:
pip install -r requirements.txt
-
Set up environment variables:
- Copy the example environment file:
# On Windows: copy .env.example .env # On macOS/Linux: cp .env.example .env
- Edit
.envand add your actual values (see.env.examplefor 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
- Copy the example environment file:
-
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
-
Run the application:
python main.py
Or using uvicorn directly:
uvicorn app.main:app --reload --port 8001
-
Access the API:
- API Base: http://localhost:8001
- Interactive docs (Swagger): http://localhost:8001/docs
- Alternative docs (ReDoc): http://localhost:8001/redoc
- Health check: http://localhost:8001/api/v1/health
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"
}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"
}Health check endpoint.
Response:
{
"status": "healthy",
"service": "Content Discovery Agent"
}Root endpoint with API information and available endpoints.
All configuration is managed through environment variables. See .env.example for a complete template with all available options and descriptions.
GOOGLE_API_KEY: Your Google Gemini API key (required for LLM operations)
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)
GOOGLE_SEARCH_API_KEY+GOOGLE_SEARCH_ENGINE_ID: For enhanced Google Search API resultsMODEL_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)
- β 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
- β 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
- β 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)
- 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
-
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" }'
-
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" }'
-
MongoDB Connection Error:
- Ensure MongoDB is running:
mongoshor check service status - Verify
MONGODB_URLin.envis correct - Check database name (will be normalized to lowercase)
- Ensure MongoDB is running:
-
Google API Key Error:
- Verify
GOOGLE_API_KEYis set in.env - Check API key is valid and has quota remaining
- Ensure key has access to Gemini API
- Verify
-
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
- Make sure Link Creator Discovery has been run first for the same
-
Port Already in Use:
- Default port is 8001 (to avoid conflict with crawler on 8000)
- Change
FASTAPI_PORTin.envor modifymain.py
- Database names are automatically normalized to lowercase in MongoDB
- Topic deduplication uses intelligent similarity matching (80% threshold)
- Set
MAX_SCRAPE_ITERATIONS=3for faster testing during development - All API endpoints support CORS (configure appropriately for production)
- Interactive API docs available at
/docsendpoint