PromptTemplate

#字符模板
from langchain.prompts import PromptTemplate

prompt = PromptTemplate.from_template("你是一个{name},帮我起1个具有{country}特色的{sex}名字")
prompt.format(name="算命大师",country="法国",sex="女孩")

ChatPromptTemplate

# 对话模板具有结构,chatmodels
from langchain.prompts import ChatPromptTemplate

chat_template = ChatPromptTemplate.from_messages(
    [
        ("system", "你是一个起名大师. 你的名字叫{name}."),
        ("human", "你好{name},你感觉如何?"),
        ("ai", "你好!我状态非常好!"),
        ("human", "你叫什么名字呢?"),
        ("ai", "你好!我叫{name}"),
        ("human", "{user_input}"),
    ]
)

chat_template.format_messages(name="陈大师", user_input="你的爸爸是谁呢?")

ChatPromptTemplate 也可以使用如下方式


from langchain.schema import SystemMessage
from langchain.schema import HumanMessage
from langchain.schema import AIMessage

# 直接创建消息,additional_kwargs是附加参数
sy = SystemMessage(
  content="你是一个起名大师",
  additional_kwargs={"大师姓名": "陈瞎子"}
)

hu = HumanMessage(
  content="请问大师叫什么?"
)
ai = AIMessage(
  content="我叫陈瞎子"
)
[sy,hu,ai]

ChatMessagePromptTemplate 可以 自定义角色


from langchain.prompts import AIMessagePromptTemplate
from langchain.prompts import SystemMessagePromptTemplate
from langchain.prompts import HumanMessagePromptTemplate
from langchain.prompts import ChatMessagePromptTemplate

prompt = "愿{subject}与你同在!"

chat_message_prompt = ChatMessagePromptTemplate.from_template(role="天行者",template=prompt)
chat_message_prompt.format(subject="原力")

自定义模板


##函数大师:根据函数名称,查找函数代码,并给出中文的代码说明

from langchain.prompts import StringPromptTemplate


# 定义一个简单的函数作为示例效果
def hello_world(abc):
    print("Hello, world!")
    return abc


PROMPT = """\
你是一个非常有经验和天赋的程序员,现在给你如下函数名称,你会按照如下格式,输出这段代码的名称、源代码、中文解释。
函数名称: {function_name}
源代码:
{source_code}
代码解释:
"""

import inspect


def get_source_code(function_name):
    #获得源代码
    return inspect.getsource(function_name)

#自定义的模板class
class CustmPrompt(StringPromptTemplate):

    
    def format(self, **kwargs) -> str:
        # 获得源代码
        source_code = get_source_code(kwargs["function_name"])

        # 生成提示词模板
        prompt = PROMPT.format(
            function_name=kwargs["function_name"].__name__, source_code=source_code
        )
        return prompt

a = CustmPrompt(input_variables=["function_name"])
pm = a.format(function_name=hello_world)

print(pm)

#和LLM连接起来
from langchain.llms import OpenAI
import os
api_base = os.getenv("OPENAI_PROXY")
api_key = os.getenv("OPENAI_API_KEY")

llm = OpenAI(
    model="gpt-3.5-turbo-instruct",
    temperature=0,
    openai_api_key=api_key,
    openai_api_base=api_base
    )
msg = llm.predict(pm)
print(msg)

使用jinji2与f-string来实现提示词模板格式化


##f-string是python内置的一种模板引擎
from langchain.prompts import PromptTemplate

fstring_template = """
给我讲一个关于{name}的{what}故事
"""

prompt = PromptTemplate.from_template(fstring_template)

prompt.format(name="翠花", what="悲伤")


##Jinja2是一个灵活、高效的Python模板引擎,可以方便地生成各种标记格式的文档。
from langchain.prompts import PromptTemplate

jinja2_template = "给我讲一个关于的故事"
prompt = PromptTemplate.from_template(jinja2_template, template_format="jinja2")

prompt.format(name="狗剩", what="高兴")

组合式提示词模板

from langchain.prompts.pipeline import PipelinePromptTemplate
from langchain.prompts.prompt import PromptTemplate
# Final Prompt由一系列变量构成
full_template = """{Character}
{behavior}
{prohibit}"""
full_prompt = PromptTemplate.from_template(full_template)

#第一层性格设计
Character_template = """你是{person},你有着{xingge}."""
Character_prompt = PromptTemplate.from_template(Character_template)
#第二层行为设计
behavior_template = """你遵从以下的行为:
{behavior_list}
"""
behavior_prompt = PromptTemplate.from_template(behavior_template)
#第三层不允许的行为
prohibit_template = """你不允许有以下行为:
{prohibit_list}
"""
prohibit_prompt = PromptTemplate.from_template(prohibit_template)
#将三层提示词组合起来
input_prompts = [
    ("Character", Character_prompt),
    ("behavior", behavior_prompt),
    ("prohibit", prohibit_prompt)
]
pipeline_prompt = PipelinePromptTemplate(final_prompt=full_prompt, pipeline_prompts=input_prompts)
#打印参数
pipeline_prompt.input_variables
#调用组合后的提示词模板
pm = pipeline_prompt.format(
    person="埃隆马斯克",
    xingge="钢铁般的意志,你是世界首富,精通物理、天文、商业,你是商业奇才,你的终极梦想是殖民火星.",
    behavior_list="1.你喜欢冒险 \n 2.你非常崇拜爱因斯坦 \n 3.你总是乐于助人,回答用户各种问题.",
    prohibit_list="1.你不可以说自己是一个人工智能助手或者机器人 \n 2.当你不知道答案的时候,可以说让我再想想. "
)
print(pm)

你是埃隆马斯克,你有着钢铁般的意志,你是世界首富,精通物理、天文、商业,你是商业奇才,你的终极梦想是殖民火星.. 你遵从以下的行为: 1.你喜欢冒险 2.你非常崇拜爱因斯坦 3.你总是乐于助人,回答用户各种问题.

你不允许有以下行为: 1.你不可以说自己是一个人工智能助手或者机器人 2.当你不知道答案的时候,可以说让我再想想.

序列化模板,可以使用模板文件 1,便于共享 2,便于版本管理 3,便于存储 4,支持常见格式 yml,txt,json

_type: prompt
input_variables:
    ["name","what"]
template:
    给我讲一个关于{name}的{what}故事
#加载yaml格式的prompt模版
prompt = load_prompt("simple_prompt.yaml")
print(prompt.format(name="小黑",what="恐怖的"))
from langchain.prompts import load_prompt
#加载yaml格式的prompt模版
prompt = load_prompt("simple_prompt.yaml")
print(prompt.format(name="小黑",what="恐怖的"))

也可以对输出格式化使用模板

{
    "input_variables": [
        "question",
        "student_answer"
    ],
    "output_parser": {
        "regex": "(.*?)\\nScore: (.*)",
        "output_keys": [
            "answer",
            "score"
        ],
        "default_output_key": null,
        "_type": "regex_parser"
    },
    "partial_variables": {},
    "template": "Given the following question and student answer, provide a correct answer and score the student answer.\nQuestion: {question}\nStudent Answer: {student_answer}\nCorrect Answer:",
    "template_format": "f-string",
    "validate_template": true,
    "_type": "prompt"
}
#支持加载文件格式的模版,并且对prompt的最终解析结果进行自定义格式化
prompt = load_prompt("prompt_with_output_parser.json")
prompt.output_parser.parse(
    "George Washington was born in 1732 and died in 1799.\nScore: 1/2"
)
Prev post

LangChain 002

Next post

LangChain 004