!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/)
*   Semantic layer over graph database

On this page

Semantic layer over graph database
==================================

You can use database queries to retrieve information from a graph database like Neo4j. One option is to use LLMs to generate Cypher statements. While that option provides excellent flexibility, the solution could be brittle and not consistently generating precise Cypher statements. Instead of generating Cypher statements, we can implement Cypher templates as tools in a semantic layer that an LLM agent can interact with.

![graph_semantic.png](/v0.1/assets/images/graph_semantic-365248d76b7862193c33f44eaa6ecaeb.png)

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 and will populate it with example data about movies and their actors.

    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 });// Import movie informationconst moviesQuery = `LOAD CSV WITH HEADERS FROM 'https://raw.githubusercontent.com/tomasonjo/blog-datasets/main/movies/movies_small.csv'AS rowMERGE (m:Movie {id:row.movieId})SET m.released = date(row.released),    m.title = row.title,    m.imdbRating = toFloat(row.imdbRating)FOREACH (director in split(row.director, '|') |     MERGE (p:Person {name:trim(director)})    MERGE (p)-[:DIRECTED]->(m))FOREACH (actor in split(row.actors, '|') |     MERGE (p:Person {name:trim(actor)})    MERGE (p)-[:ACTED_IN]->(m))FOREACH (genre in split(row.genres, '|') |     MERGE (g:Genre {name:trim(genre)})    MERGE (m)-[:IN_GENRE]->(g))`;await graph.query(moviesQuery);

    Schema refreshed successfully.

    []

Custom tools with Cypher templates[​](#custom-tools-with-cypher-templates "Direct link to Custom tools with Cypher templates")
------------------------------------------------------------------------------------------------------------------------------

A semantic layer consists of various tools exposed to an LLM that it can use to interact with a knowledge graph. They can be of various complexity. You can think of each tool in a semantic layer as a function.

The function we will implement is to retrieve information about movies or their cast.

    const descriptionQuery = `MATCH (m:Movie|Person)WHERE m.title CONTAINS $candidate OR m.name CONTAINS $candidateMATCH (m)-[r:ACTED_IN|HAS_GENRE]-(t)WITH m, type(r) as type, collect(coalesce(t.name, t.title)) as namesWITH m, type+": "+reduce(s="", n IN names | s + n + ", ") as typesWITH m, collect(types) as contextsWITH m, "type:" + labels(m)[0] + "\ntitle: "+ coalesce(m.title, m.name)        + "\nyear: "+coalesce(m.released,"") +"\n" +       reduce(s="", c in contexts | s + substring(c, 0, size(c)-2) +"\n") as contextRETURN context LIMIT 1`;const getInformation = async (entity: string) => {  try {    const data = await graph.query(descriptionQuery, { candidate: entity });    return data[0]["context"];  } catch (error) {    return "No information was found";  }};

You can observe that we have defined the Cypher statement used to retrieve information. Therefore, we can avoid generating Cypher statements and use the LLM agent to only populate the input parameters. To provide additional information to an LLM agent about when to use the tool and their input parameters, we wrap the function as a tool.

    import { StructuredTool } from "@langchain/core/tools";import { z } from "zod";const informationInput = z.object({  entity: z.string().describe("movie or a person mentioned in the question"),});class InformationTool extends StructuredTool {  schema = informationInput;  name = "Information";  description =    "useful for when you need to answer questions about various actors or movies";  async _call(input: z.infer<typeof informationInput>): Promise<string> {    return getInformation(input.entity);  }}

OpenAI Agent[​](#openai-agent "Direct link to OpenAI Agent")
------------------------------------------------------------

LangChain expression language makes it very convenient to define an agent to interact with a graph database over the semantic layer.

    import { ChatOpenAI } from "@langchain/openai";import { AgentExecutor } from "langchain/agents";import { formatToOpenAIFunctionMessages } from "langchain/agents/format_scratchpad";import { OpenAIFunctionsAgentOutputParser } from "langchain/agents/openai/output_parser";import { convertToOpenAIFunction } from "@langchain/core/utils/function_calling";import {  ChatPromptTemplate,  MessagesPlaceholder,} from "@langchain/core/prompts";import { AIMessage, BaseMessage, HumanMessage } from "@langchain/core/messages";import { RunnableSequence } from "@langchain/core/runnables";const llm = new ChatOpenAI({ model: "gpt-3.5-turbo", temperature: 0 });const tools = [new InformationTool()];const llmWithTools = llm.bind({  functions: tools.map(convertToOpenAIFunction),});const prompt = ChatPromptTemplate.fromMessages([  [    "system",    "You are a helpful assistant that finds information about movies and recommends them. If tools require follow up questions, make sure to ask the user for clarification. Make sure to include any available options that need to be clarified in the follow up questions Do only the things the user specifically requested.",  ],  new MessagesPlaceholder("chat_history"),  ["human", "{input}"],  new MessagesPlaceholder("agent_scratchpad"),]);const _formatChatHistory = (chatHistory) => {  const buffer: Array<BaseMessage> = [];  for (const [human, ai] of chatHistory) {    buffer.push(new HumanMessage({ content: human }));    buffer.push(new AIMessage({ content: ai }));  }  return buffer;};const agent = RunnableSequence.from([  {    input: (x) => x.input,    chat_history: (x) => {      if ("chat_history" in x) {        return _formatChatHistory(x.chat_history);      }      return [];    },    agent_scratchpad: (x) => {      if ("steps" in x) {        return formatToOpenAIFunctionMessages(x.steps);      }      return [];    },  },  prompt,  llmWithTools,  new OpenAIFunctionsAgentOutputParser(),]);const agentExecutor = new AgentExecutor({ agent, tools });

    await agentExecutor.invoke({ input: "Who played in Casino?" });

    {  input: "Who played in Casino?",  output: 'The movie "Casino" starred James Woods, Joe Pesci, Robert De Niro, and Sharon Stone.'}

* * *

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

[

Previous

Mapping values to database

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

Next

Prompting strategies

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

*   [Setup](#setup)
*   [Custom tools with Cypher templates](#custom-tools-with-cypher-templates)
*   [OpenAI Agent](#openai-agent)

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.