【LangChain系列 6】Prompt模版——自定义prompt模版

原文地址:【LangChain系列 6】Prompt模版——自定义prompt模版

本文速读:

  • 自定义prompt模版

LangChain提供了很多默认的prompt模版,同时LangChain提供了两种基础prompt模版:

  • 字符串prompt模版

  • 对话prompt模版

基于这两种模版,我们可以自定义prompt模版,自定义prompt模版有两个步骤是必不可少的:

  1. 要有input_variables属性,这是prompt模版对外暴露的接口,表示它需要接受输入在变量。

  2. 定义format方法,接受input_variables变量,然后返回一个格式化的prompt。

自定义prompt模版


下面将基于字符串prompt模版,定义一个prompt模版,实现的功能是:给定一个输入的函数名,然后输出该函数功能的prompt。

1. 创建一个函数:输入函数名字,返回函数源码

import inspect

def get_source_code(function_name):
    # Get the source code of the function
    return inspect.getsource(function_name)

2. 创建自定义prompt模版

from langchain.prompts import StringPromptTemplate
from pydantic import BaseModel, validator

PROMPT = """\
Given the function name and source code, generate an English language explanation of the function.
Function Name: {function_name}
Source Code:
{source_code}
Explanation:
"""


class FunctionExplainerPromptTemplate(StringPromptTemplate, BaseModel):
    """A custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function."""

    @validator("input_variables")
    def validate_input_variables(cls, v):
        """Validate that the input variables are correct."""
        if len(v) != 1 or "function_name" not in v:
            raise ValueError("function_name must be the only input_variable.")
        return v

    def format(self, **kwargs) -> str:
        # Get the source code of the function
        source_code = get_source_code(kwargs["function_name"])

        # Generate the prompt to be sent to the language model
        prompt = PROMPT.format(
            function_name=kwargs["function_name"].__name__, source_code=source_code
        )
        return prompt

    def _prompt_type(self):
        return "function-explainer"

3. 使用自定义prompt模版

fn_explainer = FunctionExplainerPromptTemplate(input_variables=["function_name"])

# Generate a prompt for the function "get_source_code"
prompt = fn_explainer.format(function_name=get_source_code)
print(prompt)

执行程序,输出如下:​​​​​​​

Given the function name and source code, generate an English language explanation of the function.
    Function Name: get_source_code
    Source Code:
    def get_source_code(function_name):
        # Get the source code of the function
        return inspect.getsource(function_name)
    
    Explanation:

本文小结

本文介绍了自定义prompt模版的两种方式:字符串prompt模版和对话prompt模版,并基于字符串prompt模版,实现了一个prompt模版:输入一个方法名,输出该方法功能的prompt。

 更多最新文章,请关注公众号:大白爱爬山

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值