文章目录(Table of Contents)
简介
通过提示LLM或大型语言模型,现在可以比以往更快地开发 AI 应用程序,但是一个应用程序可能需要提示和多次并暂停作为输出。
在此过程有很多胶水代码需要编写,因此哈里森·蔡斯 (Harrison Chase) 创建了 LangChain
,整合了常见的抽象功能,使开发过程变得更加丝滑。
这里我们会介绍 LangChain
的使用,涉及到 Models
,Memory
,Chain
,Question
,Answer
和 Agent
等概念。如下图所示:
参考资料
Models, Prompt and Parsers
首先我们会来介绍 models
,prompt
和 parsers
:
model
:指作为基础的语言模型;prompt
(提示):是指创建输入,是用来给模型传递信息的方式;parsers
(解析器):接收模型的输出,并将输出结果解析为更加结构化的数据,方便后续操作;
使用 OpenAI 的简单例子
我们可以直接调用 OpenAI
的接口,例如下面的方式(注意使用前需要设置 OPENAI_API_KEY
):
- def get_completion(prompt, model="gpt-3.5-turbo"):
- messages = [{"role": "user", "content": prompt}]
- response = openai.ChatCompletion.create(
- model=model,
- messages=messages,
- temperature=0,
- )
- return response.choices[0].message["content"]
接着我们让他回答下面的一个问题:
- get_completion('Can you tell me what is 3 plus 8 step by step.')
会给出下面的答案,还是非常详细的:
- Sure! To find the sum of 3 and 8 step by step, you can follow these steps:
- 1. Start with the number 3.
- 2. Add 1 to 3, which gives you 4.
- 3. Add 1 to 4, which gives you 5.
- 4. Add 1 to 5, which gives you 6.
- 5. Add 1 to 6, which gives you 7.
- 6. Add 1 to 7, which gives you 8.
- 7. Add 1 to 8, which gives you 9.
- 8. Add 1 to 9, which gives you 10.
- 9. Add 1 to 10, which gives you 11.
- Therefore, 3 plus 8 equals 11.
使用 OpenAI 的复杂例子
接下来我们看一个稍微复杂一些的例子。我们希望使用 ChatGPT
将英文的方言转换为更加正式的表达方式。我们可以设定 styple
,和要转换的句子,最后构建 prompt
即可:
首先我们定义原始信息,和需要转换的风格:
- # 原始的信息
- customer_email = """
- Arrr, I be fuming that me blender lid \
- flew off and splattered me kitchen walls \
- 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!
- """
- # 美式英语 + 平静、尊敬的语调
- style = """American English \
- in a calm and respectful tone, at last translate to Simplified Chinese
- """
接着我们通过 f-string
来组成 prompt
,最后将 prompt
传入上面的 get_completion
获得回答即可:
- prompt = f"""Translate the text \
- that is delimited by triple backticks
- into a style that is {style}.
- text: ```{customer_email}```
- """
使用 LangChain 来回答问题
这里通常会将 temperature 设置为 0。
Memory
- 微信公众号
- 关注微信公众号
-
- QQ群
- 我们的QQ群号
-
评论