KGConstructor<T>

Models & Types · AiDotNet.RetrievalAugmentedGeneration.Graph.Construction

Constructs a knowledge graph from unstructured text using heuristic entity and relation extraction.

For Beginners

This class reads text and automatically builds a knowledge graph.

Given text: “Albert Einstein was born in Ulm, Germany. He worked at Princeton University.” It extracts:

  • Entities: Albert Einstein (PERSON), Ulm (LOCATION), Germany (LOCATION), Princeton University (ORGANIZATION)
  • Relations: Einstein BORN_IN Ulm, Einstein LOCATED_IN Germany, Einstein WORKED_AT Princeton University

The heuristic approach uses patterns like:

  • Capitalized words = likely entity names
  • Words like “born in”, “works at”, “located in” = relation indicators
  • Entities appearing near each other = likely related

How It Works

The construction pipeline operates in four stages:

  1. Chunk Text: Split text into overlapping chunks for processing
  2. Extract Entities: Identify named entities using regex patterns and capitalization heuristics
  3. Extract Relations: Detect relations via co-occurrence and proximity-based patterns
  4. Entity Resolution: Merge similar entity names to reduce duplicates

When an IGenerator LLM text generator is injected, construction instead prompts the model to extract entities and relations as structured JSON (Microsoft GraphRAG parity), parsing the result with Newtonsoft.Json. If no generator is injected, or if the LLM returns malformed JSON, construction transparently falls back to the regex/heuristic path documented above (an explicit offline fallback — never silent pretending).

Constructors

Constructor Summary
KGConstructor() Initializes a new instance of the KGConstructor class using only the regex/heuristic (offline, no-LLM) extraction path.
KGConstructor(IGenerator<T> generator) Initializes a new instance of the KGConstructor class with an optional LLM text generator.

Methods

Method Summary
KnowledgeGraph<T> ConstructFromText(string text, KnowledgeGraph<T> graph, KGConstructionOptions options) Constructs a knowledge graph from the given text.
List<ExtractedEntity> ExtractEntities(string text, double confidenceThreshold) Extracts entities from a text chunk using heuristic patterns.
List<ExtractedRelation> ExtractRelations(string text, List<ExtractedEntity> entities, int maxEntitiesPerSentence) Extracts relations between entities based on proximity and pattern matching.