# Input Parameters Source: https://company-research-agent.pratikdani.com/api-reference/input Input schema and parameters for the Company Research & Analysis Agent # Input Parameters The Company Research & Analysis Agent uses a simple input schema that triggers the CrewAI research process. ## Input Schema ```json theme={null} { "title": "Company Research Agent Input", "type": "object", "schemaVersion": 1, "properties": { "domain": { "title": "Company Domain", "type": "string", "description": "Domain name of the company to research (e.g., apple.com)", "editor": "textfield" } }, "required": ["domain"] } ``` ## Parameters The domain name of the company you want to research. This will be used by the AI agents to: 1. Search for company news 2. Find professional profiles 3. Gather LinkedIn data 4. Collect Crunchbase information 5. Extract PitchBook details **Examples:** * `apple.com` * `microsoft.com` * `tesla.com` ## Input Processing The domain input goes through several processing steps: 1. **Validation** ```python theme={null} async def validate_domain(domain: str) -> str: """ @param domain - Raw domain name input @returns Cleaned and validated domain name @throws ValueError if domain is invalid """ if not domain: raise ValueError("Domain is required") # Remove protocol and www domain = re.sub(r'^(https?://)?(www\.)?', '', domain.lower()) # Remove trailing path domain = domain.split('/')[0] if not validators.domain(domain): raise ValueError(f"Invalid domain: {domain}") return domain ``` 2. **AI Agent Assignment** The validated domain is passed to the Research Specialist agent, which coordinates with other agents to gather information. ## Environment Variables The following environment variables are required: Your Apify API token for accessing web scraping capabilities Google API key for the Gemini model used by AI agents ## Error Cases The agent will fail with an error message if: 1. **Domain Validation** * No domain is provided * Domain format is invalid * Domain cannot be resolved 2. **API Access** * Invalid or missing API tokens * Rate limits exceeded * API service unavailable 3. **AI Processing** * LLM service unavailable * Invalid response format * Processing timeout ## Example Usage ### Basic Input ```json theme={null} { "domain": "apple.com" } ``` ### Input with Auto-Cleaning ```json theme={null} { "domain": "https://www.microsoft.com/en-us" } // Will be processed as: "microsoft.com" ``` The input system is designed to be user-friendly. It automatically cleans and normalizes the domain input, allowing users to provide URLs in various formats. # Output Format Source: https://company-research-agent.pratikdani.com/api-reference/output Understanding the output format of the Company Research & Analysis Agent # Output Format The Company Research & Analysis Agent produces a comprehensive output that combines insights from multiple AI agents. ## Output Schema ```json theme={null} { "title": "Company Research Agent Output", "type": "object", "schemaVersion": 1, "properties": { "company_info": { "type": "object", "description": "Basic company information", "properties": { "name": "string", "domain": "string", "description": "string", "industry": "string", "founded_year": "integer", "headquarters": "string" } }, "research_data": { "type": "object", "description": "Raw research data from various sources", "properties": { "linkedin_data": "object", "crunchbase_data": "object", "pitchbook_data": "object", "news_articles": "array" } }, "analysis": { "type": "object", "description": "AI-generated analysis and insights", "properties": { "market_position": "string", "competitive_advantages": "array", "growth_metrics": "object", "risk_factors": "array" } }, "report": { "type": "object", "description": "Structured report compiled by AI", "properties": { "executive_summary": "string", "detailed_sections": "array", "key_findings": "array", "recommendations": "array" } }, "metadata": { "type": "object", "description": "Information about the research process", "properties": { "research_timestamp": "string", "data_sources": "array", "completion_status": "string" } } } } ``` ## Output Components ### 1. Company Information Basic company details gathered by the Research Specialist: ```json theme={null} { "company_info": { "name": "Apple Inc.", "domain": "apple.com", "description": "Technology company that designs, manufactures, and markets smartphones, computers, and consumer electronics", "industry": "Consumer Electronics", "founded_year": 1976, "headquarters": "Cupertino, California, United States" } } ``` ### 2. Research Data Raw data collected from various sources: ```json theme={null} { "research_data": { "linkedin_data": { "employee_count": 164000, "followers": 28000000, "specialties": ["..."], "recent_updates": ["..."] }, "crunchbase_data": { "funding_rounds": ["..."], "investors": ["..."], "acquisitions": ["..."] }, "pitchbook_data": { "financials": {"..."}, "market_share": {"..."}, "competitors": ["..."] }, "news_articles": [ { "title": "...", "url": "...", "date": "...", "summary": "..." } ] } } ``` ### 3. Analysis AI-generated insights from the Data Analyst: ```json theme={null} { "analysis": { "market_position": "Industry leader in consumer electronics and services", "competitive_advantages": [ "Strong brand recognition", "Vertical integration", "Innovation capability" ], "growth_metrics": { "revenue_growth": "12%", "market_share_trend": "Increasing", "expansion_rate": "High" }, "risk_factors": [ "Supply chain dependencies", "Regulatory challenges", "Market saturation" ] } } ``` ### 4. Report Structured report from the Content Compiler: ```json theme={null} { "report": { "executive_summary": "Comprehensive overview of company status...", "detailed_sections": [ { "title": "Business Overview", "content": "..." }, { "title": "Market Analysis", "content": "..." } ], "key_findings": [ "Strong market position in premium segment", "Diversifying revenue streams", "Expanding services portfolio" ], "recommendations": [ "Monitor emerging competitors", "Focus on service expansion", "Strengthen supply chain" ] } } ``` ### 5. Metadata Information about the research process: ```json theme={null} { "metadata": { "research_timestamp": "2024-01-20T10:30:00Z", "data_sources": [ "LinkedIn", "Crunchbase", "PitchBook", "Google News" ], "completion_status": "success" } } ``` ## Output Processing The output goes through several stages: 1. **Data Collection** * Raw data gathered by Research Specialist * Multiple sources accessed in parallel 2. **Analysis** * Data Analyst processes raw information * Pattern recognition and insight extraction 3. **Report Generation** * Content Compiler structures findings * Formats for readability and clarity ## Error Handling The output includes error information when applicable: ```json theme={null} { "error": { "code": "DATA_SOURCE_ERROR", "message": "Unable to access LinkedIn data", "source": "linkedin_scraper", "timestamp": "2024-01-20T10:30:00Z" } } ``` The output format is designed to be both machine-readable and human-friendly. The structured data can be used programmatically, while the report sections provide narrative insights. # API Reference Source: https://company-research-agent.pratikdani.com/api-reference/overview Complete API reference for the Company Research & Analysis Agent # API Reference The Company Research & Analysis Agent provides a RESTful API through the Apify platform. This reference documents all available endpoints, parameters, and response formats. ## Authentication All API requests require authentication using your Apify API token. You can find your API token in the [Apify Console](https://console.apify.com/account/integrations). ```bash theme={null} # Include your API token in the request URL https://api.apify.com/v2/acts/pratikdani~company-research-analysis-agent/runs?token=YOUR_API_TOKEN ``` ## Base URL ``` https://api.apify.com/v2/acts/pratikdani~company-research-analysis-agent ``` ## Endpoints ### Start a Run ```http theme={null} POST /runs ``` Starts a new actor run with the provided input. ### Get Run Status ```http theme={null} GET /runs/{runId} ``` Retrieves the status of a specific actor run. ### Get Run Results ```http theme={null} GET /runs/{runId}/dataset/items ``` Retrieves the results of a completed actor run. ## Rate Limits The actor is subject to Apify's standard rate limits: * Maximum 5 concurrent actor runs per user * Maximum runtime of 24 hours per run ## Error Handling The API uses standard HTTP response codes: * 200: Success * 400: Bad request * 401: Unauthorized * 429: Too many requests * 500: Internal server error ## SDKs and Libraries Official SDKs are available for: * [Python](https://docs.apify.com/apify-client-python) * [JavaScript](https://docs.apify.com/apify-client-js) * [Other languages](https://docs.apify.com/api/client) # Agent Specifications Source: https://company-research-agent.pratikdani.com/architecture/agents Detailed documentation of the specialized AI agents # Agent Specifications The Company Research Agent uses three specialized AI agents, each with a specific role in the research process. This document details each agent's configuration and responsibilities. ## Researcher Agent The primary data gathering agent. ```python theme={null} @agent def researcher(self) -> Agent: """ @agent Company Research Specialist @description Expert in gathering comprehensive company information @returns Agent - Configured researcher agent """ return Agent( role="Company Research Specialist", goal="Gather comprehensive information about companies from various sources", backstory="""You are an expert business researcher with years of experience in gathering and analyzing company information. You excel at finding accurate and relevant details about organizations, their products, and market presence.""", tools=[ CompanyNewsSearchTool(actor=self.actor), ProfessionalProfilesTool(actor=self.actor), LinkedInScraperTool(actor=self.actor), CrunchbaseScraperTool(actor=self.actor), PitchBookScraperTool(actor=self.actor), GoogleSearchTool(actor=self.actor) ], llm=self.llm ) ``` ### Researcher Capabilities Finds and analyzes recent news articles about the company Locates company profiles across professional platforms Extracts detailed information from various sources Performs targeted Google searches for specific information ## Data Analyst Agent Processes and analyzes gathered information. ```python theme={null} @agent def data_analyst(self) -> Agent: """ @agent Business Data Analyst @description Expert in analyzing company data and extracting insights @returns Agent - Configured analyst agent """ return Agent( role="Business Data Analyst", goal="Analyze company data and extract meaningful insights", backstory="""You are a skilled data analyst specializing in business metrics and market analysis. You have a strong background in interpreting company performance data and identifying market trends.""", llm=self.llm ) ``` ### Analysis Capabilities * Market trend identification * Financial metric analysis * Competitive landscape assessment * Growth pattern recognition * Risk factor identification ## Content Compiler Agent Formats and structures the research findings. ```python theme={null} @agent def content_compiler(self) -> Agent: """ @agent Business Report Writer @description Expert in creating comprehensive business reports @returns Agent - Configured compiler agent """ return Agent( role="Business Report Writer", goal="Compile research findings into comprehensive, well-structured reports", backstory="""You are an experienced business writer who excels at organizing complex information into clear, actionable reports. You have a keen eye for important details and can present information in a professional format.""", llm=self.llm ) ``` ### Compilation Capabilities * Report structuring * Key insight highlighting * Data visualization recommendations * Executive summary creation * Action item identification ## Agent Interaction Flow ```mermaid theme={null} graph TD A[Researcher Agent] -->|Raw Data| B[Data Analyst Agent] B -->|Analyzed Data| C[Content Compiler Agent] C -->|Final Report| D[Output] ``` ## Configuration Parameters ### Common Parameters | Parameter | Type | Description | | --------- | ------ | ----------------------- | | role | string | Agent's specific role | | goal | string | Primary objective | | backstory | string | Context and expertise | | llm | LLM | Language model instance | ### Researcher-Specific Parameters | Parameter | Type | Description | | --------- | --------------- | ------------------------ | | tools | List\[BaseTool] | Available research tools | | verbose | boolean | Output verbosity | ## Best Practices 1. **Agent Independence** * Each agent operates independently * Clear separation of responsibilities * Minimal cross-agent dependencies 2. **Error Handling** * Agents handle task-specific errors * Graceful failure recovery * Clear error reporting 3. **Performance Optimization** * Efficient tool usage * Resource management * Output filtering Agents are designed to be autonomous but collaborative. Each agent focuses on its specific role while contributing to the overall research objective. # CrewAI Implementation Source: https://company-research-agent.pratikdani.com/architecture/crew Detailed documentation of the CrewAI implementation # CrewAI Implementation The Company Research Agent uses CrewAI to coordinate multiple AI agents in gathering and analyzing company information. This document details the implementation of the `CompanyResearchCrew` class. ## Class Overview ```python theme={null} @CrewBase class CompanyResearchCrew: """ @class CompanyResearchCrew @description Coordinates multiple AI agents for comprehensive company research @param actor - Apify Actor instance for web scraping operations """ ``` ## Initialization ```python theme={null} def __init__(self, actor): self.actor = actor self.llm = LLM( model="gemini/gemini-2.0-flash-lite", temperature=0.7, api_key=os.getenv("GOOGLE_API_KEY") ) ``` ## Tasks The crew executes three main tasks: ### 1. Research Company ```python theme={null} @task def research_company(self) -> Task: """ @task Research company details using domain name @returns Task - Research task configuration """ return Task( description="""Research the company using their domain name: {domain}. Focus on key insights about the company's: 1. Overview and core business 2. Products and services 3. Market presence and performance 4. Key personnel and organization 5. Financial metrics and funding 6. Technology stack and digital presence 7. Recent developments and news 8. Major Competitors""", agent=self.researcher() ) ``` ### 2. Analyze Data ```python theme={null} @task def analyze_data(self) -> Task: """ @task Analyze gathered company data @returns Task - Analysis task configuration """ return Task( description="""Analyze the research findings to extract key insights about: 1. business focus, 2. product lineup, 3. market and demographic details, 4. funding rounds, 5. notable executives, 6. social media profiles, 7. a list of major competitors""", agent=self.data_analyst() ) ``` ### 3. Compile Report ```python theme={null} @task def compile_report(self) -> Task: """ @task Compile findings into a structured report @returns Task - Report compilation task configuration """ return Task( description="""Create a comprehensive report combining all research and analysis. Structure the information clearly and highlight key findings.""", expected_output="Final structured report in JSON format", agent=self.content_compiler() ) ``` ## Crew Configuration The crew is configured to work sequentially: ```python theme={null} @crew def crew(self) -> Crew: """ @returns Crew - Configured CrewAI crew """ return Crew( agents=[ self.researcher(), self.data_analyst(), ], tasks=[ self.research_company(), self.analyze_data(), ], process=Process.sequential, verbose=True, max_rpm=100, show_tools_output=False ) ``` ## Usage Example ```python theme={null} # Initialize the crew with an Apify actor instance research_crew = CompanyResearchCrew(actor=actor) # Start the research process result = research_crew.crew().kickoff( inputs={'domain': 'example.com'} ) ``` ## Performance Considerations The crew implementation includes several optimizations: * **Sequential Processing**: Tasks are executed in order to ensure data consistency * **Rate Limiting**: `max_rpm=100` prevents API overload * **Output Control**: `show_tools_output=False` reduces noise * **Verbose Mode**: Enabled for debugging and monitoring ## Error Handling The crew handles errors at multiple levels: 1. **Task Level**: Individual task failures 2. **Agent Level**: Agent execution errors 3. **Tool Level**: Data collection errors The crew implementation is designed to be maintainable and extensible. New tasks or agents can be added by following the existing patterns. # Architecture Overview Source: https://company-research-agent.pratikdani.com/architecture/overview Understanding the Company Research Agent architecture # Architecture Overview The Company Research Agent is built using CrewAI, a powerful framework for orchestrating multiple AI agents to work together on complex tasks. The architecture combines specialized agents, custom tools, and the Apify platform to deliver comprehensive company research. ## High-Level Architecture Coordinates multiple AI agents working together to research and analyze company data Provides web scraping and data collection capabilities through specialized actors Purpose-built tools for interacting with various data sources Uses Google's Gemini model for analysis and report generation ## Core Components ### 1. CrewAI Crew The `CompanyResearchCrew` class orchestrates three specialized agents: ```python theme={null} @CrewBase class CompanyResearchCrew: def crew(self) -> Crew: return Crew( agents=[ self.researcher(), self.data_analyst(), ], tasks=[ self.research_company(), self.analyze_data(), ], process=Process.sequential ) ``` ### 2. Specialized Agents Each agent has a specific role in the research process: * **Researcher**: Gathers raw company information * **Data Analyst**: Processes and analyzes the collected data * **Content Compiler**: Formats the findings into structured reports ### 3. Custom Tools The system includes specialized tools for different data sources: ```python theme={null} tools=[ CompanyNewsSearchTool(actor=self.actor), ProfessionalProfilesTool(actor=self.actor), LinkedInScraperTool(actor=self.actor), CrunchbaseScraperTool(actor=self.actor), PitchBookScraperTool(actor=self.actor), GoogleSearchTool(actor=self.actor) ] ``` ### 4. Task Flow The research process follows a sequential workflow: 1. Company research using domain name 2. Data analysis and insight extraction 3. Report compilation and formatting ## Integration Points ### Apify Platform * **Actors**: Uses specialized Apify actors for web scraping * **Dataset**: Stores and manages research results * **Key-Value Store**: Handles intermediate data storage ### LLM Integration ```python theme={null} self.llm = LLM( model="gemini/gemini-2.0-flash-lite", temperature=0.7, api_key=os.getenv("GOOGLE_API_KEY") ) ``` ## Data Flow 1. **Input**: Company domain name 2. **Research Phase**: Multiple tools gather data in parallel 3. **Analysis Phase**: Data is processed and analyzed 4. **Output**: Structured report in JSON format ## Error Handling The system includes robust error handling: * Tool-level error handling for each data source * Agent-level task retry mechanisms * Crew-level process management ## Performance Optimization * Concurrent data collection where possible * Rate limiting controls * Memory management for large datasets The architecture is designed to be modular and extensible. New agents, tools, or data sources can be added without major modifications to the core system. # Custom Tools Source: https://company-research-agent.pratikdani.com/architecture/tools Documentation of custom CrewAI tools for company research # Custom Tools The Company Research Agent implements several custom tools that extend CrewAI's `BaseTool` class. These tools provide specialized functionality for gathering company information from various sources. ## Tool Overview Gathers recent news articles about companies Finds company profiles on professional platforms Extracts data from LinkedIn company pages Collects funding and company data Gathers detailed company information Performs targeted web searches ## Company News Search Tool ```python theme={null} class CompanyNewsSearchTool(BaseTool): """ @class CompanyNewsSearchTool @description Searches for and retrieves recent news articles about a company @param actor - Apify Actor instance """ name: str = "Company News Search" description: str = """ Searches for and retrieves recent news articles about a company using its domain name. Returns articles with titles, URLs, descriptions, and publication dates. """ actor: Actor = Field(description="Apify Actor instance") ``` ### Usage Example ```python theme={null} news_tool = CompanyNewsSearchTool(actor=actor) news_articles = news_tool._run("example.com") ``` ## Professional Profiles Tool ```python theme={null} class ProfessionalProfilesTool(BaseTool): """ @class ProfessionalProfilesTool @description Finds company profiles on professional platforms @param actor - Apify Actor instance """ name: str = "Professional Profiles Search" description: str = """ Finds company profiles on LinkedIn, Crunchbase, and PitchBook using domain name. Returns profile URLs and descriptions for each platform. """ actor: Actor = Field(description="Apify Actor instance") ``` ### Usage Example ```python theme={null} profiles_tool = ProfessionalProfilesTool(actor=actor) profiles = profiles_tool._run("example.com") ``` ## LinkedIn Scraper Tool ```python theme={null} class LinkedInScraperTool(BaseTool): """ @class LinkedInScraperTool @description Scrapes detailed company information from LinkedIn @param actor - Apify Actor instance """ name: str = "LinkedIn Company Profile Scraper" description: str = """ Scrapes detailed company information from LinkedIn company profiles. Requires a valid LinkedIn company profile URL. """ actor: Actor = Field(description="Apify Actor instance") ``` ### Usage Example ```python theme={null} linkedin_tool = LinkedInScraperTool(actor=actor) company_data = linkedin_tool._run("https://linkedin.com/company/example") ``` ## Crunchbase Scraper Tool ```python theme={null} class CrunchbaseScraperTool(BaseTool): """ @class CrunchbaseScraperTool @description Scrapes company information from Crunchbase @param actor - Apify Actor instance """ name: str = "Crunchbase Organization Scraper" description: str = """ Scrapes detailed company information from Crunchbase organization profiles. Requires a valid Crunchbase organization URL. """ actor: Actor = Field(description="Apify Actor instance") ``` ### Usage Example ```python theme={null} crunchbase_tool = CrunchbaseScraperTool(actor=actor) funding_data = crunchbase_tool._run("https://crunchbase.com/organization/example") ``` ## PitchBook Scraper Tool ```python theme={null} class PitchBookScraperTool(BaseTool): """ @class PitchBookScraperTool @description Scrapes company information from PitchBook @param actor - Apify Actor instance """ name: str = "PitchBook Company Profile Scraper" description: str = """ Scrapes detailed company information from PitchBook company profiles. Requires a valid PitchBook company profile URL. """ actor: Actor = Field(description="Apify Actor instance") ``` ### Usage Example ```python theme={null} pitchbook_tool = PitchBookScraperTool(actor=actor) company_info = pitchbook_tool._run("https://pitchbook.com/profiles/company/example") ``` ## Google Search Tool ```python theme={null} class GoogleSearchTool(BaseTool): """ @class GoogleSearchTool @description Performs Google searches for company information @param actor - Apify Actor instance """ name: str = "Google Search" description: str = """ Searches google for a given query and returns the results """ actor: Actor = Field(description="Apify Actor instance") ``` ### Usage Example ```python theme={null} search_tool = GoogleSearchTool(actor=actor) search_results = search_tool._run("example company products") ``` ## Common Implementation Pattern All tools follow a similar implementation pattern: 1. **Synchronous Wrapper** ```python theme={null} def _run(self, input_param: str) -> Dict: """Execute synchronously by creating a new event loop""" loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: return loop.run_until_complete(self._async_run(input_param)) finally: loop.close() ``` 2. **Async Implementation** ```python theme={null} async def _async_run(self, input_param: str) -> Dict: """Async implementation of the tool""" # Tool-specific implementation ``` ## Error Handling Tools implement comprehensive error handling: ```python theme={null} try: actor_run = await self.actor.call(actor_id="actor_id", run_input=run_input) if actor_run is None: raise RuntimeError('Actor task failed to start.') except Exception as e: logging.error(f"Error in tool execution: {str(e)}") raise ``` All tools are designed to be thread-safe and can be used concurrently by multiple agents. They handle their own error cases and resource cleanup. # Getting Started Source: https://company-research-agent.pratikdani.com/getting-started Learn how to use the AI-powered Company Research Agent # Getting Started This guide will help you start using the Company Research & Analysis Agent to gather comprehensive company information using AI agents. ## Prerequisites * An [Apify account](https://console.apify.com/sign-up) * API token from your Apify account (if using programmatically) * Google API key for the Gemini model * Python 3.8 or later ## Installation ### 1. Install Required Packages ```bash theme={null} pip install apify-client crewai python-dotenv nest-asyncio ``` ### 2. Set Up Environment Variables Create a `.env` file in your project root: ```bash theme={null} APIFY_TOKEN=your_apify_token GOOGLE_API_KEY=your_google_api_key ``` ## Quick Start ### Using the Web Interface 1. Visit the [actor page](https://apify.com/pratikdani/company-research-analysis-agent) 2. Click "Try for Free" or "Use with Custom Data" 3. Enter a company domain (e.g., `apple.com`) 4. Click "Start" 5. Wait for the AI agents to complete their research ### Using Python ```python theme={null} from apify_client import ApifyClient from src.company_research_crew import CompanyResearchCrew # Initialize the Apify client client = ApifyClient('YOUR_API_TOKEN') # Initialize the research crew research_crew = CompanyResearchCrew(actor=actor) # Start the research process result = research_crew.crew().kickoff( inputs={'domain': 'apple.com'} ) # Print the results print(result) ``` ## Understanding Results The agent provides two types of output: ### 1. Comprehensive Report A detailed report containing: * Company overview * Products and services * Market presence * Key personnel * Financial metrics * Recent developments ### 2. Structured Data Raw data including: * LinkedIn profile data * PitchBook investment data * Crunchbase company data * Recent news articles * Funding analysis ## AI Agent Roles The system uses three specialized AI agents: 1. **Research Specialist** * Gathers company information * Uses multiple data sources * Validates data accuracy 2. **Data Analyst** * Processes raw data * Identifies patterns * Extracts insights 3. **Report Writer** * Structures information * Highlights key findings * Creates clear reports ## Next Steps * Learn about [configuration options](/guides/configuration) * Explore [usage examples](/examples/basic-usage) * Read the [API reference](/api-reference/overview) * Understand the [architecture](/architecture/overview) The AI agents work together to provide comprehensive research. Each agent specializes in a specific aspect of the research process, ensuring high-quality results. # Configuration Source: https://company-research-agent.pratikdani.com/guides/configuration Configure the Company Research & Analysis Agent for your needs # Configuration Learn how to configure the Company Research & Analysis Agent for optimal performance and customization. ## Actor Configuration The actor's behavior can be configured through the `actor.json` file: ```json theme={null} { "actorSpecification": 1, "name": "company-research-analysis-agent", "title": "Company Research & Analysis Agent", "version": "1.0", "minMemoryMbytes": 128, "maxMemoryMbytes": 1024 } ``` ### Memory Settings Minimum memory allocation (default: 128MB) Maximum memory allocation (default: 1024MB) ## Dataset Views The actor provides two configurable dataset views: ### Overview View Shows the domain and generated report: ```json theme={null} { "views": { "overview": { "title": "Company Report", "transformation": { "fields": ["domain", "generated_report"] } } } } ``` ### Raw Data View Shows all collected data: ```json theme={null} { "views": { "raw_data": { "title": "Raw Data", "transformation": { "fields": [ "domain", "recent_news", "linkedin_data", "pitchbook_data", "crunchbase_data", "funding_analysis" ] } } } } ``` ## Storage Configuration Data is stored in Apify's storage: * **Default Dataset**: Contains all scraped data * **Key-Value Store**: Stores intermediate results * **Request Queue**: Manages scraping requests ## Performance Optimization ### Memory Usage Adjust memory based on your needs: ```json theme={null} { "minMemoryMbytes": 256, // For basic scraping "maxMemoryMbytes": 2048 // For large companies } ``` ### Concurrent Operations The actor manages concurrent requests to different data sources: * LinkedIn scraping * Crunchbase data collection * PitchBook profile extraction * Google News searches ## Error Handling Configure error handling in the actor: ```python theme={null} # Retry configuration MAX_RETRIES = 3 RETRY_DELAY = 1000 # milliseconds # Timeout settings REQUEST_TIMEOUT = 30000 # milliseconds PAGE_LOAD_TIMEOUT = 60000 # milliseconds ``` ## Proxy Configuration The actor uses Apify's proxy services: ```python theme={null} # Proxy configuration PROXY_CONFIGURATION = { 'useApifyProxy': True, 'groups': ['RESIDENTIAL'], 'countryCode': 'US' } ``` ## Rate Limiting Configure rate limits to respect target websites: ```python theme={null} # Rate limiting configuration REQUESTS_PER_MINUTE = 30 CONCURRENT_REQUESTS = 5 ``` These settings provide a good balance between performance and reliability. Adjust them based on your specific needs and target website limitations. # Installation Source: https://company-research-agent.pratikdani.com/guides/installation How to install and set up the Company Research & Analysis Agent # Installation The Company Research & Analysis Agent can be used in two ways: 1. Through the Apify platform (no installation required) 2. Running locally using Docker ## Using Apify Platform No installation is required. Simply: 1. Visit [Apify Console](https://console.apify.com) 2. Search for "Company Research & Analysis Agent" 3. Click "Try for Free" or "Use with Custom Data" ## Running Locally ### Prerequisites * [Docker](https://www.docker.com/get-started) * [Git](https://git-scm.com/downloads) ### Steps 1. Clone the repository: ```bash theme={null} git clone https://github.com/pratik-dani/company-research.git cd company-research ``` 2. Build the Docker image: ```bash theme={null} docker build -t company-research-agent . ``` 3. Create a `.env` file with your API keys: ```bash theme={null} cp .env.example .env # Edit .env with your API keys ``` 4. Run the container: ```bash theme={null} docker run -it --env-file .env company-research-agent ``` ## Environment Variables The following environment variables are required: Your Apify API token OpenAI API key for report generation ## Verifying Installation To verify your installation: 1. Run a test query: ```bash theme={null} docker run -it --env-file .env company-research-agent --domain apify.com ``` 2. Check the output: * Results should appear in the `apify_storage` directory * No error messages should be present * The report should contain company information ## Troubleshooting Common issues and solutions: ### Docker Build Fails * Ensure Docker is running * Check internet connection * Verify Dockerfile syntax ### Missing API Keys * Copy `.env.example` to `.env` * Add required API keys * Ensure keys have correct permissions ### Memory Issues * Increase Docker memory limit * Check available system resources For production use, we recommend using the Apify platform which provides automatic scaling, monitoring, and proxy management. # Usage Guide Source: https://company-research-agent.pratikdani.com/guides/usage Learn how to effectively use the Company Research & Analysis Agent # Usage Guide This guide explains how to effectively use the Company Research & Analysis Agent for various use cases. ## Basic Usage ### 1. Single Company Research ```python theme={null} from apify_client import ApifyClient client = ApifyClient('YOUR_API_TOKEN') # Run the actor run = client.actor('pratikdani/company-research-analysis-agent').call( run_input={'domain': 'apple.com'} ) # Get results results = client.dataset(run['defaultDatasetId']).list_items().items ``` ### 2. Batch Processing ```python theme={null} domains = ['apple.com', 'microsoft.com', 'google.com'] async def process_companies(domains): results = [] for domain in domains: run = await client.actor('pratikdani/company-research-analysis-agent').call( run_input={'domain': domain} ) results.append(run) return results ``` ## Advanced Usage ### 1. Custom Data Processing ```python theme={null} def process_company_data(data): # Extract specific fields company_info = { 'name': data['linkedin_data'].get('name'), 'funding': data['funding_analysis'].get('total_raised'), 'employees': data['linkedin_data'].get('employee_count'), 'recent_news': len(data['recent_news']) } return company_info ``` ### 2. Report Generation ```python theme={null} def generate_custom_report(data): # Create custom report format report = f""" # {data['linkedin_data'].get('name')} Analysis ## Key Metrics - Funding: ${data['funding_analysis'].get('total_raised'):,} - Employees: {data['linkedin_data'].get('employee_count')} - Latest Round: {data['funding_analysis'].get('largest_round', {}).get('type')} ## Recent News {format_news(data['recent_news'])} """ return report ``` ## Best Practices ### 1. Error Handling ```python theme={null} try: run = client.actor('pratikdani/company-research-analysis-agent').call( run_input={'domain': domain} ) except Exception as e: logger.error(f"Error processing {domain}: {str(e)}") # Implement retry logic or fallback ``` ### 2. Data Validation ```python theme={null} def validate_results(data): required_fields = [ 'linkedin_data', 'funding_analysis', 'recent_news' ] return all(field in data for field in required_fields) ``` ### 3. Rate Limiting ```python theme={null} import time from ratelimit import limits, sleep_and_retry @sleep_and_retry @limits(calls=30, period=60) def rate_limited_api_call(domain): return client.actor('pratikdani/company-research-analysis-agent').call( run_input={'domain': domain} ) ``` ## Common Use Cases ### 1. Investment Research ```python theme={null} def analyze_investment_potential(data): metrics = { 'funding_history': data['funding_analysis']['funding_timeline'], 'growth_rate': calculate_growth_rate(data), 'market_presence': analyze_market_presence(data), 'risk_factors': identify_risk_factors(data) } return metrics ``` ### 2. Competitive Analysis ```python theme={null} def compare_companies(company_data_list): comparison = { 'funding': {}, 'employees': {}, 'market_presence': {} } for data in company_data_list: company = data['linkedin_data']['name'] comparison['funding'][company] = data['funding_analysis']['total_raised'] comparison['employees'][company] = data['linkedin_data']['employee_count'] return comparison ``` ### 3. Market Research ```python theme={null} def analyze_market_trends(company_data_list): trends = { 'total_funding': sum(d['funding_analysis']['total_raised'] for d in company_data_list), 'avg_company_size': calculate_average_size(company_data_list), 'common_investors': find_common_investors(company_data_list) } return trends ``` Remember to handle API rate limits and implement appropriate error handling in production environments. # Introduction Source: https://company-research-agent.pratikdani.com/introduction AI-powered company research using CrewAI and Apify # Company Research & Analysis Agent The Company Research & Analysis Agent is a powerful AI-driven tool that performs comprehensive company research by coordinating multiple specialized AI agents using CrewAI. It aggregates data from authoritative sources like LinkedIn, PitchBook, and Crunchbase to provide detailed insights for business intelligence, market research, competitive analysis, and investment decision making. ## System Architecture ```mermaid theme={null} flowchart TB A[Web/SDK] --> B subgraph crew[CrewAI System] B[Research Crew] B --> C[Research] B --> D[Analysis] B --> E[Report] C & D & E -.-> F[Gemini LLM] end C --> G[Data Tools] G --> H[(External APIs)] classDef default fill:#2D3748,stroke:#4A5568,color:#fff classDef crew fill:#2D3748,stroke:#4A5568,color:#fff classDef highlight fill:#3182CE,stroke:#2B6CB0,color:#fff classDef llm fill:#B83280,stroke:#97266D,color:#fff classDef api fill:#2F855A,stroke:#276749,color:#fff class A highlight class B,C,D,E crew class F llm class G,H api ``` ## Key Features Multiple specialized AI agents work together to research, analyze, and report company information Detailed information about company operations, products, and services from multiple sources Real-time financial data including funding history and investment trends Competitive analysis, market positioning, and industry insights ## How It Works 1. User accesses the system via web interface or Python SDK 2. The CrewAI system coordinates three specialized agents: * Research agent collects company data * Analysis agent processes findings * Report agent creates final output 3. Data tools connect to external services (LinkedIn, Crunchbase, etc.) 4. Gemini LLM powers all agent decisions and analysis ## Use Cases The agent supports various business needs: * **Due Diligence**: Research for mergers, acquisitions, and investments * **Competitive Analysis**: Gather market intelligence and competitor insights * **Lead Generation**: Identify and qualify business development prospects * **Investment Research**: Support financial analysis and decision making * **Industry Analysis**: Track market trends and industry developments * **Recruitment**: Research potential employers or acquisition targets ## Data Sources We aggregate data from multiple authoritative sources: * **LinkedIn**: Company profiles, employee count, job openings * **PitchBook**: Investment data, funding rounds, acquisitions * **Crunchbase**: Company information, financials, investors * **Google News**: Recent developments and news coverage ## AI-Powered Analysis The system leverages multiple AI components: 1. **CrewAI Framework**: Coordinates AI agents for different tasks 2. **Google's Gemini Model**: Powers analysis and report generation 3. **Custom Tools**: AI-driven data collection and processing 4. **Automated Insights**: Pattern recognition and trend analysis The agent uses AI to not just collect data but also analyze and present it in a meaningful way, making it a powerful tool for business research and decision-making. ## Getting Started Ready to start researching companies? Head over to our [Getting Started](/getting-started) guide to begin using the Company Research & Analysis Agent. # Advanced Usage Examples Source: https://company-research-agent.pratikdani.com/usage/advanced-usage Advanced examples and patterns for the Company Research & Analysis Agent # Advanced Usage Examples These examples demonstrate more complex use cases and integration patterns for the Company Research & Analysis Agent. ## Competitive Analysis Compare multiple companies in the same industry: ```python theme={null} from apify_client import ApifyClient import pandas as pd import asyncio async def analyze_competitors(domains): client = ApifyClient('YOUR_API_TOKEN') results = [] for domain in domains: run = await client.actor('pratikdani/company-research-analysis-agent').call( run_input={'domain': domain} ) data = await client.dataset(run['defaultDatasetId']).list_items() results.append(data.items[0]) # Create comparison dataframe comparison = pd.DataFrame([{ 'Company': d['linkedin_data'].get('name'), 'Employees': d['linkedin_data'].get('employee_count'), 'Total Funding': d['funding_analysis'].get('total_raised'), 'Last Round': d['funding_analysis'].get('largest_round', {}).get('amount'), 'Round Type': d['funding_analysis'].get('largest_round', {}).get('type'), 'News Mentions': len(d['recent_news']) } for d in results]) return comparison # Example usage competitors = ['slack.com', 'discord.com', 'teams.microsoft.com'] comparison = asyncio.run(analyze_competitors(competitors)) print(comparison) ``` ## Investment Analysis Analyze investment opportunities with custom metrics: ```python theme={null} def analyze_investment_potential(data): # Calculate growth metrics funding_rounds = data['funding_analysis']['funding_timeline'] employee_count = data['linkedin_data']['employee_count'] news_sentiment = analyze_news_sentiment(data['recent_news']) # Create investment score metrics = { 'growth_score': calculate_growth_score(funding_rounds), 'market_presence': assess_market_presence(employee_count), 'news_sentiment': news_sentiment, 'risk_factors': identify_risks(data) } return metrics def calculate_growth_score(funding_rounds): if not funding_rounds: return 0 # Calculate funding growth rate amounts = [round['amount'] for round in funding_rounds] times = [pd.to_datetime(round['date']) for round in funding_rounds] if len(amounts) < 2: return amounts[0] if amounts else 0 growth_rates = [] for i in range(1, len(amounts)): time_diff = (times[i] - times[i-1]).days / 365 if time_diff > 0: growth_rate = (amounts[i] - amounts[i-1]) / time_diff growth_rates.append(growth_rate) return sum(growth_rates) / len(growth_rates) if growth_rates else 0 # Example usage client = ApifyClient('YOUR_API_TOKEN') run = client.actor('pratikdani/company-research-analysis-agent').call( run_input={'domain': 'startup.com'} ) data = client.dataset(run['defaultDatasetId']).list_items().items[0] investment_analysis = analyze_investment_potential(data) ``` ## Market Research Dashboard Create a dashboard for market analysis: ```python theme={null} import streamlit as st import plotly.express as px from apify_client import ApifyClient def create_market_dashboard(domains): client = ApifyClient('YOUR_API_TOKEN') market_data = [] for domain in domains: run = client.actor('pratikdani/company-research-analysis-agent').call( run_input={'domain': domain} ) data = client.dataset(run['defaultDatasetId']).list_items().items[0] market_data.append(data) # Create dashboard st.title('Market Research Dashboard') # Funding Overview funding_data = pd.DataFrame([{ 'Company': d['linkedin_data'].get('name'), 'Total Funding': d['funding_analysis'].get('total_raised') } for d in market_data]) st.header('Funding Overview') fig = px.bar(funding_data, x='Company', y='Total Funding') st.plotly_chart(fig) # Employee Growth employee_data = pd.DataFrame([{ 'Company': d['linkedin_data'].get('name'), 'Employees': d['linkedin_data'].get('employee_count') } for d in market_data]) st.header('Company Size Comparison') fig = px.pie(employee_data, values='Employees', names='Company') st.plotly_chart(fig) # News Analysis st.header('Recent News Activity') for data in market_data: company = data['linkedin_data'].get('name') news_count = len(data['recent_news']) st.subheader(f"{company}: {news_count} recent news items") for news in data['recent_news'][:3]: st.write(f"- {news['title']}") # Run the dashboard domains = ['company1.com', 'company2.com', 'company3.com'] create_market_dashboard(domains) ``` ## Custom Report Generation Generate specialized reports: ```python theme={null} def generate_custom_report(data, report_type='executive'): if report_type == 'executive': return generate_executive_summary(data) elif report_type == 'financial': return generate_financial_report(data) elif report_type == 'technical': return generate_technical_analysis(data) else: raise ValueError(f"Unknown report type: {report_type}") def generate_executive_summary(data): company = data['linkedin_data'].get('name') return f""" # Executive Summary: {company} ## Company Overview - Industry: {data['linkedin_data'].get('industry')} - Founded: {data['linkedin_data'].get('founded')} - Employees: {data['linkedin_data'].get('employee_count')} ## Key Metrics - Total Funding: ${data['funding_analysis'].get('total_raised'):,} - Latest Round: {data['funding_analysis'].get('largest_round', {}).get('type')} - Key Markets: {', '.join(data['linkedin_data'].get('specialties', []))} ## Recent Developments {format_recent_news(data['recent_news'][:3])} ## Strategic Recommendations {generate_recommendations(data)} """ # Example usage client = ApifyClient('YOUR_API_TOKEN') run = client.actor('pratikdani/company-research-analysis-agent').call( run_input={'domain': 'target.com'} ) data = client.dataset(run['defaultDatasetId']).list_items().items[0] # Generate different report types executive_report = generate_custom_report(data, 'executive') financial_report = generate_custom_report(data, 'financial') technical_report = generate_custom_report(data, 'technical') ``` These examples assume you have the required Python packages installed (pandas, streamlit, plotly). They can be customized further based on specific needs. # Basic Usage Examples Source: https://company-research-agent.pratikdani.com/usage/basic-usage Simple examples of using the Company Research & Analysis Agent # Basic Usage Examples Here are some basic examples of how to use the Company Research & Analysis Agent in different scenarios. ## Web Interface Example The simplest way to use the actor is through the Apify web interface. 1. Visit the actor's page 2. Enter a domain name 3. Click "Start" ## Command Line Example Using curl to start an actor run: ```bash theme={null} curl --request POST \ --url https://api.apify.com/v2/acts/pratikdani~company-research-analysis-agent/runs?token=YOUR_API_TOKEN \ --header 'content-type: application/json' \ --data '{ "domain": "apify.com" }' ``` ## Python Example Simple script to research a company: ```python theme={null} from apify_client import ApifyClient # Initialize the client client = ApifyClient('YOUR_API_TOKEN') # Run the actor run_input = { 'domain': 'apify.com' } # Start the run run = client.actor('pratikdani/company-research-analysis-agent').call(run_input=run_input) # Wait for the run to finish and fetch results results = client.dataset(run['defaultDatasetId']).list_items().items # Print the generated report print(results[0]['generated_report']) ``` ## Node.js Example Using the actor with Node.js: ```javascript theme={null} const { ApifyClient } = require('apify-client'); // Initialize the client const client = new ApifyClient({ token: 'YOUR_API_TOKEN', }); async function researchCompany() { // Start the actor and wait for it to finish const run = await client.actor('pratikdani/company-research-analysis-agent').call({ domain: 'apify.com' }); // Fetch and print results const { items } = await client.dataset(run.defaultDatasetId).listItems(); console.log(items[0].generated_report); } researchCompany(); ``` ## Batch Processing Example Research multiple companies at once: ```python theme={null} from apify_client import ApifyClient import asyncio async def research_companies(domains): client = ApifyClient('YOUR_API_TOKEN') results = [] for domain in domains: try: # Start the actor run run = await client.actor('pratikdani/company-research-analysis-agent').call( run_input={'domain': domain} ) # Get the results items = await client.dataset(run['defaultDatasetId']).list_items() results.append(items.items[0]) except Exception as e: print(f"Error processing {domain}: {str(e)}") return results # List of companies to research domains = [ 'apify.com', 'microsoft.com', 'apple.com' ] # Run the batch process results = asyncio.run(research_companies(domains)) # Process results for result in results: print(f"Company: {result['domain']}") print(f"Report Length: {len(result['generated_report'])} characters") print("---") ``` ## Save Results Example Save the research results to a file: ```python theme={null} import json from apify_client import ApifyClient def save_company_research(domain, output_file): # Initialize the client client = ApifyClient('YOUR_API_TOKEN') # Run the actor run = client.actor('pratikdani/company-research-analysis-agent').call( run_input={'domain': domain} ) # Get results results = client.dataset(run['defaultDatasetId']).list_items().items[0] # Save to file with open(output_file, 'w') as f: json.dump(results, f, indent=2) print(f"Results saved to {output_file}") # Use the function save_company_research('apify.com', 'apify_research.json') ``` Remember to replace 'YOUR\_API\_TOKEN' with your actual Apify API token in all examples.