Hyper-Extract

repository·main·Indexed 25 days ago

https://github.com/yifanfeng97/hyper-extract

An LLM-powered knowledge extraction and evolution framework (version 0.3.0) that transforms unstructured text into structured, strongly-typed Knowledge Abstracts, including Graphs, Hypergraphs, and Spatio-Temporal Graphs. It features a CLI and Python API for automating extraction, semantic search capabilities via FAISS vector indexing, and support for multiple LLM providers including OpenAI, Bailian, and local vLLM instances. Includes tools for exporting knowledge to Obsidian vaults and an MCP server for agent integration.

Tokens
63.2K
Snippets
202
Records
410
Agent score
85%

What's inside hyperextract

  1. Overview of Hyper-Extract Skills

    main

    The hyperextract-skills package provides specialized skills for designing knowledge templates.

    SkillPurpose
    RootEntry point for template design
    brainstormRequirements exploration and type discussion
    record-designerDesign model/list/set structures
    graph-designerDesign graph/hypergraph/etc structures
    yaml-validatorValidate YAML configurations
    multilingualConvert to multi-language support
    template-optimizerOptimize templates and fix common issues
  2. Understand Auto-Types in Hyper-Extract

    main
    Auto-Types are the core data structures used to extract, organize, and store structured knowledge from text. They are Pydantic-based, providing type-safe schemas, LLM-powered extraction, built-in operations (search, merge, visualize), and serialization capabilities. All Auto-Types inherit from BaseAutoType, which provides common methods like parse, feed_text, build_index, search, chat, dump, and load.
  3. Choose a workflow for Hyper-Extract

    main

    Hyper-Extract offers two primary ways to interact with the system depending on your needs:

    • CLI (Command Line Interface): Best for processing documents without writing code, batch processing files, or users who prefer terminal-based workflows.
    • Python SDK: Best for building applications, integrating Hyper-Extract into existing codebases, or when you require full programmatic control.
  4. Understand the Hyper-Extract Three-Layer Architecture

    main

    Hyper-Extract operates using a three-layer architecture that separates user interfaces from data structures and extraction algorithms:

    1. Layer 3: Interface: Provides access via the CLI, Python SDK, and Template API.
    2. Layer 2: Methods: Contains the extraction algorithms, categorized into RAG-Based and Typical methods.
    3. Layer 1: Data: The foundation using Auto-Types to define data structures, resulting in Structured Knowledge.
    LayerPurposeComponents
    Auto-TypesDefine data structures8 type classes
    MethodsExtraction algorithmsRAG + Typical methods
    TemplatesDomain-specific configs80+ preset templates
  5. Understand Auto-Types knowledge structures

    main

    Auto-Types are intelligent, Pydantic-based data structures used to organize extracted knowledge. They act as containers that shape the output of document extraction.

    Key characteristics include:

    • Type-Safe: Uses Pydantic for consistent data validation.
    • Self-Contained: Includes built-in operations for searching, visualizing, and saving.
    • Serializable: Can be saved to disk and reloaded.
    • Composable: Supports merging, updating, and incremental extension.
  6. Understand the Hyper-Extract Data Flow

    main

    Hyper-Extract processes raw text through a four-stage pipeline to produce structured, type-safe data:

    1. Input Processing: Raw text is split into chunks if it exceeds the chunk_size. The default chunk size is 2048 characters with a 256-character overlap, using separators like paragraphs, sentences, and words.
    2. Extraction: Each chunk is processed in parallel. An LLM is called with a formatted prompt to extract structured data based on a schema.
    3. Merging: Results from all chunks are merged by deduplicating entities, combining relations, and resolving conflicts.
    4. Result: The final merged data is encapsulated into an AutoTypeInstance for operations like search, chat, and visualization.
  7. Quickstart: Extract and Visualize Knowledge

    main

    Use the Template class to create an extraction pipeline, parse text, and visualize the resulting knowledge graph.

    from hyperextract import Template
    
    # Create template
    ka = Template.create("general/biography_graph", language="en")
    
    # Extract knowledge
    with open("document.md") as f:
        result = ka.parse(f.read())
    
    # Access data
    print(f"Nodes: {len(result.nodes)}")
    print(f"Edges: {len(result.edges)}")
    
    # Build index for search/chat capabilities
    result.build_index()
    
    # Visualize
    result.show()
    from hyperextract import Template
    
    # Create template
    ka = Template.create("general/biography_graph", language="en")
    
    # Extract knowledge
    with open("document.md") as f:
        result = ka.parse(f.read())
    
    # Access data
    print(f"Nodes: {len(result.nodes)}")
    print(f"Edges: {len(result.edges)}")
    
    # Build index for search/chat capabilities
    result.build_index()
    
    # Visualize
    result.show()
  8. Overview of Hyper-Extract Workflow

    main

    Hyper-Extract is a tool for designing YAML configuration templates used in structured knowledge extraction. The workflow follows a sequential process to move from initial requirements to a validated, multilingual YAML configuration:

    1. brainstorm: Discuss requirements, determine the data type, and create a design draft.
    2. designer: Generate the actual YAML based on the design draft. This step uses either record-designer (for models, lists, or sets) or graph-designer (for graphs, hypergraphs, temporal, or spatial structures).
    3. validator (optional): Validate the syntax and structure of the generated YAML.
    4. multilingual (optional): Add support for multiple languages to the configuration.
  9. Design a Temporal Graph

    main

    To create a temporal graph, add a time-related field to your relations and configure the identifiers block to recognize the time field. This allows the system to distinguish between multiple relations between the same entities occurring at different times.

    1. Add Time Field to Relations

    Include a field (e.g., event_date) in the relations.fields list. It is recommended to set required: false and a default empty string to handle missing data.

    2. Configure Time Identifier

    In the identifiers block, set time_field to your chosen field name. Update relation_id to include the time field in its template (e.g., '{source}|{relation_type}|{target}|{event_date}') to ensure unique relation IDs across different timestamps.

    3. Apply Time Handling Rules

    Follow these guidelines for data consistency:

    • Observation time: Use {observation_time}.
    • Absolute dates: Keep as-is (e.g., 2024-01-01).
    • Relative time: Convert to absolute dates.
    • Fuzzy time: Leave empty; do not guess.
    relations:
      fields:
        - name: source
          type: str
        - name: target
          type: str
        - name: relation_type
          type: str
        - name: event_date
          type: str
          description: 'When the relation occurred'
          required: false
          default: ''
    
    identifiers:
      entity_id: name
      relation_id: '{source}|{relation_type}|{target}|{event_date}'
      relation_members:
        source: source
        target: target
      time_field: event_date
    
    guideline:
      rules_for_time:
        - 'Observation time: {observation_time}'
        - 'Absolute dates: Keep as-is (e.g., 2024-01-01)'
        - 'Relative time: Convert to absolute'
        - 'Fuzzy time: Leave empty, do not guess'
  10. Configure auto-type specific template sections

    main

    The type field in your template determines which specialized sections are available in output, guideline, and identifiers.

    Lists/Sets (type: list)

    Use items instead of entities or relations under output.

    output:
      items:
        description:
          zh: "列表项"
          en: "List items"
        fields:
          - name: value
            type: str

    Models (type: model)

    Use fields directly under output for flat extraction.

    output:
      fields:
        - name: company_name
          type: str
        - name: revenue
          type: float

    Temporal Graphs (type: temporal_graph)

    Includes specialized time extraction rules and identifier settings.

    • Guideline: Use rules_for_time.
    • Identifiers: Use time_field to specify which field contains the temporal data.
    guideline:
      rules_for_time:
        zh: ["规则1"]
        en: ["Rule 1"]
    
    identifiers:
      time_field: time

    Spatial Graphs (type: spatial_graph)

    Includes specialized location extraction rules and field requirements.

    • Output: Include location or coordinates fields in entities.
    • Guideline: Use rules_for_location.
    output:
      entities:
        fields:
          - name: location
            type: str
          - name: coordinates
            type: str
    
    guideline:
      rules_for_location:
        zh: ["规则1"]
        en: ["Rule 1"]