logo
8

使用langchain的PromptTemplate和文心一言API打造一个翻译助手

1、准备工作

首先到百度千帆平台<https://cloud.baidu.com/>申请API Key 和 Secret Key。

2、安装第三方python库

  
  
  
  
  
  
pip install openai langchain langchain-wenxin
langchain-wenxin的github地址<https://github.com/ninehills/langchain-wenxin>

3、创建翻译助手

3.1、创建translate_helper.py文件,内容如下:

  
  
  
  
  
  
from langchain.prompts import (
ChatPromptTemplate,
HumanMessagePromptTemplate,
)
from langchain_wenxin import ChatWenxin
WENXIN_APP_Key = "APP KEY"
WENXIN_APP_SECRET = "APP SECRET"
def translate(input_text):
# 模板
template = """你是一个把英文翻译成中文的助手,请把下面input标签内的内容翻译成中文,如果内容只有一个单词或短语,请给出音标,中文和例句;如果内容是句子,请只给出中文。
<input>{text}</input>
翻译结果:
"""
# 使用template创建HumanMessagePromptTemplate,模板中含有一个text变量
human_message_prompt = HumanMessagePromptTemplate.from_template(template)
# 创建ChatPromptTemplate
chat_prompt = ChatPromptTemplate.from_messages([human_message_prompt])
# 使用传入的input_text参数对text进行赋值,创建messages
messages = chat_prompt.format_prompt(text=input_text).to_messages()
#print('input content: \n', messages[0].content)
chat_model = ChatWenxin(
temperature=0.9,
model="ernie-bot-turbo",
baidu_api_key = WENXIN_APP_Key,
baidu_secret_key = WENXIN_APP_SECRET,
verbose=True,
)
# 调用文心API
response = chat_model(
messages
)
# 返回结果
return response
if __name__ == "__main__":
input_text = input("请输入需要翻译的英文:")
# 无输入退出
while input_text:
response = translate(input_text)
print("翻译结果: \n", response.content)
input_text = input("请输入需要翻译的英文:")

3.2、运行

打开命令行输入python ./translate_helper.py,如果显示下面提示文字则运行成功。
请输入需要翻译的英文:

3.3、测试

输入单词prompt并回车
提示/prompt/pərˈspɔːm/
例句:老师给了我一个翻译提示,让我顺利完成了翻译任务。
输入短语go through并回车
通过,经过。音标为/'gəʊ tuː /,例句“They went through the customs at the airport.”
输入These days, workers of Heze Sanqing Food Co Ltd, a food processor based in Heze, East China's Shandong province, are busy unloading and loading unusually large amounts of goods. The firm produces 100,000 metric tons of canned fruits and vegetables per year, averaging about 274 tons a day.(来源<http://www.chinadaily.com.cn/a/202309/11/WS64fe4bc5a310d2dce4bb4f59.html>)并回车
这些天,位于中国山东省东部的菏泽三青食品有限公司(Heze Sanqing Food Co Ltd)的工人正忙着卸货和装货,他们搬运的货物数量异常巨大。该公司每年生产10万吨罐装水果和蔬菜,平均每天约274吨。

4、关于模板

在上面的模板中,我们使用标签<input>{text}</input>来告诉文心一言,标签中的内容是需要进行的翻译的。这种做法非常重要!非常重要!非常重要!当然我们也可以使用其他符号:
  • 三引号"""
  • 三反引号```
  • 三虚线---
  • 尖口号<>
  • XML标签<tag></tag>
注:使用这些符号的效果,对不同语言大模型需要经过测试验证。
同时,对输出也做了要求,如输入了单词,要求输出音标,中文和例句。

5、小结

通过上面的代码,我们打造了一个简单的翻译助手;你也可以根据自己的场景来对模板进行修改,来实现自己特定的功能。喜欢的小伙伴记得点赞!
评论
用户头像