> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Neo4j 集成

> 使用 LangChain Python 集成 Neo4j 图。

> [Neo4j](https://neo4j.com/docs/getting-started/) 是由 `Neo4j, Inc` 开发的图数据库管理系统。

> `Neo4j` 存储的元素包括节点、连接它们的边以及节点和边的属性。其开发者将其描述为具有原生图存储和处理的ACID兼容事务数据库， `Neo4j` 提供非开源的"社区版"，采用GNU通用公共许可证的修改版进行许可，同时提供在线备份和高可用性扩展（采用闭源商业许可）。Neo也以闭源商业条款许可了这些扩展的 `Neo4j`。

> 该笔记本演示如何使用大语言模型（LLMs）为可使用 `Cypher` 查询语言的图数据库提供自然语言接口。

> [Cypher](https://en.wikipedia.org/wiki/Cypher_\(query_language\)) 是一种声明式图查询语言，支持在属性图中进行表达能力强且高效的查询。

## 设置

您需要先启动 `Neo4j` 实例。一种方法是创建 [Neo4j免费Aura云服务数据库实例](https://neo4j.com/cloud/platform/aura-graph-database/) ，或使用 [Neo4j桌面应用程序](https://neo4j.com/download/) 本地运行数据库，也可通过Docker容器部署。

本地运行Docker容器可通过执行以下脚本：

```
docker run \
    --name neo4j \
    -p 7474:7474 -p 7687:7687 \
    -d \
    -e NEO4J_AUTH=neo4j/password \
    -e NEO4J_PLUGINS=\[\"apoc\"\]  \
    neo4j:latest
```

如果使用Docker容器，需要等待几秒钟让数据库启动。

```python theme={null}
from langchain_neo4j import GraphCypherQAChain, Neo4jGraph
from langchain_openai import ChatOpenAI
```

```python theme={null}
graph = Neo4jGraph(url="bolt://localhost:7687", username="neo4j", password="password")
```

我们默认使用OpenAI模型。

```python theme={null}
import getpass
import os

if "OPENAI_API_KEY" not in os.environ:
    os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
```

## 初始化数据库

假设数据库为空，可通过Cypher查询语言填充数据。以下Cypher语句是幂等的，即无论运行一次或多次，数据库信息都将保持一致。

```python theme={null}
graph.query(
    """
MERGE (m:Movie {name:"Top Gun", runtime: 120})
WITH m
UNWIND ["Tom Cruise", "Val Kilmer", "Anthony Edwards", "Meg Ryan"] AS actor
MERGE (a:Actor {name:actor})
MERGE (a)-[:ACTED_IN]->(m)
"""
)
```

```text theme={null}
[]
```

## 刷新图元数据信息

当数据库架构发生变化时，可通过刷新所需生成Cypher语句的元数据信息。

```python theme={null}
graph.refresh_schema()
```

```python theme={null}
print(graph.schema)
```

```text theme={null}
Node properties:
Movie {runtime: INTEGER, name: STRING}
Actor {name: STRING}
Relationship properties:

The relationships:
(:Actor)-[:ACTED_IN]->(:Movie)
```

## 增强元数据信息

选择增强的元数据版本可使系统自动扫描数据库中的示例值并计算一些分布指标。例如，如果节点属性有少于10个不同值，则在元数据中返回所有可能值；否则，每个节点和关系属性仅返回一个示例值。

```python theme={null}
enhanced_graph = Neo4jGraph(
    url="bolt://localhost:7687",
    username="neo4j",
    password="password",
    enhanced_schema=True,
)
print(enhanced_graph.schema)
```

```text theme={null}
Node properties:
- **Movie**
  - `runtime`: INTEGER Min: 120, Max: 120
  - `name`: STRING Available options: ['Top Gun']
- **Actor**
  - `name`: STRING Available options: ['Tom Cruise', 'Val Kilmer', 'Anthony Edwards', 'Meg Ryan']
Relationship properties:

The relationships:
(:Actor)-[:ACTED_IN]->(:Movie)
```

## 图查询

现在可以使用图Cypher QA链对图进行提问。

```python theme={null}
chain = GraphCypherQAChain.from_llm(
    ChatOpenAI(temperature=0), graph=graph, verbose=True, allow_dangerous_requests=True
)
```

```python theme={null}
chain.invoke({"query": "Who played in Top Gun?"})
```

```text theme={null}
> Entering new GraphCypherQAChain chain...
Generated Cypher:
MATCH (a:Actor)-[:ACTED_IN]->(m:Movie)
WHERE m.name = 'Top Gun'
RETURN a.name
Full Context:
[{'a.name': 'Tom Cruise'}, {'a.name': 'Val Kilmer'}, {'a.name': 'Anthony Edwards'}, {'a.name': 'Meg Ryan'}]

> Finished chain.
```

```text theme={null}
{'query': 'Who played in Top Gun?',
 'result': 'Tom Cruise, Val Kilmer, Anthony Edwards, and Meg Ryan played in Top Gun.'}
```

## 限制返回结果数量

可通过 `top_k` 参数限制Cypher QA链的返回结果数量。默认值为10。

```python theme={null}
chain = GraphCypherQAChain.from_llm(
    ChatOpenAI(temperature=0),
    graph=graph,
    verbose=True,
    top_k=2,
    allow_dangerous_requests=True,
)
```

```python theme={null}
chain.invoke({"query": "Who played in Top Gun?"})
```

```text theme={null}
> Entering new GraphCypherQAChain chain...
Generated Cypher:
MATCH (a:Actor)-[:ACTED_IN]->(m:Movie)
WHERE m.name = 'Top Gun'
RETURN a.name
Full Context:
[{'a.name': 'Tom Cruise'}, {'a.name': 'Val Kilmer'}]

> Finished chain.
```

```text theme={null}
{'query': 'Who played in Top Gun?',
 'result': 'Tom Cruise, Val Kilmer played in Top Gun.'}
```

## 返回中间结果

可通过 `return_intermediate_steps` 参数返回Cypher QA链的中间步骤。

```python theme={null}
chain = GraphCypherQAChain.from_llm(
    ChatOpenAI(temperature=0),
    graph=graph,
    verbose=True,
    return_intermediate_steps=True,
    allow_dangerous_requests=True,
)
```

```python theme={null}
result = chain.invoke({"query": "Who played in Top Gun?"})
print(f"Intermediate steps: {result['intermediate_steps']}")
print(f"Final answer: {result['result']}")
```

```text theme={null}
> Entering new GraphCypherQAChain chain...
Generated Cypher:
MATCH (a:Actor)-[:ACTED_IN]->(m:Movie)
WHERE m.name = 'Top Gun'
RETURN a.name
Full Context:
[{'a.name': 'Tom Cruise'}, {'a.name': 'Val Kilmer'}, {'a.name': 'Anthony Edwards'}, {'a.name': 'Meg Ryan'}]

> Finished chain.
Intermediate steps: [{'query': "MATCH (a:Actor)-[:ACTED_IN]->(m:Movie)\nWHERE m.name = 'Top Gun'\nRETURN a.name"}, {'context': [{'a.name': 'Tom Cruise'}, {'a.name': 'Val Kilmer'}, {'a.name': 'Anthony Edwards'}, {'a.name': 'Meg Ryan'}]}]
Final answer: Tom Cruise, Val Kilmer, Anthony Edwards, and Meg Ryan played in Top Gun.
```

## 返回直接结果

可通过 `return_direct` 参数返回Cypher QA链的直接结果。

```python theme={null}
chain = GraphCypherQAChain.from_llm(
    ChatOpenAI(temperature=0),
    graph=graph,
    verbose=True,
    return_direct=True,
    allow_dangerous_requests=True,
)
```

```python theme={null}
chain.invoke({"query": "Who played in Top Gun?"})
```

```text theme={null}
> Entering new GraphCypherQAChain chain...
Generated Cypher:
MATCH (a:Actor)-[:ACTED_IN]->(m:Movie)
WHERE m.name = 'Top Gun'
RETURN a.name

> Finished chain.
```

```text theme={null}
{'query': 'Who played in Top Gun?',
 'result': [{'a.name': 'Tom Cruise'},
  {'a.name': 'Val Kilmer'},
  {'a.name': 'Anthony Edwards'},
  {'a.name': 'Meg Ryan'}]}
```

## 在Cypher生成提示词中添加示例

可定义特定问题所需的Cypher语句，供大语言模型生成。

```python theme={null}
from langchain_core.prompts.prompt import PromptTemplate

CYPHER_GENERATION_TEMPLATE = """Task:Generate Cypher statement to query a graph database.
Instructions:
Use only the provided relationship types and properties in the schema.
Do not use any other relationship types or properties that are not provided.
Schema:
{schema}
Note: Do not include any explanations or apologies in your responses.
Do not respond to any questions that might ask anything else than for you to construct a Cypher statement.
Do not include any text except the generated Cypher statement.
Examples: Here are a few examples of generated Cypher statements for particular questions:
# How many people played in Top Gun?
MATCH (m:Movie {{name:"Top Gun"}})<-[:ACTED_IN]-()
RETURN count(*) AS numberOfActors

The question is:
{question}"""

CYPHER_GENERATION_PROMPT = PromptTemplate(
    input_variables=["schema", "question"], template=CYPHER_GENERATION_TEMPLATE
)

chain = GraphCypherQAChain.from_llm(
    ChatOpenAI(temperature=0),
    graph=graph,
    verbose=True,
    cypher_prompt=CYPHER_GENERATION_PROMPT,
    allow_dangerous_requests=True,
)
```

```python theme={null}
chain.invoke({"query": "How many people played in Top Gun?"})
```

```text theme={null}
> Entering new GraphCypherQAChain chain...
Generated Cypher:
MATCH (m:Movie {name:"Top Gun"})<-[:ACTED_IN]-()
RETURN count(*) AS numberOfActors
Full Context:
[{'numberOfActors': 4}]

> Finished chain.
```

```text theme={null}
{'query': 'How many people played in Top Gun?',
 'result': 'There were 4 actors in Top Gun.'}
```

## 为Cypher和答案生成使用独立LLM

可通过 `cypher_llm` 和 `qa_llm` 参数定义不同的LLM。

```python theme={null}
chain = GraphCypherQAChain.from_llm(
    graph=graph,
    cypher_llm=ChatOpenAI(temperature=0, model="gpt-4o-mini"),
    qa_llm=ChatOpenAI(temperature=0, model="gpt-4o-mini"),
    verbose=True,
    allow_dangerous_requests=True,
)
```

```python theme={null}
chain.invoke({"query": "Who played in Top Gun?"})
```

```text theme={null}
> Entering new GraphCypherQAChain chain...
Generated Cypher:
MATCH (a:Actor)-[:ACTED_IN]->(m:Movie)
WHERE m.name = 'Top Gun'
RETURN a.name
Full Context:
[{'a.name': 'Tom Cruise'}, {'a.name': 'Val Kilmer'}, {'a.name': 'Anthony Edwards'}, {'a.name': 'Meg Ryan'}]

> Finished chain.
```

```text theme={null}
{'query': 'Who played in Top Gun?',
 'result': 'Tom Cruise, Val Kilmer, Anthony Edwards, and Meg Ryan played in Top Gun.'}
```

## 忽略指定的节点和关系类型

可通过 `include_types` 或 `exclude_types` 忽略图元数据中的部分内容。

```python theme={null}
chain = GraphCypherQAChain.from_llm(
    graph=graph,
    cypher_llm=ChatOpenAI(temperature=0, model="gpt-4o-mini"),
    qa_llm=ChatOpenAI(temperature=0, model="gpt-4o-mini"),
    verbose=True,
    exclude_types=["Movie"],
    allow_dangerous_requests=True,
)
```

```python theme={null}
# Inspect graph schema
print(chain.graph_schema)
```

```text theme={null}
Node properties are the following:
Actor {name: STRING}
Relationship properties are the following:

The relationships are the following:
```

## 验证生成的Cypher语句

可通过 `validate_cypher` 参数验证并修正生成的Cypher语句中的关系方向。

```python theme={null}
chain = GraphCypherQAChain.from_llm(
    llm=ChatOpenAI(temperature=0, model="gpt-4o-mini"),
    graph=graph,
    verbose=True,
    validate_cypher=True,
    allow_dangerous_requests=True,
)
```

```python theme={null}
chain.invoke({"query": "Who played in Top Gun?"})
```

```text theme={null}
> Entering new GraphCypherQAChain chain...
Generated Cypher:
MATCH (a:Actor)-[:ACTED_IN]->(m:Movie)
WHERE m.name = 'Top Gun'
RETURN a.name
Full Context:
[{'a.name': 'Tom Cruise'}, {'a.name': 'Val Kilmer'}, {'a.name': 'Anthony Edwards'}, {'a.name': 'Meg Ryan'}]

> Finished chain.
```

```text theme={null}
{'query': 'Who played in Top Gun?',
 'result': 'Tom Cruise, Val Kilmer, Anthony Edwards, and Meg Ryan played in Top Gun.'}
```

## 将数据库结果作为工具/函数输出

可通过 `use_function_response` 参数将数据库结果作为工具/函数输出传递给LLM。此方法可提高响应的准确性和相关性，因为LLM会更紧密地遵循提供的上下文。
*您需要使用原生支持函数调用的LLM才能使用此功能*。

```python theme={null}
chain = GraphCypherQAChain.from_llm(
    llm=ChatOpenAI(temperature=0, model="gpt-4o-mini"),
    graph=graph,
    verbose=True,
    use_function_response=True,
    allow_dangerous_requests=True,
)
chain.invoke({"query": "Who played in Top Gun?"})
```

```text theme={null}
> Entering new GraphCypherQAChain chain...
Generated Cypher:
MATCH (a:Actor)-[:ACTED_IN]->(m:Movie)
WHERE m.name = 'Top Gun'
RETURN a.name
Full Context:
[{'a.name': 'Tom Cruise'}, {'a.name': 'Val Kilmer'}, {'a.name': 'Anthony Edwards'}, {'a.name': 'Meg Ryan'}]

> Finished chain.
```

```text theme={null}
{'query': 'Who played in Top Gun?',
 'result': 'The main actors in Top Gun are Tom Cruise, Val Kilmer, Anthony Edwards, and Meg Ryan.'}
```

在使用函数响应功能时，可通过 `function_response_system` 参数提供自定义系统消息，以指导模型如何生成答案。

*注意：当使用 `use_function_response` 时， `qa_prompt` 将失效*

```python theme={null}
chain = GraphCypherQAChain.from_llm(
    llm=ChatOpenAI(temperature=0, model="gpt-4o-mini"),
    graph=graph,
    verbose=True,
    use_function_response=True,
    function_response_system="Respond as a pirate!",
    allow_dangerous_requests=True,
)
chain.invoke({"query": "Who played in Top Gun?"})
```

```text theme={null}
> Entering new GraphCypherQAChain chain...
Generated Cypher:
MATCH (a:Actor)-[:ACTED_IN]->(m:Movie)
WHERE m.name = 'Top Gun'
RETURN a.name
Full Context:
[{'a.name': 'Tom Cruise'}, {'a.name': 'Val Kilmer'}, {'a.name': 'Anthony Edwards'}, {'a.name': 'Meg Ryan'}]

> Finished chain.
```

```text theme={null}
{'query': 'Who played in Top Gun?',
 'result': "Arrr matey! In the film Top Gun, ye be seein' Tom Cruise, Val Kilmer, Anthony Edwards, and Meg Ryan sailin' the high seas of the sky! Aye, they be a fine crew of actors, they be!"}
```

***

> 官方原文：[src/oss/python/integrations/graphs/neo4j\_cypher.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/python/integrations/graphs/neo4j_cypher.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.