【LangChain】Prompts之自定义提示模板

LangChain学习文档


概要

假设我们希望LLM生成给定函数名称的英语解释。为了实现此任务,我们将创建一个自定义提示模板,该模板将函数名称作为输入,并格式化提示模板以提供函数的源代码。

为什么需要自定义提示模板?

LangChain提供了一组默认的提示模板,可用于生成各种任务的提示。但是,在某些情况下,默认的提示模板可能无法满足我们的需求。例如,我们可能想要创建一个提示模板,其中包含适合我们的语言模型的特定动态指令。在这种情况下,您可以创建自定义提示模板。

此处查看当前的默认提示模板集。

创建自定义提示模板(Creating a Custom Prompt Template)

本质上有两种不同的提示模板可用 - 字符串提示模板聊天提示模板

一、字符串提示模板提供字符串格式的简单提示。

二、聊天提示模板生成更结构化的提示以与聊天 API 一起使用。

在本指南中,我们将使用字符串提示模板创建自定义提示。

要创建自定义字符串提示模板,有两个要求:

① 它有一个 input_variables 属性,该属性公开提示模板所需的输入变量。

② 它公开了一个格式方法,该方法接受与预期的 input_variables 相对应的关键字参数并返回格式化的提示。

我们将创建一个自定义提示模板,它将函数名称作为输入,并格式化提示以提供函数的源代码。为了实现这一点,我们首先创建一个函数,该函数将返回给定名称的函数的源代码。

python 复制代码
import inspect


def get_source_code(function_name):
    # 获取函数的源码
    return inspect.getsource(function_name)

接下来,我们将创建一个自定义提示模板,它将函数名称作为输入,并格式化提示模板以提供函数的源代码。

python 复制代码
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:
        # 获取函数的源码
        source_code = get_source_code(kwargs["function_name"])

        # 生成要发送到语言模型的提示
        # __name__是当前模块名
        prompt = PROMPT.format(
            function_name=kwargs["function_name"].__name__, source_code=source_code
        )
        return prompt

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

参考api:

使用自定义提示模板(Use the custom prompt template)

现在我们已经创建了自定义提示模板,我们可以使用它来为我们的任务生成提示。

python 复制代码
fn_explainer = FunctionExplainerPromptTemplate(input_variables=["function_name"])

# 生成函数"get_source_code"的提示
prompt = fn_explainer.format(function_name=get_source_code)
print(prompt)

结果:

python 复制代码
    给定函数名称和源代码,生成该函数的英语解释。
    函数名称: get_source_code
    源码:
    def get_source_code(function_name):
        # Get the source code of the function
        return inspect.getsource(function_name)
    
    Explanation:
    

总结

本文讲解的就是如何创建自定义提示:

  1. 先定义一个包含变量的字符串,变量用{},如:
python 复制代码
"""\
Given the function name and source code, generate an English language explanation of the function.
Function Name: {function_name}
Source Code:
{source_code}
Explanation:
"""
  1. 使用PROMPT.format(xxx)函数,进行格式化,如:
python 复制代码
prompt = PROMPT.format(
            function_name=kwargs["function_name"].__name__, source_code=source_code
        )

参考地址:

https://python.langchain.com/docs/modules/model_io/prompts/prompt_templates/custom_prompt_template

相关推荐
聚客AI35 分钟前
ChatGPT到Claude全适配:跨模型Prompt高级设计规范与迁移技巧
人工智能·机器学习·语言模型·自然语言处理·langchain·transformer·llama
后端研发Marion8 小时前
LangFlow技术深度解析:可视化编排LangChain应用的新范式 -(2)流编辑器系统
langchain·智能体·langflow
无心水1 天前
【程序员AI入门:模型】19.开源模型工程化全攻略:从选型部署到高效集成,LangChain与One-API双剑合璧
人工智能·langchain·开源·ai入门·程序员ai开发入门·程序员的 ai 开发第一课·程序员ai入门
lxsy2 天前
langchain 接入国内搜索api——百度AI搜索
langchain·百度ai搜索
明明跟你说过2 天前
掌握 LangChain 文档处理核心:Document Loaders 与 Text Splitters 全解析
人工智能·语言模型·自然语言处理·langchain
胡玉洋3 天前
从新手到高手:全面解析 AI 时代的「魔法咒语」——Prompt
人工智能·ai·prompt·transformer·协议
L_cl3 天前
【NLP 72、Prompt、Agent、MCP、function calling】
prompt
ZhangJiQun&MXP3 天前
Top-p采样:解锁语言模型的创意之门
人工智能·深度学习·机器学习·语言模型·自然语言处理·langchain·概率论
Lilith的AI学习日记3 天前
Claude官方63组提示词模板全解析:从工作到生活的AI应用指南
人工智能·prompt·生活·ai编程·claude
珊珊而川3 天前
ChatPromptTemplate创建方式比较
服务器·langchain