LLM学习(6)—— LLM 应用
以下项目参考自Datawhale不过只有其中一点点功能@Datawhale
简易知识库助手
相对于LLM学习(4),首先更改了embedding的方式,由Gemini换成了zhipu,Gemini的人工zz嵌入模型实在太离谱了,把none选项改成了包含历史对话而不仅仅是一问一答,增加了对于pdf和md文件的的导入然后转换为检索词向量库(chroma)。新增加了一个prompt的文本框,我感觉默认的值其实已经不错了。
存在的问题
- 因为我的prompt并没有区分三种不同的问答情况(qa,none,qa_chain)我只是把none内个部分的context置为[None]区分history也是这样我只是单纯的把history置为[None]但是已经在给定prompt中“you have a conversation with a human”和“And your answer should refer to the context provided”的情况下给None是否会造成某些奇奇怪怪的错误或者使得结果变得没有那么好,这里我没有经过实验。
- 大量使用回调函数然后global而不是传参,使用gradio库中的传参问题在前面的LLM学习中已经说过了LLM学习(4),不知道为什么gradio里面参数我不使用global的时候是值传递???,直接复制了一份,但是我希望他不停的监控文本框、选择栏的输入,这样显然是不行的,所以被逼无奈才出此下策(减慢了速度),不知道到底是库的问题还是一开始我的代码逻辑就有问题。
- 只是在开头实现了删除chroma向量库,而不是在GUI中实现,因为关一次删一次只能这样,但是我希望有个显示栏去显示已经存在的向量库,和按钮确定是否清除。以后有机会我会补充一个LLM(6)续集(虽然大概率是🕊)。
- 程序中并没有给出 zhipuembedding ,请自己去查看@Datawhale然后下载,程序中也没有设置环境变量,你可以通过启用
!set ZHIPUAI_API_KEY=you key
去设置环境变量用!setx ZHIPUAI_API_KEY ""
去删除,也可以自己写个bat文件运行,但是我更推荐手动去win设置里面添加删除。 - 如果你启用了向量库的删除多次删除过后可以因为某些不知名的进程占用导致删除失败,这时候就需要自己手动关闭进程,最简单的就是直接把代码重启。
- split 必须在load之前,而且prompt必须更改,但是你可以只复制一下(实现逻辑问题,会改的会改的🕊🕊🕊🕊🕊🕊🕊🕊🕊🕊🕊🕊🕊)
导入库文件
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain.prompts import PromptTemplate
from langchain.chains import create_retrieval_chain
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain.vectorstores.chroma import Chroma
import gradio as gr
import os
import psutil
from langchain_community.document_loaders import PyMuPDFLoader
from zhipuai_embedding import ZhipuAIEmbeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter
#这里注意把端口改成你自己的,如果不知道端口多少那么试试7890再试试10809
os.environ['http_proxy'] = 'http://127.0.0.1:10809'
os.environ['https_proxy'] = 'http://127.0.0.1:10809'
#!set ZHIPUAI_API_KEY=you key
# 测试连接是否成功
# llm = ChatGoogleGenerativeAI(model="gemini-pro",google_api_key="")
# result = llm.invoke("message")
# print(result.content)
删除之前的向量库(可以注释掉)
def delete_folder_contents(folder_path):
#遍历文件夹中的所有文件和子文件夹
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
#如果是文件,则直接删除
if os.path.isfile(file_path):
os.remove(file_path)
#如果是子文件夹,则递归删除其内容
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
folder_path = "./data/vector_db_zhipu/chroma"
delete_folder_contents(folder_path)
#!rm -rf './data/vector_db_zhipu/chroma' ##linux直接用这个命令就行,不需要那么麻烦
函数
# 检索链+历史对话
def get_chat_qa_chain(chat_history,api_key,message,template):
llm = ChatGoogleGenerativeAI(model="gemini-pro",google_api_key=api_key)
path = './data/vector_db_zhipu/chroma'
embeddings = ZhipuAIEmbeddings()
vectordb=Chroma(
persist_directory=path,
embedding_function=embeddings
)
print(f"向量库中存储的数量:{vectordb._collection.count()}")
# template = """You are a helpful AI assistant and you have a conversation with a human
# chat_history:{chat_history}
# And your answer should refer to the context provided below in addition to the chat_history.
# context: {context}
# input: {input}
# answer:
# """
retriever=vectordb.as_retriever()
prompt = PromptTemplate.from_template(template)
combine_docs_chain = create_stuff_documents_chain(llm, prompt)
retrieval_chain = create_retrieval_chain(retriever, combine_docs_chain)
result=retrieval_chain.invoke({"input":message,"chat_history":chat_history})
return result["answer"]
# 检索链
def get_qa_chain(api_key,message,template):
return get_chat_qa_chain(chat_history=[None],api_key=api_key,message=message,template=template)
# 历史对话
def get_qa(api_key,input,history,template):
# template = """You are a helpful AI assistant and you have a conversation with a human
# chat_history:{chat_history}
# input: {input}
# answer:
# """
prompt_template = PromptTemplate.from_template(template)
message=prompt_template.format(chat_history=history,input=input,context=[None])
llm = ChatGoogleGenerativeAI(model="gemini-pro",google_api_key=api_key)
result = llm.invoke(message)
print(result.content)
return result.content
# 历史对话转换格式
def transform_history(history):
new_history=[]
for chat in history:
new_history.append({"user":chat[0]})
new_history.append({"AI":chat[1]})
return new_history
GUI
with gr.Blocks() as demo:
radio = gr.Radio(
["qa", "chat_qa", "none"], label="What mode do you want?"
)
def radio_change(R):
global select_mode
select_mode=R
radio.change(fn=radio_change,inputs=radio)
api_key=gr.Textbox(lines=1, placeholder="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", label="your api_key")
def api_change(A):
global API_key
API_key=A
api_key.change(fn=api_change,inputs=api_key)
split=gr.Slider(20, 1000, label="split", info="Choose split_documents between 5 and 1000")
def split_change(split):
global sp
sp=split
split.change(fn=split_change,inputs=split)
with gr.Row():
global pp
file=gr.File(file_count="multiple",file_types=["file"])
template = """You are a helpful AI assistant and you have a conversation with a human
chat_history:{chat_history}
And your answer should refer to the context provided below in addition to the chat_history.
context: {context}
input: {input}
answer:
"""
prompt=gr.Textbox(placeholder="""You are a helpful AI assistant and you have a conversation with a human
chat_history:{chat_history}
And your answer should refer to the context provided below in addition to the chat_history.
context: {context}
input: {input}
answer:
""", label="your prompt[the chat_history,contex,input,answer must in it]",value=template)
# print(type(file))
def pdf_load(files):
global sp
loaders = []
for f in files:
file_path=f.name
file_type = file_path.split('.')[-1]
if file_type == 'pdf':
loaders.append(PyMuPDFLoader(file_path))
elif file_type == 'md':
loaders.append(UnstructuredMarkdownLoader(file_path))
texts = []
for loader in loaders: texts.extend(loader.load())
text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
split_docs = text_splitter.split_documents(texts)
print(len(split_docs))
embeddings = ZhipuAIEmbeddings()
persist_directory = './data/vector_db_zhipu/chroma'
print(sp)
vectordb = Chroma.from_documents(
documents=split_docs[:sp],
embedding=embeddings,
persist_directory=persist_directory)
vectordb.persist()
def prompt_change(prompt):
global pp
pp=prompt
file.change(fn=pdf_load,inputs=file)
prompt.change(fn=prompt_change,inputs=prompt)
# print(type(file))
chatbot = gr.Chatbot()
msg=gr.Textbox()
def select(message,chat_history):
print(message)
global select_mode
global API_key
global pp
print(pp)
# print(API_key)
# print(select_mode)
# print('Stop0')
bot_message=""
history=transform_history(chat_history)
if select_mode=="none":
bot_message=get_qa(api_key=API_key,input=message,history=history,template=pp)
# print('Stop2')
elif select_mode=="qa":
bot_message=get_qa_chain(api_key=API_key,message=message,template=pp)
# print('Stop3')
elif select_mode=="chat_qa":
bot_message=get_chat_qa_chain(history,API_key,message,template=pp)
# print('Stop4')
chat_history.append((message, bot_message))
# print('Stop5')
return "", chat_history
msg.submit(select,[msg,chatbot],[msg,chatbot])
launch
demo.launch(share=True,debug=True)
演示
首先我们导入pdf和md文件,填入api,prompt我就用默认的了,split选择40
在none的情况下连接成功!
切换为chat_qa,可以看到由于split设置的不够,使用并没有prompt的知识
继续
让Gemini输出来源
结尾
一个月的学习,虽然ddl很多,但是结束了是真的一身轻松啊,而且这个月的学习中也从队友和助教还有群里的老哥们身上学到了很多,非常感谢他们的指点。在发现嵌入模型出现问题的时候,在队友和群友还有助教的帮助下才找到了问题的关键(虽然最后还是换了zhipu,Geogle你欠我的拿什么还!)
还有的就是,LLM和RAG真的很好玩啊,以后我有钱了,一定要买几片A100去布置一个自己的Model。