langchain prompt

111 阅读2分钟

langchain prompt结构有四部分组成:

  1. instructions 用于额外的提示,如确定对话场景,明确身份等,一般都是固定的
  2. context 上下文,是额外的知识,一般用于存放数据库查询到的知识
  3. prompter input 我们传统概念上的prompt
  4. output indicator 用于标记输出的开始。

langchain提供了两种提示词:string和chat,并基于此提供了提示模版 prompt template chatprompt template fewshotprompt template pipeline prompt

基础使用string template和chat template

最基础的template有以下步骤:

from langchain.template import PromptTemplate

template = "a f string{name}"
# 这种方法直接从字符串模板中创建提示词
template = PromptTemplate.from_template(template = template)

template.format(name = "")
复制代码

直接调用PromptTemplate和PromptTemplate.from_template的区别: 前者是该累的构造函数,分别传入input variable和template,后者自动获取variable 对于chat场景,有以下方法

from langchain.prompts import (
    ChatPromptTemplate,
    SystemMessagePromptTemplate,
    HumanMessagePromptTemplate,
)

template = "f string{string}"
system_message_prompt = SystemMessagePromptTemplate.from_template(template = template)

human_template = "f string{string}"
human_message_prompt = HumanMessagePromptTemplate.from_template(template = template)

# message_template -> message_prompt -> template -> prompt, etc..

prompt_template = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) # 如果是string template,那么就直接format了,但是这里是chat template,所以要先from_messages

prompt = prompt_template.format_prompt(string = "", string = "").to_messages() # format prompt 而不是直接format

import os

from langchain_openai import ChatOpenAI

chat = ChatOpenAI(
    model = os.environ.get("LLM_MODELEND"),
)

result = chat.invoke(prompt)
复制代码

fewshot Prompt-给模型以示例

few-shot,zeroshot等概念略 在代码中,一个“shot”就是一个字典,字典包含信息

# 1. 创建一些示例
samples = [
  {
    "flower_type": "玫瑰",
    "occasion": "爱情",
    "ad_copy": "玫瑰,浪漫的象征,是你向心爱的人表达爱意的最佳选择。"
  },
  {
    "flower_type": "康乃馨",
    "occasion": "母亲节",
    "ad_copy": "康乃馨代表着母爱的纯洁与伟大,是母亲节赠送给母亲的完美礼物。"
  },
  {
    "flower_type": "百合",
    "occasion": "庆祝",
    "ad_copy": "百合象征着纯洁与高雅,是你庆祝特殊时刻的理想选择。"
  },
  {
    "flower_type": "向日葵",
    "occasion": "鼓励",
    "ad_copy": "向日葵象征着坚韧和乐观,是你鼓励亲朋好友的最好方式。"
  }
]

复制代码

创建prompt_template对象

from langchain.prompts.prompt import PromptTemplate

template = "鲜花类型: {flower_type}\n场合: {occasion}\n文案: {ad_copy}"
prompt_sample = PromptTemplate(
    input_variables = ["flower_name", "occasion", "ad"],
    template = template) # 本质上是一个可以接受输入的字符串
# format, format_prompt的区别是什么?直接调用PromptTemplate和PromptTemplate.format的区别是什么?
print(prompt.format(**samples[0]))

from langchain.prompts.few_shot import FewShotPromptTemplate

prompt = FewShotPromptTemplate(
    examples = samples,
    example_prompt = prompt_sample,
    suffix = "鲜花类型: {flower_type}\n场合: {occasion}", # suffix有什么用?
    input_variables = ["flower_type", "occasion"],
)

import os

from langchain_openai import ChatOpenAI

chat = ChatOpenAI(
    model = os.environ.get("LLM_MODELEND"),
)

results = chat.invoke(prompt.format(flower_type = "野玫瑰", occasion = "狂野"))

print(results)
# content='文案:野玫瑰,充满野性的美丽,是你释放内心狂野、展现独特魅力的绝佳象征。' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 23, 'prompt_tokens': 145, 'total_tokens': 168}, 'model_name': 'Doubao-pro-32k', 'system_fingerprint': '', 'finish_reason': 'stop', 'logprobs': None} id='run-59f2b2e3-3814-41bc-807a-3f3c20491f7c-0' usage_metadata={'input_tokens': 145, 'output_tokens': 23, 'total_tokens': 168}