基于 Python 的自然语言处理系列(69):RAG-prompt

1. LangChain 简介

        LangChain 是一个用于开发基于语言模型(LM)的应用程序的框架。它支持创建以下类型的应用:

  1. 上下文感知(Context-aware):连接语言模型(LM)到上下文数据源(如提示指令、少样本示例、相关内容等)。

  2. 推理能力(Reasoning):依靠 LM 进行推理(根据提供的上下文决定如何回答、采取何种行动等)。

1.1 典型应用场景

  1. 文档问答(如法律、医学领域)

  2. 聊天机器人(如市场营销、HR 招聘)

  3. 结构化数据分析(如 SQL 查询、报告文档分析)

        LangChain 主要包含以下三个核心组件:

  1. LLM(大语言模型):作为核心推理引擎,理解和使用不同类型的 LM 是使用 LangChain 的基础。

  2. Prompt Templates(提示模板):为 LM 提供指令,决定模型的输出。

  3. Output Parsers(输出解析器):将 LLM 的原始响应转换为可用格式,方便后续使用。

2. 提示(Prompt)

        提示(Prompt)是用户提供给语言模型的输入或指令,帮助其理解上下文并生成相关的语言输出。LangChain 提供了一些用于构建和处理提示的类和函数。

2.1 提示模板(Prompt Template)

        提示模板是一种预定义的提示生成配方,包含 指令少样本示例特定上下文 以及 适用于特定任务的问题

from langchain.prompts import PromptTemplate

prompt_template = PromptTemplate(
    input_variables=["adjective", "content"],
    template="Tell me a {adjective} joke about {content}.",
)

print(prompt_template.format(adjective="funny", content="chickens"))

        或者使用 from_template 方法(不需要显式定义 input_variables):

prompt_template = PromptTemplate.from_template(
    template="Tell me a {adjective} joke about {content}.",
)

print(prompt_template.format(adjective="funny", content="chickens"))

2.2 ChatPromptTemplate

        聊天提示(ChatPromptTemplate)由一系列聊天消息组成,每条消息都有一个 role(角色)。

        在 OpenAI Chat API 中,常见的角色包括:

  • SystemMessage:系统消息

  • AIMessage:AI 生成的消息

  • HumanMessage:用户输入的消息

  • FunctionMessage:函数调用生成的消息

示例:

from langchain.prompts import ChatPromptTemplate
from langchain.schema.messages import SystemMessage, HumanMessagePromptTemplate

chat_template = ChatPromptTemplate.from_messages(
    [
        SystemMessage(content="""
        You serve as the teacher assistant to Chaky, who instructs an NLP course.
        Your primary responsibility is to assist students in successfully completing the NLP course.
        """),
        HumanMessagePromptTemplate.from_template("{text}"),
    ]
)

messages = chat_template.format_messages(text="How to get an A if I fail every quiz?")
print(messages)

3. 附录

        本篇博文介绍了 LangChain 的基本概念,以及如何使用提示模板(Prompt Templates)和聊天提示模板(ChatPromptTemplate)构建 NLP 应用。在接下来的文章中,我们将继续深入探讨 LangChain 其他核心模块的使用方法。

如果你觉得这篇博文对你有帮助,请点赞、收藏、关注我,并且可以打赏支持我!

欢迎关注我的后续博文,我将分享更多关于人工智能、自然语言处理和计算机视觉的精彩内容。

谢谢大家的支持!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

会飞的Anthony

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值