!function(){function t(t){document.documentElement.setAttribute("data-theme",t)}var e=function(){var t=null;try{t=new URLSearchParams(window.location.search).get("docusaurus-theme")}catch(t){}return t}()||function(){var t=null;try{t=localStorage.getItem("theme")}catch(t){}return t}();t(null!==e?e:"light")}(),document.documentElement.setAttribute("data-announcement-bar-initially-dismissed",function(){try{return"true"===localStorage.getItem("docusaurus.announcement.dismiss")}catch(t){}return!1}())

[Skip to main content](#__docusaurus_skipToContent_fallback)

LangChain v0.2 is coming soon! Preview the new docs [here](/v0.2/docs/introduction/).

[

![🦜️🔗 Langchain](/v0.1/img/brand/wordmark.png)![🦜️🔗 Langchain](/v0.1/img/brand/wordmark-dark.png)

](/v0.1/)[Docs](/v0.1/docs/get_started/introduction/)[Use cases](/v0.1/docs/use_cases/)[Integrations](/v0.1/docs/integrations/platforms/)[API Reference](https://api.js.langchain.com)

[More](#)

*   [People](/v0.1/docs/people/)
*   [Community](/v0.1/docs/community/)
*   [Tutorials](/v0.1/docs/additional_resources/tutorials/)
*   [Contributing](/v0.1/docs/contributing/)

[v0.1](#)

*   [v0.2](https://js.langchain.com/v0.2/docs/introduction)
*   [v0.1](/v0.1/docs/get_started/introduction/)

[🦜🔗](#)

*   [LangSmith](https://smith.langchain.com)
*   [LangSmith Docs](https://docs.smith.langchain.com)
*   [LangChain Hub](https://smith.langchain.com/hub)
*   [LangServe](https://github.com/langchain-ai/langserve)
*   [Python Docs](https://python.langchain.com/)

[Chat](https://chatjs.langchain.com)[](https://github.com/langchain-ai/langchainjs)

Search

*   [Use cases](/v0.1/docs/use_cases/)
    
    *   [SQL](/v0.1/docs/use_cases/sql/)
        
    *   [Chatbots](/v0.1/docs/use_cases/chatbots/)
        
    *   [Extraction](/v0.1/docs/use_cases/extraction/)
        
    *   [Query Analysis](/v0.1/docs/use_cases/query_analysis/)
        
    *   [Q&A with RAG](/v0.1/docs/use_cases/question_answering/)
        
    *   [Tool use](/v0.1/docs/use_cases/tool_use/)
        
    *   [Interacting with APIs](/v0.1/docs/use_cases/api/)
    *   [Tabular Question Answering](/v0.1/docs/use_cases/tabular/)
    *   [Graphs](/v0.1/docs/use_cases/graph/)
        
        *   [Quickstart](/v0.1/docs/use_cases/graph/quickstart/)
        *   [Constructing knowledge graphs](/v0.1/docs/use_cases/graph/construction/)
        *   [Mapping values to database](/v0.1/docs/use_cases/graph/mapping/)
        *   [Semantic layer over graph database](/v0.1/docs/use_cases/graph/semantic/)
        *   [Prompting strategies](/v0.1/docs/use_cases/graph/prompting/)
    *   [Summarization](/v0.1/docs/use_cases/summarization/)
    *   [Agent Simulations](/v0.1/docs/use_cases/agent_simulations/)
        
    *   [Autonomous Agents](/v0.1/docs/use_cases/autonomous_agents/)
        
    *   [Code Understanding](/v0.1/docs/use_cases/code_understanding/)
    *   [Audio/Video Structured Extraction](/v0.1/docs/use_cases/media/)

*   [](/v0.1/)
*   [Use cases](/v0.1/docs/use_cases/)
*   [Graphs](/v0.1/docs/use_cases/graph/)
*   Constructing knowledge graphs

On this page

Constructing knowledge graphs
=============================

In this guide we’ll go over the basic ways of constructing a knowledge graph based on unstructured text. The constructured graph can then be used as knowledge base in a RAG application. At a high-level, the steps of constructing a knowledge are from text are:

1.  Extracting structured information from text: Model is used to extract structured graph information from text.
2.  Storing into graph database: Storing the extracted structured graph information into a graph database enables downstream RAG applications

Setup[​](#setup "Direct link to Setup")
---------------------------------------

#### Install dependencies[​](#install-dependencies "Direct link to Install dependencies")

tip

See [this section for general instructions on installing integration packages](/v0.1/docs/get_started/installation/#installing-integration-packages).

*   npm
*   yarn
*   pnpm

    npm i langchain @langchain/community @langchain/openai neo4j-driver zod

    yarn add langchain @langchain/community @langchain/openai neo4j-driver zod

    pnpm add langchain @langchain/community @langchain/openai neo4j-driver zod

#### Set environment variables[​](#set-environment-variables "Direct link to Set environment variables")

We’ll use OpenAI in this example:

    OPENAI_API_KEY=your-api-key# Optional, use LangSmith for best-in-class observabilityLANGSMITH_API_KEY=your-api-keyLANGCHAIN_TRACING_V2=true

Next, we need to define Neo4j credentials. Follow [these installation steps](https://neo4j.com/docs/operations-manual/current/installation/) to set up a Neo4j database.

    NEO4J_URI="bolt://localhost:7687"NEO4J_USERNAME="neo4j"NEO4J_PASSWORD="password"

The below example will create a connection with a Neo4j database.

    import "neo4j-driver";import { Neo4jGraph } from "@langchain/community/graphs/neo4j_graph";const url = Deno.env.get("NEO4J_URI");const username = Deno.env.get("NEO4J_USER");const password = Deno.env.get("NEO4J_PASSWORD");const graph = await Neo4jGraph.initialize({ url, username, password });

LLM Graph Transformer[​](#llm-graph-transformer "Direct link to LLM Graph Transformer")
---------------------------------------------------------------------------------------

Extracting graph data from text enables the transformation of unstructured information into structured formats, facilitating deeper insights and more efficient navigation through complex relationships and patterns. The LLMGraphTransformer converts text documents into structured graph documents by leveraging a LLM to parse and categorize entities and their relationships. The selection of the LLM model significantly influences the output by determining the accuracy and nuance of the extracted graph data.

    import { ChatOpenAI } from "@langchain/openai";import { LLMGraphTransformer } from "@langchain/community/experimental/graph_transformers/llm";const model = new ChatOpenAI({  temperature: 0,  model: "gpt-4-turbo-preview",});const llmGraphTransformer = new LLMGraphTransformer({  llm: model,});

Now we can pass in example text and examine the results.

    import { Document } from "@langchain/core/documents";let text = `Marie Curie, was a Polish and naturalised-French physicist and chemist who conducted pioneering research on radioactivity.She was the first woman to win a Nobel Prize, the first person to win a Nobel Prize twice, and the only person to win a Nobel Prize in two scientific fields.Her husband, Pierre Curie, was a co-winner of her first Nobel Prize, making them the first-ever married couple to win the Nobel Prize and launching the Curie family legacy of five Nobel Prizes.She was, in 1906, the first woman to become a professor at the University of Paris.`;const result = await llmGraphTransformer.convertToGraphDocuments([  new Document({ pageContent: text }),]);console.log(`Nodes: ${result[0].nodes.length}`);console.log(`Relationships:${result[0].relationships.length}`);

    Nodes: 8Relationships:7

Note that the graph construction process is non-deterministic since we are using LLM. Therefore, you might get slightly different results on each execution. Examine the following image to better grasp the structure of the generated knowledge graph.

![graph_construction1.png](/v0.1/assets/images/graph_construction1-2b4d31978d58696d5a6a52ad92ae088f.png)

Additionally, you have the flexibility to define specific types of nodes and relationships for extraction according to your requirements.

    const llmGraphTransformerFiltered = new LLMGraphTransformer({  llm: model,  allowedNodes: ["PERSON", "COUNTRY", "ORGANIZATION"],  allowedRelationships: ["NATIONALITY", "LOCATED_IN", "WORKED_AT", "SPOUSE"],  strictMode: false,});const result_filtered =  await llmGraphTransformerFiltered.convertToGraphDocuments([    new Document({ pageContent: text }),  ]);console.log(`Nodes: ${result_filtered[0].nodes.length}`);console.log(`Relationships:${result_filtered[0].relationships.length}`);

    Nodes: 6Relationships:4

For a better understanding of the generated graph, we can again visualize it.

![graph_construction1.png](/v0.1/assets/images/graph_construction2-8b43506ae0fb3a006eaa4ba83fea8af5.png)

Storing to graph database[​](#storing-to-graph-database "Direct link to Storing to graph database")
---------------------------------------------------------------------------------------------------

The generated graph documents can be stored to a graph database using the `addGraphDocuments` method.

    await graph.addGraphDocuments(result_filtered);

* * *

#### Help us out by providing feedback on this documentation page:

[

Previous

Quickstart

](/v0.1/docs/use_cases/graph/quickstart/)[

Next

Mapping values to database

](/v0.1/docs/use_cases/graph/mapping/)

*   [Setup](#setup)
*   [LLM Graph Transformer](#llm-graph-transformer)
*   [Storing to graph database](#storing-to-graph-database)

Community

*   [Discord](https://discord.gg/cU2adEyC7w)
*   [Twitter](https://twitter.com/LangChainAI)

GitHub

*   [Python](https://github.com/langchain-ai/langchain)
*   [JS/TS](https://github.com/langchain-ai/langchainjs)

More

*   [Homepage](https://langchain.com)
*   [Blog](https://blog.langchain.dev)

Copyright © 2024 LangChain, Inc.