通义千问:基于LangChain的LLM应用开发1——prompt template 提示词模板
参考文档
通义千问版:基于LangChain的LLM应用开发2——模型、提示和输出解析
DeepLearning.AI国外吴恩达视频网站
源码:
———
环境配置
配置通义千问大模型环境:
阿里云官网很详细。通义千问模型服务灵积
b站参考视频:20240705_am_python通过OpenAI库,调用千问大模型,并进行反复询问等功能加强
参考如上,建议使用系统变量,防止API_KEY显示在代码中。
小插曲·:若pycharm找不到系统变量,重启pycharm!
调用尝试
作者使用jupyter notebook
from openai import OpenAI
import os
client = OpenAI(
api_key=os.getenv("DASHSCOPE_API_KEY"), # 如果您没有配置环境变量,请在此处用您的API Key进行替换
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # 填写DashScope服务的base_url
)
def get_response(prompt,model = "qwen-turbo"):
messages=[{'role': 'user', 'content': prompt}]
response = client.chat.completions.create(
model=model,
messages = messages,
temperature=0.0,
)
return response.choices[0].message.content
get_response("1+1=?")
输出如下即为成功调用大模型:
接下来进入主题:
LangChain的提示词模板
#创建qwen对象
from langchain_community.llms import Tongyi
chat = Tongyi(temperature = 0.0)
模板字符串变量,用style风格翻译三个引号中的text
template_string = """Translate the text \
that is delimited by triple backticks \
into a style that is {style}. \
text:```{text}```
"""#模板字符串
获取提示词模板
from langchain.prompts import ChatPromptTemplate
#获取模板
prompt_template = ChatPromptTemplate.from_template(template_string)
#输出模板
prompt_template.messages[0].prompt
通过from_template()方法,可知创建的模板输入为两个,分别是:style和text。
接下来分别给出style和text:
#这里引用顾客和商家的场景
customer_style = """American English \
in a calm and respectful tone
"""
#这里的顾客的英语口吻是海盗的风格,期望通过模型将其变得平静,受尊重的
customer_email = """
Arrr,I be fuming that me blender lid \
flew off and splattered me kitchen wall \
with smoothie! And to make matters worse,\
the warranty don't cover the cost of \
cleaning up me kitchen. I need yer help \
right now,matey!"""
将输入和提示词格式化在一起
customer_messages = prompt_template.format_messages(style = customer_style,text = customer_email)
#打印输出,查看其内容及类型
print(type(customer_messages))
print(type(customer_messages[0]))
print(customer_messages[0])
由于模型近期望接收str类型,因此仅将customer_messages[0].content作为输入:
customer_response = chat.invoke(customer_messages[0].content)
customer_response
通过上述内容即完成了prompt模板的设定及qwen模型的调用,已设定好的模板可在后续代码中多次重复使用,这点类似c++的模板类。
接下来是商家客服的回复,作为prompt模板的重复使用示例。
声明商家的回复内容及风格变量,用模型改写
#这里期望通过模型将商家的说话风格变得像有礼貌的海盗一样
service_reply = """Hey there customer, \
the warranty does not cover \
cleaning expenses ror your kitchen \
because it's your fault that \
you misused your blender \
by forgetting to put the lid on before \
starting the blender. \
Tough luck! see ya!
"""
service_style_pirate = """\
a polite tone \
that speak in English Pirate"""
将提示词和模型输入整合后,输入给模型,打印模型输出
service_messages = prompt_template.format_messages(style = service_style_pirate,text = service_reply)
service_response = chat.invoke(service_messages[0].content)
print(service_response
个人学习整理,刚刚接触大模型,学习Langchain途中做一定的学习记录,由于7月9日开始OPENAI国内被禁,且各大视频教程主流为使用openai接口录制,因此以通义千问模型为基础学习Langchain有一定的学习价值,文中代码主要来自吴恩达的基于LangChain的LLM应用开发。