gpt4 book ai didi

python - 如何向 RetrievalQA.from_chain_type 添加内存?或者,如何向 ConversationalRetrievalChain 添加自定义提示?

转载 作者:行者123 更新时间:2023-12-02 22:46:36 24 4
gpt4 key购买 nike

如何向 RetrievalQA.from_chain_type 添加内存?或者,如何向 ConversationalRetrievalChain 添加自定义提示?

在过去的两周里,我一直在尝试制作一个可以通过文档聊天的聊天机器人(因此不仅仅是语义搜索/质量保证,因此需要内存),而且还可以使用自定义提示。我已经尝试了所有链的每种组合,到目前为止,我得到的最接近的是 ConversationalRetrievalChain,但没有自定义提示,以及 RetrievalQA.from_chain_type 但没有内存

最佳答案

更新:这篇文章回答了OP问题的第一部分:

how do i add memory to RetrievalQA.from_chain_type?

第二部分请参见@andrew_reece's answer

or, how do I add a custom prompt to ConversationalRetrievalChain?

原文:

您是否尝试过传入chain_type_kwargs(底部是源代码的屏幕截图以供快速引用)?

文档并没有让你很容易理解底层的内容,但这里有一些可以实现你的目标的东西。

您可以在此处找到笔记本 GitHub Link设置

from langchain.chat_models import ChatOpenAI
from langchain.chains import RetrievalQA
from langchain.memory import ConversationBufferMemory
from langchain import PromptTemplate
from langchain.retrievers import TFIDFRetriever


retriever = TFIDFRetriever.from_texts(
["Our client, a gentleman named Jason, has a dog whose name is Dobby",
"Jason has a good friend called Emma",
"Emma has a cat whose name is Sullivan"])

然后定义您的自定义提示:

template = """
Use the following context (delimited by <ctx></ctx>) and the chat history (delimited by <hs></hs>) to answer the question:
------
<ctx>
{context}
</ctx>
------
<hs>
{history}
</hs>
------
{question}
Answer:
"""
prompt = PromptTemplate(
input_variables=["history", "context", "question"],
template=template,
)

记下您用于输入变量的内容,尤其是 'history''question',因为您在设置内存时需要匹配这些变量:

qa = RetrievalQA.from_chain_type(
llm=ChatOpenAI(),
chain_type='stuff',
retriever=retriever,
verbose=True,
chain_type_kwargs={
"verbose": True,
"prompt": prompt,
"memory": ConversationBufferMemory(
memory_key="history",
input_key="question"),
}
)

现在您可以调用 qa.run({"query": "who's the client'sfriend?"})

"The client's friend is Emma."

然后qa.run(“她的宠物的名字是?”)

"Emma's pet's name is Sullivan."

检查并验证内存/聊天历史记录:qa.combine_documents_chain.memory

ConversationBufferMemory(chat_memory=ChatMessageHistory(messages=[HumanMessage(content="who's the client's friend?", additional_kwargs={}), AIMessage(content="The client's friend is Emma.", additional_kwargs={}), HumanMessage(content="and her pet's name is?", additional_kwargs={}), AIMessage(content="Emma's pet's name is Sullivan.", additional_kwargs={})]), output_key=None, input_key='question', return_messages=False, human_prefix='Human', ai_prefix='AI', memory_key='history')enter image description here

enter image description here

关于python - 如何向 RetrievalQA.from_chain_type 添加内存?或者,如何向 ConversationalRetrievalChain 添加自定义提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76240871/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com