当前位置: 首页 > news >正文

【Langchain】+ 【baichuan】实现领域知识库【RAG】问答系统

本项目使用Langchainbaichuan 大模型, 结合领域百科词条数据(用xlsx保存),简单地实现了领域百科问答实现。

from langchain.text_splitter import CharacterTextSplitter, RecursiveCharacterTextSplitter
from langchain_community.embeddings import OpenAIEmbeddings, SentenceTransformerEmbeddings
from langchain_community.vectorstores import Chroma, FAISS
from langchain_community.llms import OpenAI, Baichuan
from langchain_community.chat_models import ChatOpenAI, ChatBaichuan
from langchain.memory import ConversationBufferWindowMemory
from langchain.chains import ConversationalRetrievalChain, RetrievalQA
#import langchain_community import chat_models
#print(chat_models.__all__)import streamlit as st
import pandas as pd
import os
import warnings
import time
warnings.filterwarnings('ignore')# 对存储了领域百科词条的xlsx文件进行解析
def get_xlsx_text(xlsx_file):df = pd.read_excel(xlsx_file, engine='openpyxl')text = ""for index, row in df.iterrows():text += row['title'].replace('\n', '')text += row['content'].replace('\n', '')text += '\n\n'return text# Splits a given text into smaller chunks based on specified conditions
def get_text_chunks(text):text_splitter = RecursiveCharacterTextSplitter(separators="\n\n",chunk_size=1000,chunk_overlap=200,length_function=len)chunks = text_splitter.split_text(text)return chunks# 对切分的文本块构建编码向量并存储到FASISS
# Generates embeddings for given text chunks and creates a vector store using FAISS
def get_vectorstore(text_chunks):# embeddings = OpenAIEmbeddings() #有经济条件的可以使用 opanaiembendingembeddings = SentenceTransformerEmbeddings(model_name='all-MiniLM-L6-v2')vectorstore = FAISS.from_texts(texts=text_chunks, embedding=embeddings)return vectorstore
# Initializes a conversation chain with a given vector store# 对切分的文本块构建编码向量并存储到Chroma
# Generates embeddings for given text chunks and creates a vector store using Chroma
def get_vectorstore_chroma(text_chunks):# embeddings = OpenAIEmbeddings()embeddings = SentenceTransformerEmbeddings(model_name='all-MiniLM-L6-v2')vectorstore = Chroma.from_texts(texts=text_chunks, embedding=embeddings)return vectorstoredef get_conversation_chain_baichuan(vectorstore):memory = ConversationBufferWindowMemory(memory_key='chat_history', return_message=True) # 设置记忆存储器conversation_chain = ConversationalRetrievalChain.from_llm(llm=Baichuan(temperature=temperature_input, model_name=model_select),retriever=vectorstore.as_retriever(),get_chat_history=lambda h: h,memory=memory)return conversation_chainos.environ["http_proxy"] = "http://127.0.0.1:7890"
os.environ["https_proxy"] = "http://127.0.0.1:7890"# langchain 可以通过设置环境变量来设置参数
os.environ['BAICHUAN_API_KEY'] = 'sk-88888888888888888888888888888888'
temperature_input = 0.7
model_select = 'Baichuan2-Turbo-192K'
raw_text = get_xlsx_text('领域文件/twiki百科问答.xlsx')text_chunks = get_text_chunks(raw_text)
vectorstore = get_vectorstore_chroma(text_chunks)
# Create conversation chain
qa = get_conversation_chain_baichuan(vectorstore)
questions = ["什么是森林经营项目?","风电项目开发过程中需要的主要资料?","什么是ESG"
]
for question in questions:result = qa(question)print(f"**Question**: {question} \n")print(f"**Answer__**: {result['answer']} \n")
http://www.lryc.cn/news/302823.html

相关文章:

  • Anaconda、conda、pip、virtualenv的区别
  • 【数据结构】每天五分钟,快速入门数据结构(一)——数组
  • NBlog个人博客部署维护过程记录 -- 后端springboot + 前端vue
  • WireShark 安装指南:详细安装步骤和使用技巧
  • PyTorch detach():深入解析与实战应用
  • uniapp 开发一个密码管理app
  • Postman详细攻略
  • 如何在本地服务器部署TeslaMate并远程查看特斯拉汽车数据无需公网ip
  • 如何在CentOS安装SQL Server数据库并实现无公网ip环境远程连接
  • 备战蓝桥杯 Day5
  • 爬虫学习笔记-scrapy爬取电影天堂(双层网址嵌套)
  • Unity笔记:数据持久化的几种方式
  • MySQL 基础知识(八)之用户权限管理
  • QT编写工具基本流程(自用)
  • 代码随想录算法训练营第三六天 | 无重叠区间、划分字母区间、合并区间
  • DP读书:《openEuler操作系统》(十)套接字 Socket 数据传输的基本模型
  • 抓住母亲节销售机会:Shopee 平台选品策略大揭秘
  • Mysql如何优化数据查询方案
  • SwiftUI 更自然地向自定义视图传递参数的“另类”方式
  • Word第一课
  • 【Vue3】路由传参的几种方式
  • 突破编程_C++_面试(高级特性(1))
  • django请求生命周期流程图,路由匹配,路由有名无名反向解析,路由分发,名称空间
  • @ 代码随想录算法训练营第8周(C语言)|Day54(动态规划)
  • Flask 学习100-Flask-SocketIO 结合 xterm.js 实现网页版Xshell
  • Springboot AOP开发
  • office的excel中使用,告诉我详细的解决方案,如何变成转化为金额格式
  • 灾后重建中GIS技术的关键作用与案例分析
  • java环境安装
  • 如何在iStoreOS软路由系统中安装cpolar实现公网远程本地电脑桌面