大型语言模型(LLM)正在成为一种具有转型性的技术,使开发人员能够构建以往无法实现的应用程序。然而,仅仅使用这些独立的LLM通常不足以创建一个真正强大的应用程序——真正的力量在于将它们与其他计算或知识来源相结合。
langchain旨在帮助开发这类应用程序。以下介绍如何用langchain做翻译机器人。
重要概念:
LLM & Prompt:
这包括提示管理、提示优化、为所有LLM提供通用接口以及用于与LLM一起使用的常用实用工具。
chain:
链式调用超出了单个LLM的调用范围,它涉及到一系列的调用(无论是调用LLM还是其他实用工具)。LangChain为链式调用提供了标准接口,与其他工具进行了大量的集成,并为常见应用提供了端到端的链式调用。
用法:(python)
pip install langchain
参数化prompt template。用到 (AIMessage, HumanMessage, SystemMessage)和 ChatOpenAI
from langchain.schema import AIMessage, HumanMessage, SystemMessage
from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
AIMessagePromptTemplate,
HumanMessagePromptTemplate,
)
from langchain.chains import LLMChain
from langchain.chat_models import ChatOpenAI
Message类用于服务ChatGPT不同的角色prompt, ChatOpenAI用于处理对话API。
先构造参数化的system prompt:
templatePoem = (
"""You are a translation expert, proficient in various languages.
Please translate the article or text in the style of William Shakespeare.
Translates everything into {to_lan}."""
)
system_prompt_poem = SystemMessagePromptTemplate.from_template(templatePoem)
其中 "{to_lan}" 是system prompt的参数模板,用于输入用于翻译的目标语言。
user prompt是全量翻译,暂不需要使用特别模板:
human_message_prompt = HumanMessagePromptTemplate.from_template("{text}")
其中"{text}"为模板本身也是参数。
至此,system prompt, user prompt的参数设置完成。
继续定义langchain的模板,使用上述两个prompt template定义用于Chat的template:
chat_prompt_template_poem = ChatPromptTemplate.from_messages(
[system_prompt_poem, human_message_prompt]
)
Chat template包含了 system prompt 对象和 human prompt对象,用于对话模型。langchain在调用OpenAI对话接口时,会使用chat_prompt_template_poem构造相应的JSON结构,发送去OpenAI接口。
接下来定义模型和LLMChain:
#Create model
translation_model = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0)
#Create Chain
translation_chain_luxun = LLMChain(llm=translation_model, prompt=chat_prompt_template_luxun)
模型,ChatOpenAI,是langchain中用来调用chat/completion接口的类,因此默认定义使用gpt-3.5-turbo,及设置温度为0,以降低模型生成时的创意。
LLMChain是langchain中重要的对象,用于链式调用多种功能,此例子使用LLMChain调用模型进行翻译并获取结果。
接下来调用run 方法并按模板参数名称构造JSON数据,传递给run方法:
# Text to be translated.
text = """A password change has been requested for your account. If this was you, please use the link below to reset your password."""
##Poem Result
chain_result_poem = translation_chain_poem.run({'to_lan':'Chinese',
'text': text})
入参是 {to_lan} 和 {text},run方法的JSON参数则提供这两个参数名称入相应的值。langchain核心功能会在调用LLMChain的run方法时,用参数格式化模板,并构造 chat/completion接品需要的message参数。
#Python类型参数
[
SystemMessage(content='You are a translation expert, proficient in various languages. \n Please translate the article or text in the style of LuXun.\n And keep clean and concise, as less words as you can.\n Translates everything into Chinese.', additional_kwargs={}),
HumanMessage(content='A password change has been requested for your account. If this was you, please use the link below to reset your password.', additional_kwargs={}, example=False)
]
#JSON化后的messages数组:
[
{
"role":"system",
"content":"You are a translation expert, proficient in various languages. \n Please translate the article or text in the style of LuXun.\n And keep clean and concise, as less words as you can.\n Translates everything into Chinese."
},
{
"role":"user",
"content":"A password change has been requested for your account. If this was you, please use the link below to reset your password."
}
]
得到的翻译结果会直接返回,并存入 chain_result_poem 变量中。
##Poem style
print(f'Shakespeare: \n {chain_result_poem}')
#Shakespeare:
# 一個密碼更改的請求已經被提出,關於你的帳戶。若此為汝所為,請使用下方之連結重設汝的密碼。
如有大量文本,需要重复调用翻译可以包装成方法,以多次调用:
to_lan = 'Chinese'
text = [ 'To continue setting up your OpenAI account, please verify that this is your email address.',
'A password change has been requested for your account. If this was you, please use the link below to reset your password.',
'If you have a specific article or text that you would like to have translated, please provide it, and I\'ll be glad to help you with the translation.'
]
## only reuse translation_chain_poem
global_to_lan = 'English'
def get_splited_text():
return text
def translateTo(to_lan, texts = []):
global global_to_lan
global_to_lan = to_lan
results = [translation_chain_poem.run({'to_lan':global_to_lan, 'text':item}) for item in texts ]
return results
translated = translateTo('中文', get_splited_text())
print( '\n'.join(translated))
#result:
#為了繼續設置您的OpenAI帳戶,請驗證這是否為您的電子郵件地址。
#汝之账户已有人请求更改密码。若此为汝所为,请使用下方链接重设汝之密码。
#若有特定之文章或文本,欲求翻譯者翻譯,請提供該文本,吾將樂意協助翻譯。
完成后,就可以用这个LLMChain去扩展其它功能了。 以上是这周在极客时间,AI 大模型应用开发实战营的课程内容。谢谢阅读。
375



被折叠的 条评论
为什么被折叠?



