LangChain 的大语言模型的使用

王 茂南 2025年9月20日07:15:13
评论
1916字阅读6分23秒

简介

通过提示LLM或大型语言模型,现在可以比以往更快地开发 AI 应用程序,但是一个应用程序可能需要提示和多次并暂停作为输出。

在此过程有很多胶水代码需要编写,因此哈里森·蔡斯 (Harrison Chase) 创建了 LangChain,整合了常见的抽象功能,使开发过程变得更加丝滑。

这里我们会介绍 LangChain 的使用,涉及到 ModelsMemoryChainQuestionAnswerAgent 等概念。如下图所示:

参考资料

 

 

Models, Prompt and Parsers

首先我们会来介绍 modelspromptparsers

  • model:指作为基础的语言模型;
  • prompt(提示):是指创建输入,是用来给模型传递信息的方式;
  • parsers(解析器):接收模型的输出,并将输出结果解析为更加结构化的数据,方便后续操作;

 

使用 OpenAI 的简单例子

我们可以直接调用 OpenAI 的接口,例如下面的方式(注意使用前需要设置 OPENAI_API_KEY):

  1. def get_completion(prompt, model="gpt-3.5-turbo"):
  2.     messages = [{"role": "user", "content": prompt}]
  3.     response = openai.ChatCompletion.create(
  4.         model=model,
  5.         messages=messages,
  6.         temperature=0,
  7.     )
  8.     return response.choices[0].message["content"]

接着我们让他回答下面的一个问题:

  1. get_completion('Can you tell me what is 3 plus 8 step by step.')

会给出下面的答案,还是非常详细的:

  1. Sure! To find the sum of 3 and 8 step by step, you can follow these steps:
  2. 1. Start with the number 3.
  3. 2. Add 1 to 3, which gives you 4.
  4. 3. Add 1 to 4, which gives you 5.
  5. 4. Add 1 to 5, which gives you 6.
  6. 5. Add 1 to 6, which gives you 7.
  7. 6. Add 1 to 7, which gives you 8.
  8. 7. Add 1 to 8, which gives you 9.
  9. 8. Add 1 to 9, which gives you 10.
  10. 9. Add 1 to 10, which gives you 11.
  11. Therefore, 3 plus 8 equals 11.

 

使用 OpenAI 的复杂例子

接下来我们看一个稍微复杂一些的例子。我们希望使用 ChatGPT 将英文的方言转换为更加正式的表达方式。我们可以设定 styple,和要转换的句子,最后构建 prompt 即可:

首先我们定义原始信息,和需要转换的风格:

  1. # 原始的信息
  2. customer_email = """
  3. Arrr, I be fuming that me blender lid \
  4. flew off and splattered me kitchen walls \
  5. with smoothie! And to make matters worse,\
  6. the warranty don't cover the cost of \
  7. cleaning up me kitchen. I need yer help \
  8. right now, matey!
  9. """
  10. # 美式英语 + 平静、尊敬的语调
  11. style = """American English \
  12. in a calm and respectful tone, at last translate to Simplified Chinese
  13. """

接着我们通过 f-string 来组成 prompt,最后将 prompt 传入上面的 get_completion 获得回答即可:

  1. prompt = f"""Translate the text \
  2. that is delimited by triple backticks 
  3. into a style that is {style}.
  4. text: ```{customer_email}```
  5. """

 

使用 LangChain 来回答问题

 

这里通常会将 temperature 设置为 0。

 

 

Memory

  • 微信公众号
  • 关注微信公众号
  • weinxin
  • QQ群
  • 我们的QQ群号
  • weinxin
王 茂南
  • 本文由 发表于 2025年9月20日07:15:13
  • 转载请务必保留本文链接:https://mathpretty.com/16213.html
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: