自定义提示词

from langchain.prompts import StringPromptTemplate
import inspect


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


# 自定义的模板class
class CustmPrompt(StringPromptTemplate):
    def format(self, **kwargs) -> str:
        # 获得源代码
        source_code = inspect.getsource(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=inspect.getsource)
print(pm)

序列化提示词

        1. yaml文件格式

_type: prompt
input_variables:
  ["name" ,"what" ]
template:
  给我讲一个关于{name}的{what}故事

        2. json文件格式

{
  "_type": "prompt",
  "input_variables": ["name","what"],
  "template": "给我讲一个关于{name}的{what}故事"
}

使用

from langchain.prompts import load_prompt

prompt=load_prompt("./file/prompt_template001.yaml")
pm=prompt.format(name="Alice",what="可爱的")
print(f"yaml prompt:{pm}")

prompt=load_prompt("./file/prompt_template002.json")
pmj=prompt.format(name="Alice",what="可爱的")
print(f"json prompt:{pmj}")

Logo

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。

更多推荐