LangChain中6大模块的使用逻辑

1.直接用LangChain配合LLM进行一问一答。直接查对应LLM的文档就行。

2.引入PromptTemplate,不仅可以定义一个规范的prompt,可以把prompt中的一些内容挖空,在后面再单独定义,起到解耦合的作用。不用PromptTemplate,直接在prompt字符串中挖空也是一样的,但在第三条中只能用PromptTemplate。

3.前面把prompt当作变量喂给LLM,可以使用chain,把prompt和LLM都当作变量喂给chain

4.如果有一些问题大模型不能解决,就需要用到tool。把tool装到agent里边,就可以让agent变成一个加强版的LLM,然后解决各种疑难杂症。

5.引入内存的概念,让LLM可以记得以前说过的内容,从而聊起天来。

既可以把prompt直接丢给LLM或者chain,也可以用模板,这时候PromptTemplate应该升级为更适合连续对话的chatPromptTemplate,SystemPromptTemplate升级为SystemMessagePromptTem-
plate
如果要让agent开启聊天功能,只需要更改agent=AgentType.***这个参数。

6.如果每聊一次天,就把之前的所有内容全部扫描一遍弄成一个字符串费时费力,可以用如下代码的方式进行优化。每次对话之后只记住新的内容。

from langchain.prompts import (
    ChatPromptTemplate, 
    MessagesPlaceholder, 
    SystemMessagePromptTemplate, 
    HumanMessagePromptTemplate
)
from langchain.chains import ConversationChain
from langchain.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferMemory
 
prompt = ChatPromptTemplate.from_messages([
    SystemMessagePromptTemplate.from_template("定义系统的角色"),
    MessagesPlaceholder(variable_name="history"),#固定写法
    HumanMessagePromptTemplate.from_template("{input}")
])
llm = ChatOpenAI(temperature=0)
# 初始化动态内存
memory = ConversationBufferMemory(return_messages=True)
# 将内存丢到chain中
conversation = ConversationChain(memory=memory, prompt=prompt, llm=llm)
# 跟AI进行对话
conversation.predict(input="Hi there!")
 
# AI回答:'Hello! How can I assist you today?'
conversation.predict(input="I'm doing well! Just having a conversation with an AI.")
 
# AI回答:"That sounds like fun! I'm happy to chat with you. Is there anything specific you'd like to talk about?"
conversation.predict(input="Tell me about yourself.")
 
# AI回答:"Sure! I am an AI language model created by OpenAI. I was trained on a large dataset of text from the internet, which allows me to understand and generate human-like language. I can answer questions, provide information, and even have conversations like this one. Is there anything else you'd like to know about me?"
  • 9
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值