LangChain:1. Prompt基本使用

AI助手已提取文章相关产品:

1. Prompt基本使用

from langchain_core.prompts import PromptTemplate
from langchain_core.prompts import ChatPromptTemplate

这里有两种prompt,其对应两种形式:PromptTemplate 和 ChatPromptTemplate

从某种意义来说,前者是一个通用形式,后者是在chat领域的一个特殊表达。

from langchain_core.prompts import PromptTemplate
prompt_template = PromptTemplate.from_template(
    "Tell me a {adjective} joke about {content}."
)
prompt_template.format(adjective="funny", content="chickens")
# 'Tell me a funny joke about chickens.'

PromptTemplate做的操作很简单,相当于把 f'Tell me a {adjective} joke about {content}.' 从变量带入字符串中分离开了,Template都可以使用format函数转化为字符串,但是这里要注意的是,参数是变量了并不是字典。

ChatPromptTemplate相当于在PromptTemplate做了一个对话的快捷方式,一般来说对话是这样的:

System: You are a helpful AI bot. Your name is Bob.
Human: Hello, how are you doing?
AI: I'm doing well, thanks!
Human: What is your name?

但是ChatPromptTemplate将其分解得具体了,其有两种表达形式,一种使用列表,一种使用更具体的ChatMessagePromptTemplate,AIMessagePromptTemplate,HumanMessagePromptTemplate

#  使用列表
from langchain_core.prompts import ChatPromptTemplate
chat_template = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a helpful AI bot. Your name is {name}."),
        ("human", "Hello, how are you doing?"),
        ("ai", "I'm doing well, thanks!"),
        ("human", "{user_input}"),
    ]
)
# 转化为字符串
messages = chat_template.format(name="Bob", user_input="What is your name?")
# 转化为列表 可以具体看看是 SystemMessage HumanMessage AIMessage 还是其他的 Message
messages = chat_template.format_messages(name="Bob", user_input="What is your name?")
# 使用细分的方式
from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, AIMessagePromptTemplate, HumanMessagePromptTemplate
c1 = SystemMessagePromptTemplate.from_template("You are a helpful AI bot. Your name is {name}.")
c2 = HumanMessagePromptTemplate.from_template("You are a helpful AI bot. Your name is {name}.")
c3 = AIMessagePromptTemplate.from_template("You are a helpful AI bot. Your name is {name}.")
c4 = HumanMessagePromptTemplate.from_template("You are a helpful AI bot. Your name is {name}.")
chat_template = ChatPromptTemplate.from_messages([c1, c2, c3, c4])
# 效果如上
messages = chat_template.format(name="Bob", user_input="What is your name?")
messages = chat_template.format_messages(name="Bob", user_input="What is your name?")

在这里要注意的是,使用列表的话元组前面一个字符串只能是 one of 'human', 'user', 'ai', 'assistant', or 'system'.,不然会报错。其中还有一个ChatMessagePromptTemplate,其from_template参数中还有一个role参数,可以自定义对话实体,不需要必须满足'human', 'user', 'ai', 'assistant', or 'system'其中的一个。

在定义好template之后,就可以搭配模型使用chain了

from langchain_community.llms import Ollama
from langchain_core.prompts import ChatPromptTemplate
llm = Ollama(model='llama3', temperature=0.0)
chat_template = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a helpful AI bot. Your name is {name}."),
        ("human", "Hello, how are you doing?"),
        ("ai", "I'm doing well, thanks!"),
        ("human", "{user_input}"),
    ]
)
chain = chat_template | llm
chain.invoke({'name': 'Bob', 'user_input': 'What is your name?'})
# "Nice to meet you! My name is Bob, and I'm here to help answer any questions or provide assistance you may need. How can I help you today?"

2. 进阶Prompt

2.1 MessagesPlaceholder

MessagesPlaceholder: 当暂时不确定使用什么角色需要占位时

from langchain_core.prompts import ChatPromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholder
from langchain_core.messages import AIMessage, HumanMessage # 这里与AIMessagePromptTemplate的区别在与前者是不能使用input_variables的
human_prompt = "Summarize our conversation so far in {word_count} words."  
human_message_template = HumanMessagePromptTemplate.from_template(human_prompt)  
# 在这里使用MessagesPlaceholder进行占位
chat_prompt = ChatPromptTemplate.from_messages(  
[MessagesPlaceholder(variable_name="conversation"), human_message_template]  
)
# 在这里添加,添加参数为占位时设置的variable_name
human_message = HumanMessage(content="What is the best way to learn programming?")
ai_message = AIMessage(
    content="""1.Choose a programming language: Decide on a programming language that you want to learn. 2. Start with the basics: Familiarize yourself with the basic programming concepts such as variables, data types and control structures. 3. Practice, practice, practice: The best way to learn programming is through hands-on experience"""
)
# 这里的 word_count 对应 chat_prompt 中的 input_variables
chat_prompt.format_prompt(
    conversation=[human_message, ai_message], word_count="10"
).to_messages()

利用示例让LLM模仿输出进而获得一个更好的效果在prompt工程中很常见,但是大量的实例会造成一个问题,那就是模型的输入长度是由限制的,大量的实例可能会导致在input_variables输入时出现长度过长模型无法输入的问题。这里就需要引入selectors

2.2 selectors

selectors:通过对示例进行选择的方式来减少示例,进而减少文本长度。要注意的是使用selectors后并不会立刻就删除示例,示例是在FewShotPromptTemplate中被删除的。

from langchain_core.prompts import PromptTemplate
examples = [
    {"input": "happy", "output": "sad"},
    {"input": "tall", "output": "short"},
    {"input": "energetic", "output": "lethargic"},
    {"input": "sunny", "output": "gloomy"},
    {"input": "windy", "output": "calm"},
]
example_prompt = PromptTemplate(
    input_variables=["input", "output"],
    template="Input: {input}\nOutput: {output}",
)
# 要注意的是format_prompt是不可以使用列表的,只能一个参数参数输入
example_prompt.format_prompt(**examples[0])
2.2.1 LengthBasedExampleSelector

LengthBasedExampleSelector: 根据文本长度来选择

from langchain_core.example_selectors import LengthBasedExampleSelector
from langchain_core.prompts import FewShotPromptTemplate
# 定义example_selector
example_selector = LengthBasedExampleSelector(
    examples=examples,
    example_prompt=example_prompt,
    # 这里max_length是针对 one example 的
    max_length=25,
    # get_text_length 是用来计算 example_prompt 的长度的
    # get_text_length: Callable[[str], int] = lambda x: len(re.split("\n| ", x))
)
FewShotPromptTemplate(
    example_selector=example_selector,
    example_prompt=example_prompt,
    prefix="Give the antonym of every input",
    suffix="Input: {adjective}\nOutput:",
    # 这里的input_variables与suffix中的adjective对应
    input_variables=["adjective"],
)
2.2.2 NGramOverlapExampleSelector

NGramOverlapExampleSelector: 根据 ngram 重叠分数,根据与输入最相似的示例 NGramOverlapExampleSelector 来选择和排序示例。ngram 重叠分数是介于 0.0 和 1.0 之间的浮点数,包括 0.0(含)。ngram 重叠分数小于或等于阈值的示例被排除在外。默认情况下,阈值设置为 -1.0,因此不会排除任何示例,只会对它们重新排序。将阈值设置为 0.0 将排除与输入没有 ngram 重叠的示例。

from langchain_community.example_selector.ngram_overlap import NGramOverlapExampleSelector
example_selector = NGramOverlapExampleSelector(  
examples=examples,  
example_prompt=example_prompt,  
# threshold 阈值默认设置为 -1.0
threshold=-1.0,  
# 阈值小于 0.0:选择器按 ngram 重叠分数对示例进行排序,不排除任何示例。 
# 阈值大于 1.0: Selector 排除所有示例,返回一个空列表。 
# 阈值等于 0.0: 选择器按 ngram 重叠分数对示例进行排序, 并排除那些与输入没有 ngram 重叠的词。
)  
dynamic_prompt = FewShotPromptTemplate(  
# We provide an ExampleSelector instead of examples.  
example_selector=example_selector,  
example_prompt=example_prompt,  
prefix="Give the Spanish translation of every input",  
suffix="Input: {sentence}\nOutput:",  
input_variables=["sentence"],  
)
2.2.3 SemanticSimilarityExampleSelector

SemanticSimilarityExampleSelector:此对象根据与输入的相似性选择示例。它通过查找具有与输入具有最大余弦相似度的嵌入的示例来实现此目的。

from langchain_chroma import Chroma  
from langchain_core.example_selectors import SemanticSimilarityExampleSelector  
from langchain_core.prompts import FewShotPromptTemplate  
from langchain_openai import OpenAIEmbeddings
example_selector = SemanticSimilarityExampleSelector.from_examples(  
examples,  
# 使用 embedding 层来判断文本相似性 
OpenAIEmbeddings(),  
# Chroma用于生成嵌入的嵌入类,用于度量语义相似度。
Chroma,  
# k表示要生成的示例数量
k=1, 
)  
similar_prompt = FewShotPromptTemplate(  
example_selector=example_selector,  
example_prompt=example_prompt,  
prefix="Give the antonym of every input",  
suffix="Input: {adjective}\nOutput:",  
input_variables=["adjective"],  
)
2.2.4 MaxMarginalRelevanceExampleSelector

MaxMarginalRelevanceExampleSelector:与输入最相似的示例组合来选择示例,同时还针对多样性进行了优化。为此,它找到具有与输入具有最大余弦相似度的嵌入的示例,然后迭代添加它们,同时惩罚它们与已选定示例的接近程度。

example_selector = MaxMarginalRelevanceExampleSelector.from_examples(  
examples,  
OpenAIEmbeddings(),  
# FAISS 和 Chroma 一样用于生成嵌入的嵌入类,用于度量语义相似度。 
FAISS,  
k=2,  
)
mmr_prompt = FewShotPromptTemplate(  
# We provide an ExampleSelector instead of examples.  
example_selector=example_selector,  
example_prompt=example_prompt,  
prefix="Give the antonym of every input",  
suffix="Input: {adjective}\nOutput:",  
input_variables=["adjective"],  
)

如何系统的去学习大模型LLM ?

作为一名热心肠的互联网老兵,我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在人工智能学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。

但苦于知识传播途径有限,很多互联网行业朋友无法获得正确的资料得到学习提升,故此将并将重要的 AI大模型资料 包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来

😝有需要的小伙伴,可以V扫描下方二维码免费领取🆓

在这里插入图片描述

一、全套AGI大模型学习路线

AI大模型时代的学习之旅:从基础到前沿,掌握人工智能的核心技能!

img

二、640套AI大模型报告合集

这套包含640份报告的合集,涵盖了AI大模型的理论研究、技术实现、行业应用等多个方面。无论您是科研人员、工程师,还是对AI大模型感兴趣的爱好者,这套报告合集都将为您提供宝贵的信息和启示。

img

三、AI大模型经典PDF籍

随着人工智能技术的飞速发展,AI大模型已经成为了当今科技领域的一大热点。这些大型预训练模型,如GPT-3、BERT、XLNet等,以其强大的语言理解和生成能力,正在改变我们对人工智能的认识。 那以下这些PDF籍就是非常不错的学习资源。

img

在这里插入图片描述

四、AI大模型商业化落地方案

img

阶段1:AI大模型时代的基础理解

  • 目标:了解AI大模型的基本概念、发展历程和核心原理。
  • 内容
    • L1.1 人工智能简述与大模型起源
    • L1.2 大模型与通用人工智能
    • L1.3 GPT模型的发展历程
    • L1.4 模型工程
      - L1.4.1 知识大模型
      - L1.4.2 生产大模型
      - L1.4.3 模型工程方法论
      - L1.4.4 模型工程实践
    • L1.5 GPT应用案例

阶段2:AI大模型API应用开发工程

  • 目标:掌握AI大模型API的使用和开发,以及相关的编程技能。
  • 内容
    • L2.1 API接口
      - L2.1.1 OpenAI API接口
      - L2.1.2 Python接口接入
      - L2.1.3 BOT工具类框架
      - L2.1.4 代码示例
    • L2.2 Prompt框架
      - L2.2.1 什么是Prompt
      - L2.2.2 Prompt框架应用现状
      - L2.2.3 基于GPTAS的Prompt框架
      - L2.2.4 Prompt框架与Thought
      - L2.2.5 Prompt框架与提示词
    • L2.3 流水线工程
      - L2.3.1 流水线工程的概念
      - L2.3.2 流水线工程的优点
      - L2.3.3 流水线工程的应用
    • L2.4 总结与展望

阶段3:AI大模型应用架构实践

  • 目标:深入理解AI大模型的应用架构,并能够进行私有化部署。
  • 内容
    • L3.1 Agent模型框架
      - L3.1.1 Agent模型框架的设计理念
      - L3.1.2 Agent模型框架的核心组件
      - L3.1.3 Agent模型框架的实现细节
    • L3.2 MetaGPT
      - L3.2.1 MetaGPT的基本概念
      - L3.2.2 MetaGPT的工作原理
      - L3.2.3 MetaGPT的应用场景
    • L3.3 ChatGLM
      - L3.3.1 ChatGLM的特点
      - L3.3.2 ChatGLM的开发环境
      - L3.3.3 ChatGLM的使用示例
    • L3.4 LLAMA
      - L3.4.1 LLAMA的特点
      - L3.4.2 LLAMA的开发环境
      - L3.4.3 LLAMA的使用示例
    • L3.5 其他大模型介绍

阶段4:AI大模型私有化部署

  • 目标:掌握多种AI大模型的私有化部署,包括多模态和特定领域模型。
  • 内容
    • L4.1 模型私有化部署概述
    • L4.2 模型私有化部署的关键技术
    • L4.3 模型私有化部署的实施步骤
    • L4.4 模型私有化部署的应用场景

学习计划:

  • 阶段1:1-2个月,建立AI大模型的基础知识体系。
  • 阶段2:2-3个月,专注于API应用开发能力的提升。
  • 阶段3:3-4个月,深入实践AI大模型的应用架构和私有化部署。
  • 阶段4:4-5个月,专注于高级模型的应用和部署。
这份完整版的大模型 LLM 学习资料已经上传优快云,朋友们如果需要可以微信扫描下方优快云官方认证二维码免费领取【保证100%免费

😝有需要的小伙伴,可以Vx扫描下方二维码免费领取🆓

在这里插入图片描述

您可能感兴趣的与本文相关内容

`ChatPromptTemplate` 是 LangChain 中的一个重要组件,主要用于定义和管理聊天机器人与用户交互时所需的提示模板 (prompt)。它使得开发者能够更方便地构建动态、结构化的提示信息,从而更好地引导语言模型生成合适的响应。 ### `ChatPromptTemplate` 的核心功能 1. **变量替换**: - 可以在模板中插入占位符,这些占位符将在实际运行时被具体的值所替代。比如 `{username}` 或者 `{query}` 等,这有助于个性化每个用户的体验。 2. **条件逻辑**: - 支持根据上下文环境的不同选择性地包含或排除某些部分的内容,增加了灵活性。 3. **多轮对话支持**: - 允许记录之前的对话历史,并据此调整当前回合的提问方式或是提供的背景资料,实现连贯自然的交流过程。 4. **模块化设计**: - 将复杂的提示分解成若干个小片段,便于维护更新同时也简化了调试流程。 5. **预设配置项**: - 提供了一些常用的默认设置选项,如系统消息、角色说明等,帮助快速搭建基础版本的应用场景。 通过合理运用 `ChatPromptTemplate` ,我们可以显著提升人机对话的质量,使其更加贴近真实的人际沟通模式。 ### 示例代码 ```python from langchain.prompts import ChatPromptTemplate # 定义一个简单的聊天提示模板 template = ChatPromptTemplate.from_messages([ ("system", "你是客服助手"), ("human", "{user_message}"), ("ai", "很高兴为您服务! {response}") ]) formatted_prompt = template.format(user_message="你好,我想了解产品详情") print(formatted_prompt) ``` 上述例子展示了如何创建一个基本的 `ChatPromptTemplate` 并填充具体的消息内容,最终形成完整的提示字符串传递给 AI 模型进行处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值