OneKE Knowledge Extraction System

repository·main·Indexed 41 days ago

https://github.com/zjunlp/oneke

A dockerized, schema-guided knowledge extraction system using a multi-agent approach to perform NER, Relation Extraction, Event Extraction, and Triple Extraction from sources like web content and PDFs. It supports various LLMs including ChatGPT, DeepSeek, LLaMA, Qwen, and ChatGLM, and provides both a CLI and a Streamlit-based Web UI for configuring tasks and visualizing knowledge graphs via Neo4j.

Tokens
14.8K
Snippets
49
Records
60
Agent score
51%

What's inside OneKE

  1. Perform Relation Extraction (RE)

    main

    Extract semantic relations between entities (e.g., Country-Capital) from unstructured text. You can specify relation type constraints or omit them to extract all relations.

    Steps:

    1. Configure ./examples/config/RE.yaml with your text and constraint (relation types).
    2. Run the extraction script:
    config_file=./examples/config/RE.yaml
    python src/run.py --config $config_file
  2. Perform Named Entity Recognition (NER)

    main

    Perform Named Entity Recognition to locate and classify entities (e.g., Person, Organization, Location) in unstructured text. You can either specify entity type constraints or omit them to extract all entities.

    Steps:

    1. Configure ./examples/config/NER.yaml with your desired text and constraint (entity types).
    2. Run the extraction script:
    config_file=./examples/config/NER.yaml
    python src/run.py --config $config_file
  3. Perform Open Domain IE (Base Task)

    main

    Use the Base task type for any user-defined extraction tasks (e.g., Web News Extraction). Unlike traditional IE tasks, Base tasks require an explicit Instruction and do not use constraint values.

    Steps:

    1. Configure ./examples/config/NewsExtraction.yaml with an Instruction (e.g., Extract key information from the given text) and an output schema.
    2. Run the extraction script:
    config_file=./examples/config/NewsExtraction.yaml
    python src/run.py --config $config_file
  4. Install OneKE using Docker Image

    main

    Docker provides a reliable and stable environment for OneKE. This method is recommended for consistent deployment.

    Prerequisites

    • Docker installation
    • NVIDIA Container Toolkit
    • GPU support (recommended CUDA version: 12.4)

    Steps

    1. Clone the repository and enter the directory:
      git clone https://github.com/zjunlp/OneKE.git
      cd OneKE
    2. Pull the official image:
      docker pull zjunlp/oneke:v4
    3. Launch the container:
      docker run --gpus all -v ./OneKE:/app/OneKE -it oneke:v4 /bin/bash

    Mapping Local Models If you are using locally deployed models, you must map the local model path to a container path:

    docker run --gpus all \
      -v ./OneKE:/app/OneKE \
      -v your_local_model_path:/app/model/your_model_name \
      -it oneke:v4 /bin/bash

    Note: Once inside the container, the working directory is /app/OneKE. Changes made to the local ./OneKE folder will sync to the container automatically.

    docker pull zjunlp/oneke:v4
    docker run --gpus all -v ./OneKE:/app/OneKE -it oneke:v4 /bin/bash
  5. Perform Triple Extraction and Build Knowledge Graphs

    main

    Identify subject-predicate-object triples to construct Knowledge Graphs (KG).

    Constraint Formats:

    • Entity types only: ["Person", "Place"]
    • Entity and Relation types: [["Person", "Place"], ["LivesIn", "BornIn"]]
    • Subject, Relation, and Object types: [["Person"], ["LivesIn"], ["Place"]]

    Building a Knowledge Graph: To automatically construct a KG (e.g., in Neo4j), add the construct field to your YAML configuration.

    Warning: If you do NOT want to build a KG, you must remove or comment out the construct field to avoid database connection errors.

    Steps:

    1. Configure ./examples/config/Triple2KG.yaml with the construct block.
    2. Run the extraction script:
    config_file=./examples/config/Triple2KG.yaml
    python src/run.py --config $config_file
    construct: # (Optional) If you want to construct a Knowledge Graph, you need to set the construct field, or you must delete this field.
      database: Neo4j # your database type.
      url: neo4j://localhost:7687 # your database URL
      username: your_username # your database username.
      password: "your_password" # your database password.
  6. Install OneKE via Manual Environment Configuration

    main

    You can set up OneKE using a Conda virtual environment. This method is lightweight and flexible.

    Prerequisites

    • Anaconda installation
    • GPU support (recommended CUDA version: 12.4)

    Steps

    1. Clone the repository:
      git clone https://github.com/zjunlp/OneKE.git
      cd OneKE
    2. Create and activate a Python 3.9 environment:
      conda create -n oneke python=3.9
      conda activate oneke
    3. Install dependencies:
      pip install -r requirements.txt
      Note: If you encounter network issues, consider setting up a domestic mirror for pip.
    git clone https://github.com/zjunlp/OneKE.git
    cd OneKE
    conda create -n oneke python=3.9
    conda activate oneke
    pip install -r requirements.txt
  7. Customize Extraction Methods via Agent Configuration

    main

    OneKE allows you to customize the combination of Schema, Extraction, and Reflection agents.

    1. Modify src/config.yaml to define your custom agent behaviors:
    customized:
        schema_agent: get_deduced_schema
        extraction_agent: extract_information_direct
        reflection_agent: reflect_with_case
    1. Set the mode to customized in your task configuration file (e.g., examples/customized.yaml):
    mode: customized
    # src/config.yaml
    customized:
        schema_agent:  get_deduced_schema
        extraction_agent: extract_information_direct
        reflection_agent: reflect_with_case
  8. Navigate the OneKE Web UI

    main

    The OneKE Web UI provides a graphical interface for configuring and running information extraction tasks. The interface is organized into several functional sections:

    Initial Page

    • 🎲 Quick Start with an Example 🎲: Loads a simple, predefined example for immediate testing.
    • Submit: Executes the configured extraction task.
    • Clear: Resets the interface to its initial state.

    Model Configuration

    Configure the LLM powering the extraction:

    • 🪄 Enter your Model: Input a model name (e.g., gpt-4o-mini, o3-mini, deepseek-chat, deepseek-reasoner) or a local file path for local models.
    • 🔑 Enter your API-Key: The API key for the selected model (not required for local models).
    • 🔗 Enter your Base-URL: Custom API endpoint. Leave empty to use the default URL.

    Task Configuration

    • 🎯 Select your Task: Choose between Traditional IE (NER, RE, EE, and Triple) or Open Domain IE (Web News Extraction, Book Knowledge Extraction, etc.). Selecting Triple allows for Knowledge Graph construction via Neo4j.
    • 🧭 Select your Mode: Choose the extraction strategy.
      • direct mode: Recommended for long text.
      • standard mode: Recommended for short text requiring high accuracy.
      • customize: Allows for custom agent strategies.
      • Not Required: Use if no agents are needed.

    Text Input

    • 📂 Use File: Toggle to switch between manual text entry and file uploads.
    • 📖 Upload a File: Supports formats like *.pdf* and *.html* (must enable 📂 Use File first).
    • 📖 Text: A text area for entering raw text in any language.

    Set Instruction

    • 🕹️ Instruction: Define what to extract (e.g., Please help me extract all the person names). Note: Base-type tasks allow free definitions, while RE, NER, EE, and Triple use predefined instructions.
    • ❗Constraint: Optional type and property constraints for extraction objects.
    • 💰 Update Case: Check to update the Case Repository.
    • 🪙 Truth: Provide ground truth data (e.g., {"relation_list": [{"head": "Guinea", "tail": "Conakry", "relation": "country capital"}]}) to help the LLM.

    Get Result

    After clicking Submit, the UI displays:

    • 🤔 Generated Schema: The automatically generated extraction schema in Python class format.
    • 😉 Final Answer: The extraction results in structured JSON format.
    • 📝 KG Visualization: A visual representation of the knowledge graph (available for Triple tasks using Neo4j).
  9. Perform Event Extraction (EE)

    main

    Extract event types, triggers, and arguments (e.g., for a data breach event, extracting the victim and compromised data).

    Steps:

    1. Configure ./examples/config/EE.yaml. Each event type requires a mapping of event arguments.
    2. Run the extraction script:
    config_file=./examples/config/EE.yaml
    python src/run.py --config $config_file
  10. Start the OneKE Web UI

    main

    OneKE provides a visual interface built with Streamlit for configuring tasks and viewing results.

    Prerequisites

    • Ensure gradio 4.44.0 is installed in your environment.

    Steps

    1. Navigate to the frontend directory and run the start script:
      cd frontend/
      chmod u+x start.sh
      bash ./start.sh
    2. Open your web browser and navigate to: http://0.0.0.0:8501
    cd frontend/
    chmod u+x start.sh
    bash ./start.sh
  11. Run Extraction via CLI

    main

    You can perform knowledge extraction using the Command Line Interface by providing a YAML configuration file.

    1. Prepare Configuration Create or modify a YAML file (examples are available in examples/config). The configuration is divided into two main sections:

    • model: Defines the category (e.g., ChatGPT, DeepSeek, LLaMA, Qwen, ChatGLM, MiniCPM, OneKE), model_name_or_path, api_key, and base_url.
    • extraction: Defines the task (e.g., Base, NER, RE, EE), instruction, use_file, file_path, output_schema, mode (quick, detailed, customized), and update_case.

    2. Execute Extraction Run the following command from the OneKE directory:

    config_file=your_yaml_file_path
    python src/run.py --config $config_file

    3. Deploy Local Models via vLLM To use local models with vLLM acceleration, first deploy the model, then run the extraction:

    # Ensure vllm_serve is set to TRUE in your config file
    config_file=your_yaml_file_path
    python src/models/vllm_serve.py --config $config_file
    python src/run.py --config $config_file
  12. How similarity scoring works in CaseRepository

    main

    The CaseRepository.get_similarity_scores method calculates relevance using a hybrid approach:

    1. Embedding Similarity: Uses a SentenceTransformer model to compare the query's embedding against the embedded corpus.
    2. String Similarity: Uses rapidfuzz to perform fuzzy string matching on the str_index field.
    3. Normalization: Both scores are normalized to a 0-1 range to ensure they are comparable.
    4. Combination: The final score is a weighted sum: 0.5 * normalized_embedding_score + 0.5 * normalized_string_score.

    This method returns four values: scores, indices, original_scores, and original_indices (the latter two being the unnormalized versions).