构建心理健康QA聊天机器人:FalkorDB和LlamaIndex使用指南

2024年04月01日 由 alex 发表 285 0

介绍

知识图将数据转换为机器可以理解的知识。但“数据”和“知识”之间有什么区别?


现实世界的知识是:


  • 情境:它根据时间和情况而变化
  • 分层:概念之间的关联可能因性别、地区、方言等而异
  • 变化:含义不固定;它随着新想法和关联的发现而改变


简而言之,知识添加了原始数据中经常缺失的“背景”。传统的数据管理系统并未经过培训,无法以结构化方式捕获含义或关系。另一方面,知识图 (KG) 旨在捕获知识固有的语义性质,为应用程序存储新数据、定义、事件、情况或概念提供基础。


本质上,知识图是知识的结构化表示,它捕获实体、它们的属性以及它们之间的关系。它旨在使应用程序更容易理解和推理现实世界。


知识图谱经常用于 NLP 和其他人工智能应用程序。通过为应用程序提供知识的结构化表示,我们可以构建能够更好地理解文本含义的系统。


总之,知识图是一个灵活的数据层,用于回答跨数据孤岛的复杂查询。它们允许与以图表形式表示和组织的情境化数据相连接。企业知识图谱就是企业数据的知识图谱。


在本文中,我们将使用 OpenAI、知识图 FalkorDB 和 LlamaIndex 构建一个医疗保健聊天机器人。但在开始之前,让我们先了解一下为什么我们选择知识图谱来构建此 RAG,而不是矢量数据库。


为什么知识图谱比矢量数据库更可靠?

知识图谱的不可预测性可能导致幻觉,给追求准确性和可靠性的企业带来挑战。检索增强生成(RAG)是一种通过将 LLM 落地来克服这些挑战的方法。知识图谱和矢量数据库是实现 RAG 的两种主要选择。但是,哪种方法能为 LLM 提供更可靠、更可解释的基础呢?


在 RAG 应用中,越来越多的人选择知识图谱,而不是矢量数据库,这有几个原因。首先,知识图谱具有人类可读的数据表示,使其更容易理解和解释。这与矢量数据库形成鲜明对比,后者使用矢量嵌入进行操作,因此难以理解。其次,知识图谱提供了可解释的结果,因为它们显示了实体之间的关系和联系,使用户能够理解结果背后的推理。另一方面,矢量数据库则不具备可解释性,因为它们无法提供与结果背后的推理相同程度的透明度。


尤其是在医疗保健领域,结果的可解释性至关重要。通过使用知识图谱,我们可以调整作为 LLM 基础的数据层,确保结果具有更高的准确性。因此,我们将尝试使用知识图谱来构建我们的聊天机器人。


FalkorDB:超低延迟知识图谱

根据 FalkorDB 自己的定义,它 "是一种用于低延迟和高吞吐量场景的超快图数据库"。它以超低延迟而著称,可以使用 Docker 运行。


我选择 FalkorDB 的原因如下:


  • 超低延迟: FalkorDB 的超低延迟非常适合需要快速响应时间的应用。
  • 功能强大: FalkorDB采用了强大的知识图谱,可以高效地表示和查询结构化数据,并捕捉人、地点、事件和产品等实体的关系和属性。
  • 与LLM相结合: 通过将知识图谱与LLMs集成,FalkorDB充分利用了两者的优势。


代码实现


安装所需的依赖项


pip install openai
!pip install llama-index
!pip install llama-index-llms-openai
!pip install llama-index-graph-stores-falkordb


使用 Docker 在本地启动 FalkorDB

将FalkorDB作为图形数据库启动的最简单方法是使用falkordb docker镜像。这个 docker 镜像内置了 FalkorDB 浏览器,可以让你可视化图表。


启动该镜像的方法如下:


docker run -p 6379:6379 -p 3000:3000 -it --rm falkordb/falkordb:latest6379:6379 -p 3000:3000 -it --rm falkordb/falkordb:latest

/FalkorDB/build/docker/run.sh: 11: [: -eq: unexpected operator
8:C 21 Jan 2024 13:25:35.914 # WARNING Memory overcommit must be enabled! Without it, a background save or replication may fail under low memory conditions. Being disabled, it can also cause failures without low memory condition, see https://github.com/jemalloc/jemalloc/issues/1328. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
8:C 21 Jan 2024 13:25:35.915 * oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
8:C 21 Jan 2024 13:25:35.915 * Redis version=7.2.3, bits=64, commit=00000000, modified=0, pid=8, just started
8:C 21 Jan 2024 13:25:35.915 * Configuration loaded
8:M 21 Jan 2024 13:25:35.915 * monotonic clock: POSIX clock_gettime
                _._
           _.-``__ ''-._
      _.-``    `.  `_.  ''-._           Redis 7.2.3 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._
 (    '      ,       .-`  | `,    )     Running in standalone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 8
  `-._    `-._  `-./  _.-'    _.-'
 |`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |           https://redis.io
  `-._    `-._`-.__.-'_.-'    _.-'
 |`-._`-._    `-.__.-'    _.-'_.-'|
 |    `-._`-._        _.-'_.-'    |
  `-._    `-._`-.__.-'_.-'    _.-'
      `-._    `-.__.-'    _.-'
          `-._        _.-'
              `-.__.-'
8:M 21 Jan 2024 13:25:35.940 * <graph> Enabled role change notification
8:M 21 Jan 2024 13:25:35.941 * <graph> Starting up FalkorDB version 4.0.3.
8:M 21 Jan 2024 13:25:35.943 * <graph> Thread pool created, using 12 threads.
8:M 21 Jan 2024 13:25:35.943 * <graph> Maximum number of OpenMP threads set to 12
8:M 21 Jan 2024 13:25:35.943 * <graph> Query backlog size: 1000
8:M 21 Jan 2024 13:25:35.943 * Module 'graph' loaded from /FalkorDB/bin/linux-x64-release/src/falkordb.so
8:M 21 Jan 2024 13:25:35.944 * Server initialized
8:M 21 Jan 2024 13:25:35.945 * Ready to accept connections tcp


实例化知识图谱


from llama_index.graph_stores.falkordb import FalkorDBGraphStore
import logging
import sys

logging.basicConfig(stream=sys.stdout, level=logging.INFO)

graph_store = FalkorDBGraphStore(
    "redis://localhost:6379", decode_responses=True
)


下载数据

在本例中,我们将使用澳大利亚政府发布的有关心理健康的 PDF 文件。您也可以创建一个更大的文档列表作为知识源。


mkdir data
wget "https://www.slhd.nsw.gov.au/mentalhealth/pdf/what_is_mental_illness.pdf" -P "./data""https://www.slhd.nsw.gov.au/mentalhealth/pdf/what_is_mental_illness.pdf" -P "./data"
wget "https://www.hhs.gov/sites/default/files/sg-youth-mental-health-social-media-advisory.pdf" -P "./data"
wget "https://files.eric.ed.gov/fulltext/EJ1154566.pdf" -P "./data"


导入所需的依赖项


import os
from llama_index.core import Settings
from llama_index.llms.openai import OpenAI
from llama_index.core import StorageContext
from IPython.display import Markdown, display
from llama_index.core import SimpleDirectoryReader, KnowledgeGraphIndex
os.environ["OPENAI_API_KEY"] = "<your OpenAI API key here>"


读取数据并处理文档


documents = SimpleDirectoryReader("./data").load_data()"./data").load_data()
将文档转换为三元组,并存储到 FalkorDB 中
llm = OpenAI(temperature=0, model="gpt-3.5-turbo")0, model="gpt-3.5-turbo")
Settings.llm = llm
Settings.chunk_size = 512

storage_context = StorageContext.from_defaults(graph_store=graph_store)

# NOTE: can take a while!
index = KnowledgeGraphIndex.from_documents(
    documents,
    max_triplets_per_chunk=20,
    storage_context=storage_context,


图表可视化

要可视化图表,只需在浏览器中加载以下网址。


http://localhost:3000。


这将显示如下界面:


1


注:如果在远程机器上运行代码,则需要打开 3000 端口,并使用以下网址:


http://[remote_host_ip]:3000


实例化查询引擎


query_engine = index.as_query_engine(
    include_text=True, response_mode="tree_summarize", verbose=TrueTrue, response_mode="tree_summarize", verbose=True
)


提问


response = query_engine.query(
    "What is mental health?","What is mental health?",
)
display(Markdown(f"<b>{response}</b>"))


生成的回复


Mental health refers to a person's emotional, psychological, and social well-being. It involves how individuals think, feel, and act, and also helps determine how they handle stress, relate to others, and make choices. Good mental health is essential for overall well-being and can impact various aspects of a person's life.'s emotional, psychological, and social well-being. It involves how individuals think, feel, and act, and also helps determine how they handle stress, relate to others, and make choices. Good mental health is essential for overall well-being and can impact various aspects of a person's life.


安装 Gradio UI


!pip install --upgrade gradio


启动 Gradio 聊天机器人


import gradio as gr

def response_function(message, history):
    resp = query_engine.query(message)
    resp = f"{resp}"
    print(resp)
    return resp

gr.ChatInterface(
    response_function,
    chatbot=gr.Chatbot(height=500),
    textbox=gr.Textbox(placeholder="Ask any question related to mental health", container=False, scale=7),
    title="Mental Health Chatbot",
    description="You can ask this chatbot any question related to mental health",
    theme="soft",
    examples=["What is mental health?", "What is mental health a challenging topic?", "Where should you go to seek help?"],
    cache_examples=True,
    retry_btn=None,
    undo_btn="Delete Previous",
    clear_btn="Clear",
).launch(share=True)


这将启动 Gradio 聊天机器人用户界面。你会在笔记本上看到它,也会在 72 小时后失效的公共链接上看到它。如果你在浏览器中打开它,就会看到以下界面:


2


让我们用一个问题来验证一下。假设我们问 "什么是心理健康?


3


如你所见,答复相当到位:


"心理健康是指一个人的情绪、心理和社会福祉。它涉及个人在应对生活及其挑战时的思维、感觉和行为方式。良好的心理健康有助于一个人的整体福祉,并有助于建立积极的人际关系、做出正确的决定和有效地处理压力"。


操纵图表

您可以不依赖 KnowledgeGraphIndex() 函数,自己添加三元组来进一步操作图表。


下面是一个如何操作的示例:


MERGE (depression:MentalIllnessType {name: "Depression"})"Depression"})
MERGE (anxiety:MentalIllnessType {name: "Anxiety"})
MERGE (schizophrenia:MentalIllnessType {name: "Schizophrenia"})
MERGE (bipolar:MentalIllnessType {name: "Bipolar Mood Disorder"})
MERGE (personalityDisorders:MentalIllnessType {name: "Personality Disorders"})
MERGE (eatingDisorders:MentalIllnessType {name: "Eating Disorders"})

MERGE (mi)-[:IS_A_TYPE_OF]->(mhp)

MERGE (mhp)-[:CAN_DEVELOP_INTO]->(mi)

MERGE (depression)-[:IS_A]->(mi)
MERGE (anxiety)-[:IS_A]->(mi)
MERGE (schizophrenia)-[:IS_A]->(mi)
MERGE (bipolar)-[:IS_A]->(mi)
MERGE (personalityDisorders)-[:IS_A]->(mi)
MERGE (eatingDisorders)-[:IS_A]->(mi)

"""
graph_store.query(cypher_query)


结果

现在让我们用几个问题来测试一下聊天机器人。


4


您可以继续对话并提出后续问题,如下所示。


5


如您所见,答案相当准确,展示了知识图谱 LLM 的能力。您可以将类似的方法应用于多个领域。


结论

将知识图谱纳入 RAG 管道后,我们就能将 LLMs 落地。在医疗保健等领域,这一点至关重要,因为 LLM 的幻觉可能会带来极大的问题。在本文中,我们演示了如何结合 FalkorDB 知识图谱、OpenAI 和 LlamaIndex 来构建一个简单的医疗聊天机器人。我们还展示了操作图的方法,以及使用 Gradio 启动基本聊天机器人用户界面的方法。敬请期待未来更多此类实验,我们将使用 LLM 深入研究知识图谱操作。


文章来源:https://medium.com/the-ai-forum/building-a-mental-health-qa-chatbot-using-falkordb-knowledge-graph-and-llamaindex-d78be8d50f97
欢迎关注ATYUN官方公众号
商务合作及内容投稿请联系邮箱:bd@atyun.com
评论 登录
热门职位
Maluuba
20000~40000/月
Cisco
25000~30000/月 深圳市
PilotAILabs
30000~60000/年 深圳市
写评论取消
回复取消