admin 管理员组

文章数量: 1184232

初始化模型

from langchain.schema import SystemMessage, HumanMessage
from langchain_openai import ChatOpenAI
langchain_key = 'lsv2_pt_067c82bxxxxxxxxxxxxxxxxxxa29b6ee_c2934a750d'
import os
os.environ['LANGCHAIN_TRACING_V2'] = 'true'
os.environ['LANGCHAIN_API_KEY'] = langchain_key
os.environ['LANGCHAIN_ENDPOINT'] = 'https://api.smith.langchain'
os.environ['LANGCHAIN_PROJECT'] = 'pr-upbeat-electrocardiogram-64'
zhipu_key = 'a66dbe67exxxxxxxxxxxxxxx1317c.66qWpHQ9tC83zWJo'
# 创建模型
model = ChatOpenAI(
    temperature=0.01,
    model="glm-4-flash",
    openai_api_key=zhipu_key,
    openai_api_base="https://open.bigmodel/api/paas/v4/"
)

ConversationChain初始化(memory默认ConversationBufferMemory)

# ConversationChain对话链
from langchain import OpenAI
from langchain.chains import ConversationChain
from langchain.chains.conversation.memory import ConversationBufferMemory

conversation = ConversationChain(llm=model)
# 提示词
conversation.prompt.template

‘The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n\nCurrent conversation:\n{history}\nHuman: {input}\nAI:’
中文翻译
以下是人类和人工智能之间的友好对话。人工智能很健谈,并从其上下文中提供了许多具体细节。如果人工智能不知道问题的答案,它会如实地说它不知道。\n\n当前对话:\n{历史记录}human:{输入}\nAI:

conversation('你好我是小黑黑')

{‘input’: ‘你好我是小黑黑’,
‘history’: ‘’,
‘response’: ‘你好,小黑黑!很高兴认识你。我是人工智能助手,随时准备回答你的问题或者进行有趣的对话。有什么我可以帮你的吗?’}

conversation('请问我叫什么')

{‘input’: ‘请问我叫什么’,
‘history’: ‘Human: 你好我是小黑黑\nAI: 你好,小黑黑!很高兴认识你。我是人工智能助手,随时准备回答你的问题或者进行有趣的对话。有什么我可以帮你的吗?’,
‘response’: ‘你好,小黑黑!你之前已经告诉我你的名字了,你叫“小黑黑”。如果你有其他问题或者需要帮助,随时告诉我哦!’}

memery的几种类型

ConversationBufferMemory(同上)

‌ConversationBufferMemory ‌是 LangChain 中的一个核心模块,主要用于管理和存储对话历史记录。它按原样存储整个对话历史记录,无需任何更改,使其成为聊天机器人和其他需要准确上下文的应用程序的有用工具‌

# ConversationChain对话链
from langchain import OpenAI
from langchain.chains import ConversationChain
from langchain.chains.conversation.memory import ConversationBufferMemory
conversation_buf = ConversationChain(llm=model, memory=ConversationBufferMemory())
# 查看模版
print(conversation_buf.prompt.template)

The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.

Current conversation:
{history}
Human: {input}
AI:

conversation_buf('你好,我是小黑黑')

{‘input’: ‘你好,我是小黑黑’,
‘history’: ‘’,
‘response’: ‘你好,小黑黑!很高兴认识你。我是人工智能助手,很高兴和你聊天。请问有什么我可以帮你的吗?比如,你想了解什么信息,或者有什么问题需要解答?’}

conversation_buf.run('我是一个性格开朗的人,我准备去认识新朋友,你能帮我写一段开场白嘛')

‘当然可以,小黑黑!以下是一段适合用来认识新朋友的开场白:\n\n—\n\n嗨,你好!我是小黑黑,一个性格开朗、热爱生活的人。今天很高兴在这里遇见你。我总是对新鲜事物充满好奇,所以如果你愿意分享一些有趣的事情或者推荐一些好去处,我会非常感激。我觉得人与人之间的交流总是能带来意想不到的乐趣,不知道你有没有什么特别的爱好或者故事想要和我分享呢?\n\n—\n\n希望这段开场白能帮助你顺利开启新友谊的大门!’

# 记录每次交互的token数
from langchain.callbacks import get_openai_callback
def count_tokens(chain, query):
    with get_openai_callback() as cb:
        result = chain.run(query)
        print('花费的总token数为:', cb.total_tokens)
count_tokens(conversation_buf, '很好,谢谢')

花费的总token数为: 610

conversation_buf.memory.buffer

‘Human: 你好,我是小黑黑\nAI: 你好,小黑黑!很高兴认识你。我是人工智能助手,很高兴和你聊天。请问有什么我可以帮你的吗?比如,你想了解什么信息,或者有什么问题需要解答?\nHuman: 我是一个性格开朗的人,我准备去认识新朋友,你能帮我写一段开场白嘛\nAI: 当然可以,小黑黑!以下是一段适合用来认识新朋友的开场白:\n\n—\n\n嗨,你好!我是小黑黑,一个性格开朗、热爱生活的人。今天很高兴在这里遇见你。我总是对新鲜事物充满好奇,所以如果你愿意分享一些有趣的事情或者推荐一些好去处,我会非常感激。我觉得人与人之间的交流总是能带来意想不到的乐趣,不知道你有没有什么特别的爱好或者故事想要和我分享呢?\n\n—\n\n希望这段开场白能帮助你顺利开启新友谊的大门!\nHuman: 请生成多一些\nAI: 当然可以,小黑黑!这里还有几段不同风格的开场白,你可以根据场合和你的个性选择使用:\n\n—\n\n1. 嗨,我是小黑黑,一个乐观向上的家伙。听说这里聚集了很多有趣的人,所以我迫不及待想要认识你。你平时喜欢做些什么?有没有什么特别推荐的活动或者地方?\n\n2. 你好呀!我是小黑黑,一个喜欢探索世界的小冒险家。今天能在这里遇见你真是太好了。我总是对别人的故事很感兴趣,所以如果你愿意,我们可以聊聊你的生活经历,或者你最近有什么新鲜事儿吗?\n\n3. 嘿,我是小黑黑,一个热爱生活的阳光少年。很高兴在这里遇见你!我总是对新鲜事物充满好奇,所以如果你有什么好玩的点子或者有趣的想法,我超级期待听听看。你呢,有什么特别想分享的吗?\n\n4. 你好,我是小黑黑,一个喜欢与人交流的开心果。今天能在这里遇见你真是太幸运了。我总是相信,每一次的相遇都是缘分。你有没有什么特别的爱好,或者有什么故事想和我分享?\n\n5. 嗨,我是小黑黑,一个充满活力、热爱挑战的人。很高兴在这里认识你!如果你愿意,我们可以一起探索这个世界的美好。你有没有什么特别想去的地方或者想尝试的事情?\n\n希望这些建议能帮助你更好地开启新友谊的大门!\nHuman: 很好,谢谢\nAI: 不客气,小黑黑!很高兴能帮到你。记住,真诚和开放的态度是结识新朋友的关键。如果你在认识新朋友的过程中有任何其他问题或者需要更多建议,随时可以找我聊天。祝你在认识新朋友的过程中收获满满,期待听到你的新故事!再见啦!🌟’

ConversationSummaryMemory

ConversationSummaryMemory ‌主要用于对整个对话的内容进行总结和记忆,它通过总结对话内容,帮助大语言模型(LLM)记住历史对话信息,从而在后续对话中保持上下文的连贯性和一致性‌

from langchain.chains.conversation.memory import ConversationSummaryMemory
conversation_sum = ConversationChain(llm=model, memory=ConversationSummaryMemory(llm=model))
# 记忆存储的提示工程
conversation.memory.prompt.template

‘Progressively summarize the lines of conversation provided, adding onto the previous summary returning a new summary.\n\nEXAMPLE\nCurrent summary:\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good.\n\nNew lines of conversation:\nHuman: Why do you think artificial intelligence is a force for good?\nAI: Because artificial intelligence will help humans reach their full potential.\n\nNew summary:\nThe human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential.\nEND OF EXAMPLE\n\nCurrent summary:\n{summary}\n\nNew lines of conversation:\n{new_lines}\n\nNew summary:’
中文翻译
逐步总结所提供的对话内容,在之前的总结中添加新的总结。

示例
当前摘要:
人类询问人工智能对人工智能的看法。人工智能认为人工智能是一股向善的力量。

新的对话:
人类:为什么你认为人工智能是一股向善的力量?\美国国家航空航天局:因为人工智能将帮助人类充分发挥其潜力。

新总结:
人类问人工智能对人工智能的看法。人工智能认为人工智能是一股向善的力量,因为它将帮助人类充分发挥潜力。
示例结束

当前摘要:
{summary}

新的对话行:
{new_lines}

新摘要:

count_tokens(conversation_sum, '你好,我叫小黑黑,我长得很黑')

花费的总token数为: 390

count_tokens(conversation_sum, '我准备去相亲,请帮我撰写自我介绍')

花费的总token数为: 957

conversation_sum

## 记忆摘要
conversation_sum.memory.buffer

‘The human introduces themselves as 小黑黑 and discusses their dark complexion, which the AI acknowledges as having cultural significance. The AI suggests writing a self-introduction for a blind date, emphasizing the importance of sharing personal details, education, hobbies, values, and personality traits. The AI provides a sample self-introduction and wishes the human success in their blind date.’
中文翻译
人类自我介绍为小黑黑 并讨论了他们的深色皮肤,人工智能承认这具有文化意义。人工智能建议为相亲写一篇自我介绍,强调分享个人信息、教育、爱好、价值观和性格特征的重要性。人工智能提供了一个自我介绍的示例,并祝愿人类在相亲中取得成功。

ConversationBufferWindowMemory

ConversationBufferWindowMemory通过设置一个窗口大小(通常由参数k指定),窗口内保存最近的k次对话记录。每当新的对话发生时,窗口会向前滑动,丢弃最旧的记录,同时将新的对话记录添加到窗口中。这样,模型始终只保留最近的对话历史,避免了存储所有对话记录的负担‌

# ConversationBufferWindowMemory的功能与我们之前的 缓冲记忆 ConversationBufferMemory 相同,但是在记忆中添加了一个 窗口 Window 。这意味着在 “忘记” 之前,我们只保留给定数量的过去交互。

from langchain.chains.conversation.memory import ConversationBufferWindowMemory

conversation_bufw = ConversationChain(
    llm = model,
    memory = ConversationBufferWindowMemory(k=1)
)
conversation_bufw.prompt.template

‘The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.\n\nCurrent conversation:\n{history}\nHuman: {input}\nAI:’
中文翻译
“以下是人类和人工智能之间的友好对话。人工智能很健谈,并从其上下文中提供了许多具体细节。如果人工智能不知道问题的答案,它会如实地说它不知道。\n\n当前对话:\n{历史记录}\n联系人:{输入}\nAI:’

count_tokens(
    conversation_bufw, 
    "嗨喽,我叫小黑黑"
)
count_tokens(
    conversation_bufw, 
    "我今年27了,长得比较黑,所以没对象,请给我一个好的穿搭建议,为了让我找对象"
)
count_tokens(
    conversation_bufw, 
    "我的裤子时候穿什么颜色的"
)
# 并没有识别到小黑黑的名字
conversation_bufw


(并没有识别到小黑的姓名,因为窗口并没有包含第一轮对话)

本文标签: 记忆 langchain ConversationChain LLM