Maojui

LangChain | Python

2023-03-21

讓 LLM 記住之前聊天內容

使用 API 時,LLM 可不會記得你們的對話內容,

1
2
3
4
5
6
7
8
9
10
11
from langchain.chat_models import ChatOpenAI
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory # 全部記起來

llm = ChatOpenAI(temperature=0.0)
memory = ConversationBufferMemory()
conversation = ConversationChain(
llm=llm,
memory = memory,
verbose=True
)

Memory

  • ConversationBufferMemory
    • 全部記起來 memory = ConversationBufferMemory()
1
2
3
4
5
6
7
8
9
10
11
class ConversationBufferMemory(
*,
lc_kwargs: Dict[str, Any] = dict,
chat_memory: BaseChatMessageHistory = ChatMessageHistory,
output_key: str | None = None,
input_key: str | None = None,
return_messages: bool = False,
human_prefix: str = "Human",
ai_prefix: str = "AI",
memory_key: str = "history"
)
  • ConversationBufferWindowMemory
    • 記住 k 次對話 memory = ConversationBufferWindowMemory(k=1)
  • ConversationTokenBufferMemory
  • ConversationSummaryMemory