logo
7

文心大模型4.0结合Langchain构建多轮对话

文心大模型4.0开放API测试,我就马上动起来了。感觉这几个月百度在应用落地方面做出了极大的努力,出了百度旗下产品和平台基于LLM做了重构,API也在努力融入生态。在Langchain最新版已经有了百度千帆大模型平台的接口定义,更加令人兴奋的是居然在Langchain的Chat Models中发现了百度的Chat model: ErnieBotChat。于是,马上找了Langchain的例子实验起来。
今天我用ErnieBotChat中的文心大模型4.0(Ernie-Bot-4,或者称为competions_pro),结合langchain的LLMChain和ConversationBufferMemory来构建多轮对话(必须是有记忆的)。
由于这是开放者社区,看文章的估计都有比较好的基础了,我就直接上代码了。
  
  
  
  
  
  
import os
client_id = os.getenv("ernie_client_id")
client_secret = os.getenv("ernie_client_secret")
access_token= os.getenv("access_token")
  
  
  
  
  
  
chat = ErnieBotChat(model_name='ERNIE-Bot-4', ernie_client_id=client_id, ernie_client_secret=client_secret, access_token=access_token)
chat.predict("hi")
  
  
  
  
  
  
'Hello! How can I help you today?'
  
  
  
  
  
  
from langchain.chains import LLMChain
from langchain.memory import ConversationBufferMemory
from langchain.prompts import PromptTemplate
  
  
  
  
  
  
template = """You are a chatbot having a conversation with a human. Please answer as briefly as possible.
{chat_history}
Human: {human_input}
Chatbot:"""
prompt = PromptTemplate(
input_variables=["chat_history", "human_input"], template=template
)
memory = ConversationBufferMemory(memory_key="chat_history")
llm_chain = LLMChain(
llm=chat,
prompt=prompt,
verbose=True,
memory=memory,
)
llm_chain.predict(human_input="彩虹有几种颜色?前三种是哪些?")
  
  
  
  
  
  
> Entering new LLMChain chain...
Prompt after formatting:
You are a chatbot having a conversation with a human.
Human: 彩虹有几种颜色?前三种是哪些?
Chatbot:
> Finished chain.
'彩虹有七种颜色,前三种是红色、橙色和黄色。
  
  
  
  
  
  
llm_chain.predict(human_input="后四种呢?")
  
  
  
  
  
  
> Entering new LLMChain chain...
Prompt after formatting:
You are a chatbot having a conversation with a human.
Human: 彩虹有几种颜色?前三种是哪些?
AI: 彩虹有七种颜色,前三种是红色、橙色和黄色。
Human: 后四种呢?
Chatbot:
> Finished chain.
'后四种颜色是绿色、蓝色、靛蓝和紫色。'
从模型的回复看得出,模型对prompt的遵从度很高,回答真的是“as briefly as possible”。
评论
用户头像