AVA Framework

repository·ai·Indexed 23 days ago

https://github.com/antvis/ava

An AI-native visual analytics framework (version 4.0.0-alpha.1) that enables data loading, processing, analysis, and visualization using natural language. It features a modular architecture that automatically switches between in-memory JavaScript processing for small datasets (< 10KB) and database-backed storage (SQLite for Node.js or IndexedDB for browsers) for larger datasets. The framework provides capabilities for AI-driven analysis suggestions, natural language querying, and automated chart generation via GPT-Vis syntax.

Tokens
8.5K
Snippets
16
Records
53
Agent score
80%

What's inside @antv/ava

  1. Browser vs Node.js compatibility

    ai

    AVA is designed to run in both environments with automatic detection and adaptation:

    FeatureBrowserNode.js
    Large DatasetsUses IndexedDBUses SQLite
    CSV LoadingAccepts content stringsAccepts file paths
    Small DatasetsIn-memory processingIn-memory processing

    Note for Browsers: For extremely large datasets, it is recommended to use the server-side (Node.js) version to avoid browser memory pressure.

  2. How AVA's modular architecture works

    ai

    AVA follows a modular pipeline that adapts to data size and environment:

    1. Data Loading: Data is ingested via CSV, JSON, URL, or Text.
    2. Metadata Extraction: The system performs type inference and statistics.
    3. Size-based Routing:
      • Small datasets (< 10KB): Uses JavaScript helpers for in-memory analysis.
      • Large datasets (≥ 10KB): Switches to a database-backed approach.
    4. Environment-specific Storage:
      • Browser: Uses IndexedDB for large datasets.
      • Node.js: Uses SQLite for large datasets.
    5. Analysis & Summary: Generates code/SQL, executes it, and uses an LLM to summarize the result into natural language.
    6. Visualization (Optional): Detects intent and generates chart syntax and HTML.
  3. Enable React-specific ESLint rules

    ai

    To add React and React DOM specific linting, install eslint-plugin-react-x and eslint-plugin-react-dom. In your eslint.config.js, extend the configuration using reactX.configs['recommended-typescript'] and reactDom.configs.recommended. Ensure parserOptions.project is correctly configured to point to your TypeScript configuration files.

    // eslint.config.js
    import reactX from 'eslint-plugin-react-x'
    import reactDom from 'eslint-plugin-react-dom'
    
    export default defineConfig([
      globalIgnores(['dist']),
      {
        files: ['**/*.{ts,tsx}'],
        extends: [
          // Other configs...
          // Enable lint rules for React
          reactX.configs['recommended-typescript'],
          // Enable lint rules for React DOM
          reactDom.configs.recommended,
        ],
        languageOptions: {
          parserOptions: {
            project: ['./tsconfig.node.json', './tsconfig.app.json'],
            tsconfigRootDir: import.meta.dirname,
          },
          // other options...
        },
      },
    ])
  4. Enable type-aware ESLint rules for TypeScript

    ai

    For production applications, it is recommended to enable type-aware lint rules in your ESLint configuration. This involves replacing tseslint.configs.recommended with one of the following type-checked configurations:

    • tseslint.configs.recommendedTypeChecked
    • tseslint.configs.strictTypeChecked (stricter)
    • tseslint.configs.stylisticTypeChecked (for stylistic rules)

    You must also configure languageOptions.parserOptions to include your project (e.g., ./tsconfig.app.json) and tsconfigRootDir to enable type-aware linting.

    export default defineConfig([
      globalIgnores(['dist']),
      {
        files: ['**/*.{ts,tsx}'],
        extends: [
          // Other configs...
    
          // Remove tseslint.configs.recommended and replace with this
          tseslint.configs.recommendedTypeChecked,
          // Alternatively, use this for stricter rules
          tseslint.configs.strictTypeChecked,
          // Optionally, add this for stylistic rules
          tseslint.configs.stylisticTypeChecked,
    
          // Other configs...
        ],
        languageOptions: {
          parserOptions: {
            project: ['./tsconfig.node.json', './tsconfig.app.json'],
            tsconfigRootDir: import.meta.dirname,
          },
          // other options...
        },
      },
    ])
  5. How AVA manages data storage

    ai

    AVA uses different storage strategies depending on the environment and the size of the dataset to optimize performance and memory usage:

    1. Small Datasets: Kept directly in memory as a JavaScript array.
    2. Large Datasets (Node.js): If the data size exceeds sqlThreshold, it is loaded into a SQLiteDataStore. Analysis is performed using generated SQL queries.
    3. Large Datasets (Browser): If the data size exceeds sqlThreshold and IndexedDB is available, it is loaded into an IndexedDBDataStore. Analysis is performed by generating and executing JavaScript code against the data.
    4. Browser Fallback: If IndexedDB is unavailable, large datasets remain in memory, which may cause performance issues.
  6. Understand DatasetInfo and FieldMetadata structures

    ai

    AVA uses DatasetInfo to describe the structure and scale of the data being analyzed. This includes row and column counts, total size in bytes, and an array of FieldMetadata. Each field describes its name, type (number, string, date, or boolean), and statistical properties like uniqueCount, nullCount, and samples.

    export interface DatasetInfo {
      rowCount: number;
      columnCount: number;
      fields: FieldMetadata[];
      sizeInBytes: number;
    }
    
    export interface FieldMetadata {
      name: string;
      type: 'number' | 'string' | 'date' | 'boolean';
      samples?: any[];
      uniqueCount?: number;
      nullCount?: number;
    }
  7. GPT-Vis Syntax Rules and Specification

    ai

    GPT-Vis uses a custom, indentation-based syntax for defining visualizations. When writing or generating syntax, follow these rules:

    Core Rules

    • Start Line: The first line must be vis [type] (e.g., vis line, vis column).
    • Key-Value Pairs: Use a space between the key and the value. Do not use colons (e.g., title My Chart, NOT title: My Chart).
    • Ordering: The data property should generally appear before other attributes like title or axisXTitle.
    • Strings: Use single or double quotes for values containing spaces (e.g., title "Sales Trend"). Quotes can be omitted if there are no spaces.
    • Indentation: Use indentation to define object properties and array elements.

    Data Structures

    Object Arrays (Standard for most charts): Use - for each item in the array, with sub-fields indented.

    data
      - time 2020
        value 100
      - time 2021
        value 120

    Pure Value Arrays:

    data
      - 10
      - 20

    Nested Objects:

    style
      backgroundColor #f0f2f5
      palette
        - #5B8FF9
        - #61DDAA

    Recursive Trees:

    data
      name Root
      children
        - name ChildA
          children
            - name Grandchild

    Graph Data (Nodes/Edges):

    data
      nodes
        - name NodeA
        - name NodeB
      edges
        - source NodeA
          target NodeB
  8. Initialize the AVA instance

    ai

    To use AVA, create a new instance using the AVA class. You must provide an llm configuration object containing the model, apiKey, and baseURL.

    You can optionally specify a sqlThreshold (in bytes) to control when the system switches from in-memory processing to SQLite. The default threshold is 10KB.

    import { AVA } from '@antv/ava';
    
    const ava = new AVA({
      llm: {
        model: 'ling-1t',
        apiKey: 'YOUR_API_KEY',
        baseURL: 'LLM_BASE_URL',
      },
      sqlThreshold: 1024 * 1024 * 2, // Threshold for switching to SQLite
    });
  9. Clean up resources with dispose()

    ai

    To prevent memory leaks and release resources such as SQLite, IndexedDB, or in-memory data, call dispose() when the AVA instance is no longer needed.

    ava.dispose();
  10. Load data into AVA

    ai

    AVA supports loading data from various formats and sources. The behavior of loadCSV varies depending on the environment:

    • Node.js: Accepts a file path.
    • Browser: Accepts a CSV content string.

    Available loading methods:

    • loadCSV(filePathOrContent): Load CSV data.
    • loadObject(data): Load a JSON object.
    • loadURL(url, transform?): Load data from a URL with an optional transformation function.
    • loadText(text): Load unstructured text (processed via LLM).
  11. Analyze data and generate suggestions

    ai

    AVA provides AI-driven analysis capabilities:

    1. suggest(count?): Generates a list of recommended analysis queries based on your data. Returns an array of objects containing query, score, and reason.
    2. analysis(query): Executes a natural language query. It returns an object containing:
      • text: A natural language summary of the result.
      • data: The structured analysis result.
      • code: (Optional) JavaScript code used for in-memory analysis (small datasets).
      • sql: (Optional) SQL query used for SQLite analysis (large datasets).
    // Get top 5 suggested queries
    const queries = await ava.suggest(5);
    
    // Run analysis using a natural language query
    const result = await ava.analysis('What is the average revenue by region?');
    console.log(result.text);
    
    // Or use a suggested query
    const suggestedResult = await ava.analysis(queries[0].query);