以node4j为例,BigDL-LLM结合LangChain可以实现对图数据库的检索问答。
1.1 前提准备
首先要用BigDL-LLM加载大模型:
from bigdl.llm.langchain.llms import TransformersLLM
llm = TransformersLLM.from_model_id(
model_id="lmsys/vicuna-7b-v1.5",
model_kwargs={"temperature": 0, "max_length": 1024, "trust_remote_code": True},
)
需要有一个正在运行的 Neo4j 实例。一种选择是在他们的Aura云服务中创建一个免费的Neo4j数据库实例。还可以使用 Neo4j 桌面应用程序在本地运行数据库,或运行 docker 容器。 可以通过运行执行以下脚本来运行本地 docker 容器:
docker run \
--name neo4j \
-p 7474:7474 -p 7687:7687 \
-d \
-e NEO4J_AUTH=neo4j/pleaseletmein \
-e NEO4J_PLUGINS=\[\"apoc\"\] \
neo4j:latest
导入需要的库:
from langchain.chains import GraphCypherQAChain
from langchain.graphs import Neo4jGraph
1.2 图数据库的操作
graph = Neo4jGraph(
url="bolt://localhost:7687", username="neo4j", password="pleaseletmein"
)
数据库内的操作:
graph.query(
"""
MERGE (m:Movie {name:"Top Gun"})
WITH m
UNWIND ["Tom Cruise", "Val Kilmer", "Anthony Edwards", "Meg Ryan"] AS actor
MERGE (a:Actor {name:actor})
MERGE (a)-[:ACTED_IN]->(m)
"""
)
如果数据库的架构发生更改,可以刷新生成 Cypher 语句所需的架构信息。
graph.refresh_schema()
print(graph.get_schema)
Node properties are the following:
[{'properties': [{'property': 'name', 'type': 'STRING'}], 'labels': 'Movie'}, {'properties': [{'property': 'name', 'type': 'STRING'}], 'labels': 'Actor'}]
Relationship properties are the following:
[]
The relationships are the following:
['(:Actor)-[:ACTED_IN]->(:Movie)']
1.3 针对图数据库进行对话
chain = GraphCypherQAChain.from_llm(
llm, graph=graph, verbose=True)
chain.run("Who played in Top Gun?")