LangChain —— Prompt Templates

2024-07-19 1559阅读

文章目录

  • 一、什么是 Prompt Templates
    • 1、String PromptTemplates
    • 2、ChatPromptTemplates
    • 3、MessagesPlaceholder 留言占位符
    • 二、如何使用 Prompt Templates
      • 1、使用几个简短示例
      • 2、在 chat model 中使用几个简短示例
      • 3、部分格式化提示模板
      • 4、一起编写提示

        一、什么是 Prompt Templates

         提示模板有助于将用户输入和参数转换为语言模型的指令。这可用于指导模型的响应,帮助它理解上下文并生成相关和连贯的基于语言的输出。

        LangChain —— Prompt Templates
        (图片来源网络,侵删)

         提示模板将字典作为输入,其中 每个键 表示提示模板中要填写的 变量

         提示模板输出提示 PromptValue 值。此 PromptValue 可以传递给 LLM 或 ChatModel,也可以转换为 字符串消息列表。此 PromptValue 存在的原因是便于在字符串和消息之间切换。

         有几种不同类型的提示模板:

        1、String PromptTemplates

         这种提示模板用于 格式化单个字符串,通常用于更简单的输入。例如,构造和使用PromptTemplate的常见方法如下:

        from langchain_core.prompts import PromptTemplate
        prompt_template = PromptTemplate.from_template("Tell me a joke about {topic}")
        prompt_template.invoke({"topic": "cats"})
        

        2、ChatPromptTemplates

         这些提示模板用于格式化消息列表。这些“模板”由模板本身的列表组成。例如,构造和使用ChatPromptTemplate的常见方法如下:

        from langchain_core.prompts import ChatPromptTemplate
        prompt_template = ChatPromptTemplate.from_messages([
            ("system", "You are a helpful assistant"),
            ("user", "Tell me a joke about {topic}")
        ])
        prompt_template.invoke({"topic": "cats"})
        

         在上面的示例中,此 ChatPromptTemplate 在调用时将构造两条消息。第一个是 SystemMessage,它没有要格式化的变量。第二个是 HumanMessage,将由用户传入的 topic 变量进行格式化。

        3、MessagesPlaceholder 留言占位符

         此提示模板负责在特定位置添加消息列表。

         在上面的 ChatPromptTemplate 中,我们看到了如何格式化两条消息,每条消息都是字符串。但是,如果我们想让用户传入一个消息列表,并且要把它们放在一个特定的位置呢?这就需要使用 MessagesPlaceholder 的方法。

        from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
        from langchain_core.messages import HumanMessage
        prompt_template = ChatPromptTemplate.from_messages([
            ("system", "You are a helpful assistant"),
            MessagesPlaceholder("msgs")
        ])
        prompt_template.invoke({"msgs": [HumanMessage(content="hi!")]})
        

         这将生成一个包含两条消息的列表,第一条是 SystemMessage,第二条是我们传入的 HumanMessage。如果我们传入了5条消息,那么它总共会产生6条消息 (系统消息加上传入的5条消息)。这对于将消息列表放入特定位置非常有用。

         在不显式使用 MessagesPalaceholder 类的情况下,完成相同任务的另一种方法是:

        prompt_template = ChatPromptTemplate.from_messages([
            ("system", "You are a helpful assistant"),
            ("placeholder", "{msgs}") # 
VPS购买请点击我

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

目录[+]