Production-ready marketing analysis AI agent built with LangGraph and FastAPI. Analyzes market trends, competitor data, consumer sentiment, generates reports, and provides strategic recommendations using real data sources.
- π Market Trend Analysis - Analyze market trends, growth rates, and key market dynamics using Google Trends and real news data
- π’ Competitor Analysis - Evaluate competitor positioning, market share, strengths, and weaknesses
- π Consumer Sentiment Analysis - Analyze consumer sentiment across social media (Hacker News), news articles, and reviews
- π Report Generation - Generate comprehensive marketing reports in multiple formats
- π― Strategy Recommendations - Get actionable strategic recommendations based on business objectives
- π FastAPI REST API - Production-ready API with authentication, rate limiting, and comprehensive error handling
- π³ Docker Support - Full Docker and Docker Compose support for easy deployment
- π Free Data Sources - Uses only free/open-source services (no paid APIs required)
- Architecture
- Installation
- Configuration
- Usage
- API Documentation
- Data Sources
- Docker Deployment
- Development
The agent uses a node-based architecture where each analysis type is a dedicated node that executes based on boolean flags. This provides explicit control over which analyses run.
Request with boolean flags
β
[Market Trend Node] β [Competitor Analysis Node] β [Consumer Sentiment Node]
β β β
(if flag=true) (if flag=true) (if flag=true)
β
[Report Generation Node] β [Strategy Recommendation Node] β [Synthesis Node]
β β β
(if flag=true) (if flag=true) (always runs)
- Nodes: Analysis components (market_trend, competitor_analysis, etc.)
- Tools: Helper utilities used by nodes (web search, scraping, data sources)
- State Management: TypedDict-based state passing between nodes
- LLM Integration: OpenAI GPT-4o for query analysis and synthesis
- Python 3.11 or higher
- OpenAI API key
pip install -r requirements.txtFor advanced web scraping capabilities:
playwright install chromiumOpenAI API Key (Required)
export OPENAI_API_KEY=your_openai_api_key_hereOr create a .env file:
OPENAI_API_KEY=your_openai_api_key_hereSelf-Hosted SearXNG Search Service (Required for full functionality)
You need to self-host your own SearXNG instance. The agent uses SearXNG's API to fetch news articles and search results.
Option 1: Docker (Recommended)
docker run -d -p 8080:8080 \
-e SEARXNG_HOSTNAME=localhost \
searxng/searxng:latestThen set in your .env:
SEARCH_SERVICE_URL=http://localhost:8080Option 2: Docker Compose
Create a docker-compose.searxng.yml:
version: '3.8'
services:
searxng:
image: searxng/searxng:latest
ports:
- "8080:8080"
environment:
- SEARXNG_HOSTNAME=localhostRun: docker-compose -f docker-compose.searxng.yml up -d
Option 3: Manual Installation
Follow the SearXNG installation guide.
Configuration
Once SearXNG is running, set the URL in your .env:
SEARCH_SERVICE_URL=http://your-searxng-instance:8080Self-Hosted Scraper (Optional)
SCRAPER_SERVICE_URL=https://your-scraper-url.comYouTube Data API (Optional)
YOUTUBE_API_KEY=your_youtube_api_keyAPI Security (For FastAPI)
API_KEY=your_secret_api_key
RATE_LIMIT_PER_MINUTE=10
CORS_ORIGINS=*Server Configuration
PORT=8000
HOST=0.0.0.0
DEBUG=falseThe agent uses only free/open-source services:
- β Google Trends (pytrends) - Market trends and search interest (no setup required)
- β Self-hosted SearXNG - News articles and web search (you must self-host)
- β Hacker News API - Social media sentiment (no auth required)
- β YouTube Data API - Video content analysis (free tier, optional)
- β RSS Feeds - News articles (fallback, no setup required)
- β Playwright Scraper - Advanced web scraping (optional, install Playwright)
# Development
python main.py
# Or with uvicorn
uvicorn main:app --reload --host 0.0.0.0 --port 8000
# Production (with Gunicorn)
gunicorn -w 5 -k uvicorn.workers.UvicornWorker -b 0.0.0.0:8000 main:appHealth Check
curl http://localhost:8000/healthPerform Analysis
curl -X POST "http://localhost:8000/api/v1/analyze" \
-H "X-API-Key: your_secret_api_key" \
-H "Content-Type: application/json" \
-d '{
"query": "Analyze market trends for AI tools in last year",
"market_trend": true,
"competitor_analysis": true,
"consumer_sentiment": true,
"report_generation": false,
"strategy_recommendation": false
}'Interactive API Documentation
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
from marketing_analyst_agent import create_agent
# Create agent
agent = create_agent()
# Process analysis
result = await agent.process(
query="Analyze market trends for AI agents in 2025",
run_market_trend=True,
run_competitor_analysis=True,
run_consumer_sentiment=True,
run_report_generation=False,
run_strategy_recommendation=False
)
# Access results
print(result["analysis_result"]["content"])
print(result["data_logs"]){
"query": "Analyze market trends for AI tools in last year",
"market_trend": true,
"competitor_analysis": true,
"consumer_sentiment": true,
"report_generation": true,
"strategy_recommendation": true
}{
"status": "success",
"query": "Analyze market trends for AI tools in last year",
"result": {
"status": "success",
"processing_status": "completed",
"analysis_content": "# Marketing Analysis Report\n\n...",
"market_data": {...},
"competitor_data": {...},
"sentiment_data": {...},
"data_logs": [...],
"metadata": {
"summary": "...",
"key_insights": [...],
"recommendations": [...],
"confidence_score": 85
}
},
"output_files": {
"markdown": "output/analysis_20251206_120000.md",
"info": "output/analysis_20251206_120000_info.txt"
}
}The API uses API key authentication via the X-API-Key header:
curl -H "X-API-Key: your_secret_api_key" ...If API_KEY is not set in environment variables, the API is accessible without authentication (not recommended for production).
Default: 10 requests per minute (configurable via RATE_LIMIT_PER_MINUTE)
- Google Trends - Search interest and trend data (no setup required)
- Self-hosted SearXNG - News articles about market segment (requires self-hosting)
- RSS Feeds - Additional news sources (fallback, no setup required)
- Self-hosted SearXNG - Competitor news and articles (requires self-hosting)
- Google Trends - Search interest per competitor (no setup required)
- Playwright Scraper - Competitor website analysis (optional, install Playwright)
- Hacker News - Social media sentiment (primary, no auth required)
- YouTube - Video content sentiment (optional, requires API key)
- Self-hosted SearXNG - News sentiment (requires self-hosting)
- RSS Feeds - Additional news sources (fallback, no setup required)
- Create
.envfile:
OPENAI_API_KEY=your_openai_api_key
API_KEY=your_secret_api_key
SEARCH_SERVICE_URL=http://your-searxng-instance:8080Note: Make sure you have SearXNG running (see Self-Hosted SearXNG Setup above).
- Build and run:
docker-compose up -d- Check logs:
docker-compose logs -fdocker build -t marketing-analyst-agent .
docker run -p 8000:8000 \
-e OPENAI_API_KEY=your_key \
-e API_KEY=your_secret \
-v $(pwd)/output:/app/output \
marketing-analyst-agentResults are saved to the output folder:
analysis_[timestamp].md- Comprehensive analysis report in markdownanalysis_[timestamp]_info.txt- Analysis metadata, insights, and data logs
Markdown File:
- Executive Summary
- Key Findings
- Detailed Analysis
- Strategic Recommendations
- Next Steps
Info File:
- Analysis summary
- Key insights
- Recommendations
- Confidence score
- Data sources used
- Detailed data fetching logs
marketing_analyst_agent/
βββ main.py # FastAPI application
βββ marketing_analyst_agent.py # Core agent implementation
βββ tools/
β βββ market_data.py # Market analysis tools
β βββ data_sources.py # Data source clients
β βββ report.py # Report generation
β βββ strategy.py # Strategy recommendations
β βββ advanced_scraper.py # Playwright scraper (optional)
βββ output/ # Generated reports
βββ requirements.txt # Python dependencies
βββ Dockerfile # Docker configuration
βββ docker-compose.yml # Docker Compose setup
βββ README.md # This file
# Check syntax
python -m py_compile marketing_analyst_agent.py main.py
# Run with example query
python -c "from marketing_analyst_agent import create_agent; import asyncio; asyncio.run(create_agent().process('test query'))"The project follows production-ready practices:
- β Type hints throughout
- β Comprehensive error handling
- β Input validation and sanitization
- β Security best practices (API keys, rate limiting)
- β Docker support for deployment
- β Proper logging and monitoring
- API Key Authentication - Configurable API key protection
- Rate Limiting - Prevents abuse
- Input Validation - Pydantic models for request validation
- CORS Configuration - Configurable cross-origin policies
- Error Handling - Comprehensive error handling without exposing internals
- "Analyze market trends in the mobile gaming industry over the last 3 months"
- "Compare our competitors: Apple, Samsung, and Google in the smartphone market"
- "What is the consumer sentiment around our new product launch?"
- "Generate a comprehensive market overview report for Q1 2024"
- "Provide strategic recommendations to increase market share in the SaaS industry"
This project is part of an agent automation suite. Contributions are welcome!
This project is part of the agent automation suite.
- Built with LangGraph for agent orchestration
- Uses FastAPI for the REST API
- Powered by OpenAI GPT-4o for analysis and synthesis