> ## 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.

# Kuzu 集成

> 使用 LangChain Python 集成 Kuzu 图。

> [Kùzu](https://kuzudb.com/) 是一个可嵌入、可扩展、极快的图数据库。
> 它采用 MIT 许可证，您可以查看其源代码 [在 GitHub](https://github.com/kuzudb/kuzu)。

> Kùzu 的主要特性：
>
> * 性能和可扩展性：实现了现代、最先进的图连接算法。
> * 易用性：设置和开始使用非常简单，因为它是嵌入式架构，无需服务器。
> * 互操作性：可以方便地从外部列式格式、CSV、JSON 和关系数据库中扫描和复制数据。
> * 结构化属性图模型：实现了属性图模型，并增加了结构。
> * Cypher 支持：允许使用声明式查询语言 Cypher 方便地查询图。

> 通过访问他们的 [文档](https://docs.kuzudb.com/) 来开始使用 Kùzu。

## 设置

Kùzu 是一个嵌入式数据库（它在进程内运行），因此无需管理服务器。安装以下依赖项以开始使用：

> [!WARNING]
>
> `langchain-experimental` 包已不再维护。从 `langchain_experimental` 导入的示例可能过时或已损坏，请谨慎使用。

```bash theme={null}
pip install -U langchain-kuzu langchain-openai langchain-experimental langchain-neo4j
```

这会安装 Kùzu 以及它的 LangChain 集成，以及 OpenAI Python 包，以便我们可以使用 OpenAI 的 LLM。如果您想使用其他 LLM 提供商，可以安装 LangChain 提供的相应 Python 包。

以下是您在本地计算机上首次创建 Kùzu 数据库并连接到它的方法：

```python theme={null}
import kuzu

db = kuzu.Database("test_db")
conn = kuzu.Connection(db)
```

## 创建 `KuzuGraph`

Kùzu 与 LangChain 的集成使得从非结构化文本创建和更新图变得方便，并且还可以通过利用 LangChain LLM 链的强大功能的 Text2Cypher 管道来查询图。首先，我们创建一个 `KuzuGraph` 对象，该对象使用上面创建的数据库对象与 `KuzuGraph` 构造函数结合使用。

```python theme={null}
from langchain_kuzu.graphs.kuzu_graph import KuzuGraph

graph = KuzuGraph(db, allow_dangerous_requests=True)
```

假设我们想把以下文本转换为图：

```python theme={null}
text = "Tim Cook is the CEO of Apple. Apple has its headquarters in California."
```

我们将使用 `LLMGraphTransformer` 来利用 LLM 从文本中提取节点和关系。
为了使图更有用，我们将定义以下架构，以便 LLM 只提取与架构匹配的节点和关系。

```python theme={null}
# Define schema
allowed_nodes = ["Person", "Company", "Location"]
allowed_relationships = [
    ("Person", "IS_CEO_OF", "Company"),
    ("Company", "HAS_HEADQUARTERS_IN", "Location"),
]
```

`LLMGraphTransformer` 类提供了一种方便的方法，可以将文本转换为图文档列表。

```python theme={null}
from langchain_core.documents import Document
from langchain_neo4j import LLMGraphTransformer
from langchain_openai import ChatOpenAI

# Define the LLMGraphTransformer
llm_transformer = LLMGraphTransformer(
    llm=ChatOpenAI(model="gpt-5.4-mini", temperature=0, api_key=OPENAI_API_KEY),
    allowed_nodes=allowed_nodes,
    allowed_relationships=allowed_relationships,
)

documents = [Document(page_content=text)]
graph_documents = llm_transformer.convert_to_graph_documents(documents)
```

```python theme={null}
graph_documents[:2]
```

```text theme={null}
[GraphDocument(nodes=[Node(id='Tim Cook', type='Person', properties={}), Node(id='Apple', type='Company', properties={}), Node(id='California', type='Location', properties={})], relationships=[Relationship(source=Node(id='Tim Cook', type='Person', properties={}), target=Node(id='Apple', type='Company', properties={}), type='IS_CEO_OF', properties={}), Relationship(source=Node(id='Apple', type='Company', properties={}), target=Node(id='California', type='Location', properties={}), type='HAS_HEADQUARTERS_IN', properties={})], source=Document(metadata={}, page_content='Tim Cook is the CEO of Apple. Apple has its headquarters in California.'))]
```

然后，我们可以调用上面定义的 `KuzuGraph` 对象的 `add_graph_documents` 方法，将图文档导入 Kùzu 数据库。
`include_source` 参数设置为 `True`，以便我们创建每个实体节点与其来源文档之间的关系。

```python theme={null}
# Add the graph document to the graph
graph.add_graph_documents(
    graph_documents,
    include_source=True,
)
```

## 创建 `KuzuQAChain`

要通过 Text2Cypher 管道查询图，我们可以定义一个 `KuzuQAChain` 对象。然后，我们可以通过连接到上面定义的 `test_db` 目录中存储的现有数据库来调用链。

```python theme={null}
from langchain_kuzu.chains.graph_qa.kuzu import KuzuQAChain

# Create the KuzuQAChain with verbosity enabled to see the generated Cypher queries
chain = KuzuQAChain.from_llm(
    llm=ChatOpenAI(model="gpt-5.4-mini", temperature=0.3, api_key=OPENAI_API_KEY),
    graph=graph,
    verbose=True,
    allow_dangerous_requests=True,
)
```

请注意，我们设置了一个略高于零的温度，以避免 LLM 在其响应中过于简洁。

让我们使用 QA 链来问一些问题。

```python theme={null}
chain.invoke("Who is the CEO of Apple?")
```

```text theme={null}
> Entering new KuzuQAChain chain...
Generated Cypher:
MATCH (p:Person)-[:IS_CEO_OF]->(c:Company {id: 'Apple'}) RETURN p
Full Context:
[{'p': {'_id': {'offset': 0, 'table': 1}, '_label': 'Person', 'id': 'Tim Cook', 'type': 'entity'}}]

> Finished chain.
```

```text theme={null}
{'query': 'Who is the CEO of Apple?',
 'result': 'Tim Cook is the CEO of Apple.'}
```

```python theme={null}
chain.invoke("Where is Apple headquartered?")
```

```text theme={null}
> Entering new KuzuQAChain chain...
Generated Cypher:
MATCH (c:Company {id: 'Apple'})-[:HAS_HEADQUARTERS_IN]->(l:Location) RETURN l
Full Context:
[{'l': {'_id': {'offset': 0, 'table': 2}, '_label': 'Location', 'id': 'California', 'type': 'entity'}}]

> Finished chain.
```

```text theme={null}
{'query': 'Where is Apple headquartered?',
 'result': 'Apple is headquartered in California.'}
```

## 刷新图架构

如果您修改或更新了图，可以检查 Text2Cypher 链用于生成 Cypher 语句的刷新架构信息。
您不需要每次手动调用 `refresh_schema()`，因为调用链时会自动调用。

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

print(graph.get_schema)
```

```text theme={null}
Node properties: [{'properties': [('id', 'STRING'), ('type', 'STRING')], 'label': 'Person'}, {'properties': [('id', 'STRING'), ('type', 'STRING')], 'label': 'Location'}, {'properties': [('id', 'STRING'), ('text', 'STRING'), ('type', 'STRING')], 'label': 'Chunk'}, {'properties': [('id', 'STRING'), ('type', 'STRING')], 'label': 'Company'}]
Relationships properties: [{'properties': [], 'label': 'HAS_HEADQUARTERS_IN'}, {'properties': [('label', 'STRING'), ('triplet_source_id', 'STRING')], 'label': 'MENTIONS_Chunk_Person'}, {'properties': [('label', 'STRING'), ('triplet_source_id', 'STRING')], 'label': 'MENTIONS_Chunk_Location'}, {'properties': [], 'label': 'IS_CEO_OF'}, {'properties': [('label', 'STRING'), ('triplet_source_id', 'STRING')], 'label': 'MENTIONS_Chunk_Company'}]
Relationships: ['(:Company)-[:HAS_HEADQUARTERS_IN]->(:Location)', '(:Chunk)-[:MENTIONS_Chunk_Person]->(:Person)', '(:Chunk)-[:MENTIONS_Chunk_Location]->(:Location)', '(:Person)-[:IS_CEO_OF]->(:Company)', '(:Chunk)-[:MENTIONS_Chunk_Company]->(:Company)']
```

## 使用不同的 LLM 进行 Cypher 和答案生成

您可以通过指定 `cypher_llm` 和 `qa_llm` 来分别使用不同的 LLM 进行 Cypher 生成和答案生成。

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

```python theme={null}
chain.invoke("Who is the CEO of Apple?")
```

```text theme={null}
> Entering new KuzuQAChain chain...
Generated Cypher:
MATCH (p:Person)-[:IS_CEO_OF]->(c:Company {id: 'Apple'}) RETURN p.id, p.type
Full Context:
[{'p.id': 'Tim Cook', 'p.type': 'entity'}]

> Finished chain.
```

```text theme={null}
{'query': 'Who is the CEO of Apple?',
 'result': 'Tim Cook is the CEO of Apple.'}
```

***

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


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