自定义提示模板
假设我们希望 LLM 能根据函数名称生成该函数的英文解释。为完成这一任务,我们将创建一个自定义提示模板,将函数名称作为输入,并格式化提示模板,以提供函数的源代码。
为什么需要自定义提示模板?
LangChain 提供了一组默认提示模板,可用于为各种任务生成提示。但是,在某些情况下,默认提示模板可能无法满足您的需求。例如,您可能希望为自己的语言模型创建一个带有特定动态指令的提示模板。在这种情况下,您可以创建自定义提示模板。
在此查看当前的默认提示模板集。
创建自定义提示模板
基本上有两种不同的提示模板--字符串提示模板和聊天提示模板。字符串提示模板提供了字符串格式的简单提示,而聊天提示模板则生成了更有条理的提示,可与聊天 API 配合使用。
在本指南中,我们将使用字符串提示模板创建自定义提示。
要创建自定义字符串提示模板,有两个要求:
它有一个 input_variables 属性,用于公开提示模板期望使用的输入变量。
它有一个 format 方法,该方法接收与预期输入变量相对应的关键字参数,并返回格式化后的提示信息。
我们将创建一个自定义提示模板,将函数名称作为输入,并格式化提示,以提供函数的源代码。为此,我们首先创建一个函数,该函数将返回函数名的源代码。
import inspect
def get_source_code(function_name):
# Get the source code of the function
return inspect.getsource(function_name)
接下来,我们将创建一个自定义提示模板,将函数名称作为输入,并格式化提示模板,以提供函数的源代码。
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"
使用自定义提示模板
现在我们已经创建了自定义提示模板,可以用它来为我们的任务生成提示。
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:
Comments
Post a Comment