kg-gen

stair-lab更新放缓

从任意文本自动抽取实体与关系并生成知识图谱的 Python 工具,附带基准测试,方便用 LLM 构建和评测图谱抽取流程。

[NeurIPS '25] Knowledge Graph Generation from Any Text

MINE-evaluations-expanded发布于 2025-11-23 20:19 UTC1,290star201fork同步于 2026-11-07 07:31 UTC

怎么上手

由 README 提炼,执行前请确认
pip install kg-gen
硬件要求按 README 说明

README 未说明显存或 GPU 要求;可调用云端 API,也可通过 Ollama 使用本地模型,具体硬件取决于所选模型

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

用 LLM 从任意纯文本抽取知识图谱,支持长文本分块与实体聚类,可接入多种模型

从任意文本自动抽取实体与关系并生成知识图谱的 Python 工具,附带基准测试,方便用 LLM 构建和评测图谱抽取流程。

核心能力

  • 通过 LiteLLM 路由 OpenAI、Ollama、Anthropic、Gemini、Deepseek 等模型
  • 用 chunk_size 分块处理长文本,避免单次输入过长
  • 用 cluster 合并同义实体与关系,如 ML 与 machine learning
  • 支持消息数组输入,保留角色信息并抽取说话人与概念间关系
  • 用 aggregate 合并多个图谱,并提供 visualize 可视化

容易踩的坑

需自行准备模型 API Key 或本地 Ollama 服务,否则无法调用;model 字符串须按 LiteLLM 的 {provider}/{model_name} 格式填写;从仓库安装需用 pip install -e '.[dev]' 并额外装开发依赖

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

4 个版本MINE-evaluations-expanded
  1. MINE-evaluations-expandedMINE Eval expanded 最新正式版2025-11-23 · 2025-11-23 20:19 UTC

    uses kggen with gpt-5-nano, and gpt-oss-20b with multiple levels of reasoning + openie and graphrag options

  2. MINE-deduplication-scikitlearn-vs-faissMINE Eval (deduplication) Scikit Learn vs Faiss2025-10-28 · 2025-10-28 04:44 UTC
    查看更新说明
    ============================================================
    SUMMARY STATISTICS
    ============================================================
    faiss                                    scikit-learn
    Mean:                                    36.93 70.47
    Median:                                  40.00 73.33
    Std Dev:                                 17.72 20.36
    Min:                                      0.00 13.33
    Max:                                     73.33 100.00
    ============================================================
    
    scikit-learn vs faiss - Average difference: 33.53%
    Better cases in scikit-learn: 90
    Better cases in faiss: 6
    Equal cases: 4
    ============================================================
    

    #69 #62

  3. WikiQA-evaluationsWikiQA KGGen Dataset2025-10-06 · 2025-10-06 06:19 UTC
    查看更新说明
  4. MINE-evaluationsMINE dataset and evaluations2025-09-26 · 2025-09-26 04:58 UTC
    查看更新说明

    This files were organized into a single dataset that allows to rerun evaluations, keeping this just as a backup and history.

    Should use https://huggingface.co/datasets/josancamon/kg-gen-MINE-evaluation-dataset.

    answers.json = generated_queries instead, this was a bad name

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    kg-gen: Knowledge Graph Generation from Any Text

    📄 Paper | 🐍 Package | 🤖 MCP | 🔬 Experiments | 👩🏻‍💻 Dataset | 🐦 X Updates

    Welcome! kg-gen helps you extract knowledge graphs from any plain text using AI. It can process both small and large text inputs, and it can also handle messages in a conversation format.

    Why generate knowledge graphs? kg-gen is great if you want to:

    • Create a graph to assist with RAG (Retrieval-Augmented Generation)
    • Create graph synthetic data for model training and testing
    • Structure any text into a graph
    • Analyze the relationships between concepts in your source text

    We support API-based and local model providers via LiteLLM, including OpenAI, Ollama, Anthropic, Gemini, Deepseek, and others. We also use DSPy for structured output generation.

    Powered by a model of your choice

    Pass in a model string to use a model of your choice. Model calls are routed via LiteLLM, and usually LiteLLM goes by the format of {model_provider}/{model_name}. See specifically how to format it at https://docs.litellm.ai/docs/providers.

    Examples of models you can pass in:

    • openai/gpt-5
    • gemini/gemini-2.5-flash
    • ollama_chat/deepseek-r1:14b

    You may specify a custom API base url with base_url (example here).

    Quick start

    Install the module:

    pip install kg-gen
    

    Then import and use kg-gen. You can provide your text input in one of two formats:

    1. A single string
    2. A list of Message objects (each with a role and content)

    Below are some example snippets:

    from kg_gen import KGGen
    
    # Initialize KGGen with optional configuration
    kg = KGGen(
      model="openai/gpt-4o",  # Default model
      temperature=0.0,        # Default temperature
      api_key="YOUR_API_KEY"  # Optional if set in environment or using a local model
    )
    
    # EXAMPLE 1: Single string with context
    text_input = "Linda is Josh's mother. Ben is Josh's brother. Andrew is Josh's father."
    graph_1 = kg.generate(
      input_data=text_input,
      context="Family relationships"
    )
    # Output: 
    # entities={'Linda', 'Ben', 'Andrew', 'Josh'} 
    # edges={'is brother of', 'is father of', 'is mother of'} 
    # relations={('Ben', 'is brother of', 'Josh'), 
    #           ('Andrew', 'is father of', 'Josh'), 
    #           ('Linda', 'is mother of', 'Josh')}
    

    Visualizing KGs

    KGGen.visualize(graph, output_path, open_in_browser=True)
    

    viz-tool

    More Examples - chunking, clustering, passing in a messages array

    # EXAMPLE 2: Large text with chunking and clustering
    with open('large_text.txt', 'r') as f:
      large_text = f.read()
      
    # Example input text:
    # """
    # Neural networks are a type of machine learning model. Deep learning is a subset of machine learning
    # that uses multiple layers of neural networks. Supervised learning requires training data to learn
    # patterns. Machine learning is a type of AI technology that enables computers to learn from data.
    # AI, also known as artificial intelligence, is related to the broader field of artificial intelligence.
    # Neural nets (NN) are commonly used in ML applications. Machine learning (ML) has revolutionized
    # many fields of study.
    # ...
    # """
    
    graph_2 = kg.generate(
      input_data=large_text,
      chunk_size=5000,  # Process text in chunks of 5000 chars
      cluster=True      # Cluster similar entities and relations
    )
    # Output:
    # entities={'neural networks', 'deep learning', 'machine learning', 'AI', 'artificial intelligence', 
    #          'supervised learning', 'unsupervised learning', 'training data', ...} 
    # edges={'is type of', 'requires', 'is subset of', 'uses', 'is related to', ...} 
    # relations={('neural networks', 'is type of', 'machine learning'),
    #           ('deep learning', 'is subset of', 'machine learning'),
    #           ('supervised learning', 'requires', 'training data'),
    #           ('machine learning', 'is type of', 'AI'),
    #           ('AI', 'is related to', 'artificial intelligence'), ...}
    # entity_clusters={
    #   'artificial intelligence': {'AI', 'artificial intelligence'},
    #   'machine learning': {'machine learning', 'ML'},
    #   'neural networks': {'neural networks', 'neural nets', 'NN'}
    #   ...
    # }
    # edge_clusters={
    #   'is type of': {'is type of', 'is a type of', 'is a kind of'},
    #   'is related to': {'is related to', 'is connected to', 'is associated with'
    #  ...}
    # }
    
    # EXAMPLE 3: Messages array
    messages = [
      {"role": "user", "content": "What is the capital of France?"}, 
      {"role": "assistant", "content": "The capital of France is Paris."}
    ]
    graph_3 = kg.generate(input_data=messages)
    # Output: 
    # entities={'Paris', 'France'} 
    # edges={'has capital'} 
    # relations={('France', 'has capital', 'Paris')}
    
    # EXAMPLE 4: Combining multiple graphs
    text1 = "Linda is Joe's mother. Ben is Joe's brother."
    
    # Input text 2: also goes by Joe."
    text2 = "Andrew is Joseph's father. Judy is Andrew's sister. Joseph also goes by Joe."
    
    graph4_a = kg.generate(input_data=text1)
    graph4_b = kg.generate(input_data=text2)
    
    # Combine the graphs
    combined_graph = kg.aggregate([graph4_a, graph4_b])
    
    # Optionally cluster the combined graph
    clustered_graph = kg.cluster(
      combined_graph,
      context="Family relationships"
    )
    # Output:
    # entities={'Linda', 'Ben', 'Andrew', 'Joe', 'Joseph', 'Judy'} 
    # edges={'is mother of', 'is father of', 'is brother of', 'is sister of'} 
    # relations={('Linda', 'is mother of', 'Joe'),
    #           ('Ben', 'is brother of', 'Joe'),
    #           ('Andrew', 'is father of', 'Joe'),
    #           ('Judy', 'is sister of', 'Andrew')}
    # entity_clusters={
    #   'Joe': {'Joe', 'Joseph'},
    #   ...
    # }
    # edge_clusters={ ... }
    

    Install from this repository:

    Clone this repository and install dependencies using pip install -e '.[dev]'.

    You may verify that it works by running python tests/test_basic.py from the root directory. This will also generate a nice visualization in tests/test_basic.html.

    MCP Server for AI Agents

    For AI agents that need persistent memory capabilities:

    # Install and start MCP server
    pip install kg-gen
    kggen mcp
    
    # Use with Claude Desktop, custom MCP clients, or other AI applications
    

    See the MCP Server documentation for detailed setup and integration instructions.

    Features

    Chunking Large Texts

    For large texts, you can specify a chunk_size parameter to process the text in smaller chunks:

    graph = kg.generate(
      input_data=large_text,
      chunk_size=5000  # Process in chunks of 5000 characters
    )
    

    Clustering Similar Entities and Relations

    You can cluster similar entities and relations either during generation or afterwards:

    # During generation
    graph = kg.generate(
      input_data=text,
      cluster=True,
      context="Optional context to guide clustering"
    )
    
    # Or after generation
    clustered_graph = kg.cluster(
      graph,
      context="Optional context to guide clustering"
    )
    

    Aggregating Multiple Graphs

    You can combine multiple graphs using the aggregate method:

    graph1 = kg.generate(input_data=text1)
    graph2 = kg.generate(input_data=text2)
    combined_graph = kg.aggregate([graph1, graph2])
    

    Message Array Processing

    When processing message arrays, kg-gen:

    1. Preserves the role information from each message
    2. Maintains message order and boundaries
    3. Can extract entities and relationships:
      • Between concepts mentioned in messages
      • Between speakers (roles) and concepts
      • Across multiple messages in a conversation

    For example, given this conversation:

    messages = [
      {"role": "user", "content": "What is the capital of France?"},
      {"role": "assistant", "content": "The capital of France is Paris."}
    ]
    

    The generated graph might include entities like:

    • "user"
    • "assistant"
    • "France"
    • "Paris"

    And relations like:

    • (user, "asks about", "France")
    • (assistant, "states", "Paris")
    • (Paris, "is capital of", "France")

    Citing

    If you find KGGen useful, please consider citing:

    @misc{mo2025kggenextractingknowledgegraphs,
          title={KGGen: Extracting Knowledge Graphs from Plain Text with Language Models}, 
          author={Belinda Mo and Kyssen Yu and Joshua Kazdan and Joan Cabezas and Proud Mpala and Lisa Yu and Chris Cundy and Charilaos Kanatsoulis and Sanmi Koyejo},
          year={2025},
          eprint={2502.09956},
          archivePrefix={arXiv},
          primaryClass={cs.CL},
          url={https://arxiv.org/abs/2502.09956}, 
    }
    

    License

    The MIT License.