Langchain 学习03 RAG基础

本文介绍了如何使用AzureOpenAIAPI和RAG(Retrieval-AugmentedGeneration)方法,结合DocArray进行文档检索,并在聊天场景中处理用户问题,实现实时、基于上下文的信息查找和生成答案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

RAG基础

# Requires:
# pip install langchain docarray tiktoken

import os
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())  # 读取本地 .env 文件,里面定义了 OPENAI_API_KEY

#############
api_key = os.environ['AZURE_OPENAI_API_KEY']
azure_endpoint = os.environ['AZURE_OPENAI_ENDPOINT']
api_version = os.environ['AZURE_OPENAPI_VERSION']
model="gpt-35-turbo"
deployment_name="gpt-35-turbo"
############

from langchain_community.vectorstores import DocArrayInMemorySearch
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableParallel, RunnablePassthrough
from langchain_openai.chat_models import AzureChatOpenAI
from langchain_openai.embeddings import AzureOpenAIEmbeddings

## retrieve relevant documents to the search and include them as part of the context.
vectorstore = DocArrayInMemorySearch.from_texts(
    ["harrison worked at kensho", "bears like to eat honey"],
    embedding=AzureOpenAIEmbeddings(),
)
retriever = vectorstore.as_retriever()
## if no vector, the code as following:
# retriever.invoke("where did harrison work?")

template = """Answer the question based only on the following context:
{context}

Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)
model = AzureChatOpenAI(
    model=model,
    deployment_name=deployment_name,
    api_key=api_key,
    azure_endpoint=azure_endpoint,
    api_version=api_version,
)
output_parser = StrOutputParser()
##  create a RunnableParallel object with two entries. The first entry, context will include the document results fetched by the retriever.
## The second entry, question will contain the user’s original question. To pass on the question, we use RunnablePassthrough to copy this entry.
## using the retriever for document search, and RunnablePassthrough to pass the user’s question
setup_and_retrieval = RunnableParallel(
    {"context": retriever, "question": RunnablePassthrough()}
)
chain = setup_and_retrieval | prompt | model | output_parser

print(chain.invoke("where did harrison work?"))
### Graph RAG Retrieval-Augmented Generation Graph RAG(基于检索增强生成的图形结构)是一种结合了图数据结构和检索增强技术的方法,旨在提高自然语言处理任务中的性能。通过引入图结构,可以更好地捕捉实体之间的关系并利用这些关系来进行更有效的推理。 #### 图形结构在RAG中的应用 在传统的RAG框架基础上加入图结构能够显著提升模型的表现力。具体来说,在预训练阶段,除了文本语料库外还加入了富含节点间关联信息的知识图谱作为额外输入[^2]。这使得模型不仅学习到了词法特征,同时也掌握了大量背景知识及其相互联系。 #### LangChain实现与使用 LangChain是一个用于构建对话系统的开源工具包,支持多种类型的后端服务集成,包括但不限于大型语言模型(LLMs)[^1]。对于想要实施Graph RAG的应用场景而言,可以通过如下方式将其融入到现有的工作流当中: 1. **环境准备** 安装必要的依赖项以及配置好运行环境是第一步操作。假设已经安装好了Python开发环境,则只需执行以下命令即可完成所需软件包的下载: ```bash pip install langchain transformers torch dgl ``` 2. **加载预训练模型** 接下来是从Hugging Face或其他平台获取预先训练好的LLM实例,并初始化相应的编码器-解码器架构。 ```python from transformers import AutoModelForSeq2SeqLM, AutoTokenizer model_name = "facebook/bart-large" tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSeq2SeqLM.from_pretrained(model_name) ``` 3. **创建图数据库连接** 使用DGL(Depth-First Library)等库建立与外部存储有向无环图(如Neo4j)或者其他形式图表的数据源链接。 ```python import dgl # 这里仅提供了一个简单的例子;实际部署时可能需要根据具体情况调整参数设置 graph_data = ... # 加载或定义您的图数据集 g = dgl.graph(graph_data) ``` 4. **融合图信息至上下文中** 将来自图数据库的信息嵌入到待处理的任务描述内,以便让下游组件理解当前讨论的具体领域背景。 ```python context_with_graph_info = f"{context}\n\n附加知识点:\n{extracted_knowledge_from_graph}" inputs = tokenizer(context_with_graph_info, return_tensors="pt") outputs = model.generate(**inputs) response_text = tokenizer.decode(outputs[0], skip_special_tokens=True) ``` 5. **优化查询效率** 对于大规模应用场景下可能出现的速度瓶颈问题,考虑采用索引机制加速邻接矩阵查找过程,或是借助GPU资源加快计算速度。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值