GPT Crawler

repository·main·Indexed 12 days ago

https://github.com/builderio/gpt-crawler

A tool for crawling websites to generate structured JSON knowledge files for creating custom OpenAI GPTs or Assistants. Version 1.5.1 supports local installation, Docker containerization, a CLI with interactive and flag modes, and an Express JS API server with Swagger documentation. It features configurable URL matching, CSS/XPath selectors, sitemap support, and token/file size limits to ensure output compatibility with LLM context windows.

Tokens
4.3K
Snippets
15
Records
18
Agent score
98%

What's inside GPT Crawler

  1. Configure the crawler

    main

    Before running the crawler, you must configure the target site by editing config.ts. You need to specify the starting url, a match pattern for subsequent links, and a CSS selector to extract the relevant text content.

    Example configuration for crawling documentation:

    export const defaultConfig: Config = {
      url: "https://www.builder.io/c/docs/developers",
      match: "https://www.builder.io/c/docs/**",
      selector: `.docs-builder-container`,
      maxPagesToCrawl: 50,
      outputFileName: "output.json",
    };
  2. Run GPT Crawler using Docker

    main

    To run the crawler in a containerized environment:

    1. Navigate to the containerapp directory.
    2. Modify the config.ts within that directory to set your desired crawl parameters.
    3. The resulting output.json will be generated in the data folder.
  3. Run GPT Crawler as an API server

    main

    You can run the crawler as an Express JS API server.

    1. Install dependencies: npm install
    2. Start the server: npm run start:server. The server runs on port 3000 by default.
    3. Configure environment: Copy .env.example to .env to override variables like the port.
    4. Use the endpoint: Send a POST request to /crawl with a JSON body containing your Config object.
    5. API Documentation: Swagger docs are available at the /api-docs endpoint.
    npm run start:server
  4. Use crawled data to create a custom GPT or Assistant

    main

    Once the crawl is complete, a file named output.json is generated at the project root. You can upload this file to OpenAI to build custom AI tools.

    Create a custom GPT (UI-based)

    Best for sharing knowledge via the ChatGPT interface.

    1. Go to ChatGPT and select "My GPTs" -> "Create a GPT".
    2. Go to the "Configure" tab.
    3. Under "Knowledge", select "Upload a file" and upload your output.json.
    4. Tip: If the file is too large, use maxFileSize or maxTokens in your config.ts to reduce size before re-crawling.

    Create a custom Assistant (API-based)

    Best for integrating knowledge into your own applications via the OpenAI API.

    1. Go to the OpenAI Assistants dashboard.
    2. Click "+ Create".
    3. Select "upload" and upload your output.json file.
  5. Run the GPT Crawler using Docker

    main

    You can run the GPT Crawler as a containerized application. This method uses a Docker image where all dependencies are pre-configured in the Dockerfile.

    Prerequisites

    • Docker must be installed on your system.

    Execution Steps

    1. Navigate to the container application directory:
      cd gpt-crawler/containerapp
    2. Execute the provided shell script to build and run the container:
      . ./run.sh
    cd gpt-crawler/containerapp
    . ./run.sh
  6. Install and run GPT Crawler locally

    main

    To run the crawler on your local machine, ensure you have Node.js >= 16 installed. Follow these steps:

    1. Clone the repository
      git clone https://github.com/builderio/gpt-crawler
    2. Install dependencies
      npm i
    3. Run the crawler
      npm start
    git clone https://github.com/builderio/gpt-crawler
    npm i
    npm start
  7. Use the GPT Crawler CLI

    main

    The GPT Crawler CLI allows you to crawl a website based on specific URL patterns and CSS selectors to generate data for LLMs.

    You can run the crawler in two ways:

    1. Interactive Mode: Run the command without arguments. The CLI will prompt you for the required configuration (URL, match pattern, selector, etc.) using inquirer.
    2. Flag Mode: Provide configuration directly via command-line flags to bypass interactive prompts.

    Once the crawling process is complete, the CLI automatically writes the results to the specified output file.

    # Example using flags
    # -u: starting URL
    # -m: URL pattern to match
    # -s: CSS selector for content
    # -p: max pages to crawl
    # -o: output filename
    
    gpt-crawler --url https://example.com --match /.*\/blog\/.* --selector article --maxPagesToCrawl 10 --outputFileName my_data.json
  8. Configure the API server environment

    main

    The API server's network settings can be controlled using the following environment variables:

    • API_PORT: The port on which the server will listen (defaults to 3000).
    • API_HOST: The hostname the server will bind to (defaults to localhost).
  9. Configure the GPT Crawler via the Config object

    main

    The crawler is configured using a Config object that defines the crawl scope, extraction rules, and output constraints. You can provide a starting URL (or a sitemap), define patterns for matching or excluding links, and specify a CSS selector to extract specific text content from pages.

    Key Configuration Options

    • url: The starting URL for the crawl. If a sitemap URL is provided, the crawler will follow all links within that sitemap.
    • match: A string or array of strings representing patterns to match against links for subsequent crawling.
    • exclude: A string or array of strings representing patterns to exclude from crawling.
    • selector: A CSS selector used to grab the inner text from the page.
    • maxPagesToCrawl: The maximum number of pages to visit (default is 50).
    • outputFileName: The name of the file where the crawled data will be saved.
    • cookie: An optional single cookie object or an array of cookie objects (each with name and value) to be set during the crawl (e.g., for handling cookie consent).
    • onVisitPage: An optional async function called for every page found. It receives an object containing the Playwright page and a pushData function to manually add data to the output.
    • resourceExclusions: An optional array of file extensions to exclude from crawling.
    • maxFileSize: The maximum file size in megabytes to include in the output.
    • maxTokens: The maximum number of tokens to include in the output.
    • waitForSelectorTimeout: An optional timeout (in milliseconds) for waiting for a selector to appear.
    const config: Config = {
      url: 'https://www.builder.io/c/docs/developers',
      match: 'https://www.builder.io/c/docs/**',
      exclude: 'https://www.builder.io/c/docs/exclude-me/**',
      selector: '.docs-builder-container',
      maxPagesToCrawl: 50,
      outputFileName: 'output.json',
      cookie: [
        { name: 'consent', value: 'true' }
      ],
      onVisitPage: async ({ page, pushData }) => {
        // Custom logic per page
        await pushData({ custom: 'data' });
      }
    };
  10. Reference the Config type options

    main

    The Config object controls the crawling behavior and output constraints.

    KeyTypeDescription
    urlstringURL to start the crawl. If a sitemap is provided, it will be used instead.
    matchstringPattern to match against for links on a page to subsequently crawl.
    selectorstringCSS selector used to grab the inner text from the page.
    maxPagesToCrawlnumberLimit on the total number of pages to crawl.
    outputFileNamestringThe name of the resulting JSON file.
    resourceExclusionsstring[](Optional) Array of file extensions to exclude (e.g., ['png', 'jpg']).
    maxFileSizenumber(Optional) Maximum file size in megabytes to include in the output.
    maxTokensnumber(Optional) Maximum number of tokens to include in the output.
    type Config = {
      url: string;
      match: string;
      selector: string;
      maxPagesToCrawl: number;
      outputFileName: string;
      resourceExclusions?: string[];
      maxFileSize?: number;
      maxTokens?: number;
    };
  11. Run the crawler and write data using the default configuration

    main

    The application entrypoint provides a way to execute the full crawling and writing lifecycle using the defaultConfig. This involves two sequential steps:

    1. crawl(config): Scrapes the target website based on the provided configuration.
    2. write(config): Persists the crawled data to the specified output format (e.g., JSON files).

    Note that these functions are intended to be called with a configuration object that follows the project's schema.

    import { defaultConfig } from "../config.js";
    import { crawl, write } from "./core.js";
    
    await crawl(defaultConfig);
    await write(defaultConfig);
  12. Run a crawl via the POST /crawl API endpoint

    main

    The API server exposes a /crawl endpoint that accepts a crawler configuration object in the request body. When called, the server validates the configuration, executes the crawling process using GPTCrawlerCore, writes the results to a file, and returns the resulting JSON content in the response.

    Request Body: A JSON object matching the Config schema. Response: A JSON object containing the crawled data. Error Handling: Returns a 500 status code with a JSON error message if validation fails or the crawling process encounters an error.

    curl -X POST http://localhost:3000/crawl \
      -H "Content-Type: application/json" \
      -d '{
        "url": "https://example.com",
        "selector": "main",
        "maxDepth": 2
      }'