Firesearch Documentation

repository·main·Indexed 19 days ago

https://github.com/firecrawl/firesearch

An AI-powered deep research tool that automates complex web research by decomposing queries, searching via Firecrawl, validating findings, and synthesizing cited answers. It features a multi-step process flow including query breakdown, answer validation via confidence scores, and auto-retry strategies. The tool utilizes the LangGraphSearchEngine to manage research phases from understanding and planning to synthesis, and integrates with the Firecrawl /search API for efficient content extraction.

Tokens
5K
Snippets
14
Records
21
Agent score
66%

What's inside Firesearch

  1. Understand Firesearch search strategies

    main

    When initial search results are insufficient to meet the MIN_ANSWER_CONFIDENCE threshold, Firesearch automatically employs several strategies to find missing information:

    • Broaden Keywords: Removes specific terms to get wider results.
    • Narrow Focus: Adds specific terms to target missing aspects.
    • Synonyms: Uses alternative terms and phrases.
    • Rephrase: Completely reformulates the query.
    • Decompose: Breaks complex queries into sub-questions.
    • Academic: Adds scholarly terms for research-oriented results.
    • Practical: Focuses on tutorials and how-to guides.
  2. How Firesearch works: Process Flow

    main

    Firesearch follows a multi-step research process to ensure high-quality, cited answers:

    1. Break Down: Complex user queries are split into focused sub-questions.
    2. Search: Multiple searches are executed via the Firecrawl API for comprehensive coverage.
    3. Extract: Markdown content is extracted from the discovered web sources.
    4. Validate: The system checks if the extracted sources actually answer the sub-questions (requiring a confidence score of 0.7+).
    5. Retry: If answers are missing, the system attempts alternative search terms (up to 2 attempts).
    6. Synthesize: GPT-4o combines all validated findings into a final, cited response.

    Key Features

    • Smart Search: Decomposes complex queries.
    • Answer Validation: Verifies source relevance via confidence scores.
    • Auto-Retry: Automatically tries alternative search terms for unanswered questions.
    • Full Citations: Every fact in the response is linked to its source.
    • Context Memory: Follow-up questions maintain the conversation context.
  3. Setup Firesearch via Quick Start

    main

    To run Firesearch locally, follow these steps:

    1. Clone the repository.
    2. Configure Environment Variables: Create a .env.local file in the root directory and add your API keys:
      FIRECRAWL_API_KEY=your_firecrawl_key
      OPENAI_API_KEY=your_openai_key
    3. Install Dependencies: Run npm install or yarn install.
    4. Start Development Server: Run npm run dev or yarn dev.

    Required API Keys

    ServicePurposeGet Key
    FirecrawlWeb scraping and content extractionfirecrawl.dev/app/api-keys
    OpenAISearch planning and summarizationplatform.openai.com/api-keys
    npm install
    npm run dev
  4. How follow-up questions are generated

    main

    After an answer is provided, the engine generates exactly 3 relevant follow-up questions to encourage deeper exploration.

    Follow-up questions are designed to:

    • Explore different aspects of the topic.
    • Dig deeper into technical terms or details.
    • Be natural, conversational, and actionable.
    • Stay under 80 characters.
    • Consider the full conversation context to ensure they build upon the current topic.
  5. Understand the SearchPhase lifecycle

    main

    The search process moves through a specific sequence of phases. Understanding these helps in managing UI states or debugging where a search might be stalling:

    1. understanding: Analyzing the user's intent.
    2. planning: Breaking the query into sub-queries and search strategies.
    3. searching: Executing web searches via Firecrawl.
    4. scraping: Deep-diving into specific URLs to extract content.
    5. analyzing: Evaluating gathered information against sub-queries to check for completeness.
    6. synthesizing: Generating the final comprehensive answer and follow-up questions.
    7. complete: Finalizing the process.
    8. error: A terminal state if the process fails after retries.
    type SearchPhase = 
      | 'understanding'
      | 'planning' 
      | 'searching'
      | 'analyzing'
      | 'synthesizing'
      | 'complete'
      | 'error';
  6. How the search engine handles sub-queries and confidence

    main

    The search engine breaks down complex user queries into multiple factual sub-queries. Each sub-query consists of a question and a searchQuery. After search results are retrieved, the engine updates these sub-queries by matching them against results.

    Answering a sub-query is determined by a confidence threshold defined in SEARCH_CONFIG.MIN_ANSWER_CONFIDENCE. If a result's confidence meets this threshold, the sub-query is marked as answered: true, the answer is populated, and sources are aggregated.

  7. Configure Firesearch search behavior

    main

    You can customize the research behavior by modifying the SEARCH_CONFIG object in lib/config.ts.

    Configuration Options

    CategoryKeyDescription
    Search SettingsMAX_SEARCH_QUERIESMaximum number of search queries to generate
    MAX_SOURCES_PER_SEARCHMaximum sources to return per search query
    MAX_SOURCES_TO_SCRAPEMaximum sources to scrape for additional content
    Content ProcessingMIN_CONTENT_LENGTHMinimum content length to consider valid
    SUMMARY_CHAR_LIMITCharacter limit for source summaries
    Retry LogicMAX_RETRIESRetry attempts for failed operations
    MAX_SEARCH_ATTEMPTSMaximum attempts to find answers via search
    MIN_ANSWER_CONFIDENCEMinimum confidence (0-1) that a question was answered
    TimeoutsSCRAPE_TIMEOUTTimeout for scraping operations (ms)
    export const SEARCH_CONFIG = {
      // Search Settings
      MAX_SEARCH_QUERIES: 12,
      MAX_SOURCES_PER_SEARCH: 4,
      MAX_SOURCES_TO_SCRAPE: 3,
      
      // Content Processing
      MIN_CONTENT_LENGTH: 100,
      SUMMARY_CHAR_LIMIT: 100,
      
      // Retry Logic
      MAX_RETRIES: 2,
      MAX_SEARCH_ATTEMPTS: 2,
      MIN_ANSWER_CONFIDENCE: 0.7,
      
      // Timeouts
      SCRAPE_TIMEOUT: 15000,
    } as const;
  8. How streaming answers and citations are generated

    main

    The engine supports streaming answers to provide a better user experience. It uses a streamingLlm to generate a response that includes:

    • Citations: Uses markdown-style citations like [1], [2] to link findings to specific sources.
    • Context Awareness: If a conversation history is provided, the engine incorporates previous queries and responses to maintain continuity.
    • Streaming: The onChunk callback is used to emit text fragments as they are generated by the LLM.
  9. How alternative search queries are generated for unanswered questions

    main

    When a sub-query remains unanswered or fails to meet the MIN_ANSWER_CONFIDENCE threshold, the engine can generate alternative search queries to broaden the search.

    Strategies used for generating alternatives include:

    1. Using broader or more general terms.
    2. Trying different phrasings or synonyms.
    3. Removing specific qualifiers (like years or versions) that might be too restrictive.
    4. Searching for related concepts.
    5. Searching for the base product or company name if a specific version search fails.

    If a query contains a specific version pattern (e.g., v1.2, 2024.05) and fails multiple times (specifically after 2 attempts), the engine prioritizes stripping the version to find the base product.

  10. How content is summarized for search relevance

    main

    To keep the context window manageable and focused, the engine summarizes content retrieved from search results. The summarization process is constrained by:

    • Relevance: It only extracts findings specifically relevant to the original search query.
    • Length: Summaries are kept under the limit defined by SEARCH_CONFIG.SUMMARY_CHAR_LIMIT.
    • Format: It returns a single sentence containing specific details like numbers or dates.
  11. Configure LangGraphSearchEngine checkpointing

    main

    To enable persistence and the ability to resume searches using a checkpointId, you must pass enableCheckpointing: true in the constructor options. This initializes a MemorySaver internally. When calling .search(), providing a checkpointId will allow the engine to use a specific thread_id for state management.

    // Enable checkpointing during initialization
    const engine = new LangGraphSearchEngine(firecrawl, { enableCheckpointing: true });
    
    // Use a checkpointId to resume or track a specific thread
    await engine.search("my query", onEvent, undefined, "my-unique-session-id");
  12. Integrate Firecrawl /search API for web research

    main

    Firesearch uses the Firecrawl /search endpoint to find relevant URLs and extract markdown content in a single call. This is achieved by passing scrapeOptions in the request body.

    API Usage

    • Endpoint: POST /search
    • Purpose: Finds relevant URLs AND extracts markdown content.
    • Key Feature: The scrapeOptions parameter enables content extraction during the search process.
    • Response: Returns URLs with titles, snippets, and full markdown content.

    Example Request

    POST /search
    {
      "query": "iPhone 16 specs pricing",
      "limit": 8,
      "scrapeOptions": {
        "formats": ["markdown"]
      }
    }
    {
      "query": "iPhone 16 specs pricing",
      "limit": 8,
      "scrapeOptions": {
        "formats": ["markdown"]
      }
    }