Jean's Blog

一个专注软件测试开发技术的个人博客

0%

LangChain组件PromptTemple

提示词:大模型工作的核心部件

大模型中提示词的工作原理及组成部分,包括提示词模板、大模型处理和输出解析器三部分,通过模板将变量填入固定结构生成提示词,输入大模型后得到自然语言回答,并由输出解析器转换为结构化数据,便于后续应用处理。

image-20250829153036422

  • 大模型整体工作流程的三大组件:提示词模板、语言模型、输出解析器
  • 提示词模板的作用是将可变部分抽象为变量,固定不易变化的部分,实现复用和管理
  • 语言模型组件接收提示词模板生成的完整提示词,并返回自然语言响应
  • 输出解析器将自然语言响应转换为结构化数据(如JSON),便于后续程序处理

prompts模板:大模型推理的关键

提示词撰写的重要性及技巧,指出不会提问会导致大模型回答质量低下,强调好的提示词应包含角色设定、背景信息、目标和约束条件等要素,并提到提示词模板在应用开发中的关键作用。

  • 不会写提示词的人 — 仅提供一句话提问,缺乏上下文和约束条件
    • 例子:我想去海南玩,请你帮我做一份旅行攻略
  • 会写提示词的人 — 好的提示词应包括角色设定、背景信息、目标需求和回答要求
    • 例子:假如你是导游,我要到海南玩,预算一万元,跟行人数三个人,行程7天,请帮我做一份旅行攻略。请注意:我不喜欢行程太紧凑,我不喜欢网红景点,更喜欢有文化底蕴的景点,另外,推荐景点请附上各个景点的价格。

优秀的提示词(非推理型):

【立角色】:引导AI进入具体场景,赋予其行家身份

【述问题】:告诉AI你的困惑和问题,以及背景信息

【定目标】:告诉AI你的需求,希望达成的目标

【补要求】:告诉AI回答时注意什么,或者如何回复

提示词模板的好处:

  1. 将提示词提炼成模板
  2. 实现提示词复用、版本管理、动态变化等

PromptTemplate(字符串提示模板)

适用场景

  • 用于文本补全模型,输入是纯文本(单字符串)。
  • 适用于简单的任务,例如生成一段文本、回答问题或执行指令。

特点

  • 输入变量插值:通过 {} 占位符动态替换变量。
  • 模板格式:支持 f-string
  • 输出形式:生成一个完整的字符串作为模型输入。

  • 字符串模版 - PromptTemplate(LLMs,偏向于文本处理,不太能处理输出结构化数据)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    from langchain_core.prompts import PromptTemplate

    # 创建提示词模版
    # 方式一
    prompt_ = PromptTemplate(
    input_variables=['name', 'county', 'sex'],
    template="""
    # 角色定位
    你是一个{name},帮我起一个具有{county}特色的{sex}名字
    """
    )
    # 方式二
    prompt = PromptTemplate.from_template(
    "你是一个{name},帮我起一个具有{county}特色的{sex}名字"
    )
    # 模版 + 变量 = 提示词
    prompts = prompt.format(name="算命大师",county="日本", sex="男孩子")
    print(prompts)

ChatPromptTemple(聊天提示模板)

适用场景

  • 用于聊天模型(如 ChatGPT / 通义千问等),输入是多轮对话的消息列表(SystemMessageHumanMessageAIMessage 等)。
  • 适用于需要模拟多轮对话或角色扮演的场景。

特点

  • 多消息类型支持:可以组合系统指令、用户输入和助手回复。
  • 消息格式化:生成结构化的消息列表,供聊天模型处理。
  • 灵活性:支持动态替换变量(如 SystemMessage 中的占位符)。

  • 对话模版 - ChatPromptTemple(ChatLLMs,主流)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    from langchain_core.prompts import ChatPromptTemplate

    chat_template = ChatPromptTemplate.from_messages(
    [
    ("system", "你是一个起名大师,你的名字叫{name}"),
    ("human", "你好{name},你感觉如何?"),
    ("ai", "我感觉还不错,谢谢"),
    ("human", "你叫什么名字?"),
    ("ai", "你好,我叫{name}"),
    ("human", "{user_input}"),
    ]
    )
    chats = chat_template.format_messages(name="算命大师",user_input="你好我是谁呢?")
    print(chats)
  • 消息占位符

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
    from langchain_core.messages import HumanMessage

    prompt_template = ChatPromptTemplate([
    ("system", "你是一个厉害的人工智能助手"),
    MessagesPlaceholder("messages"), # 相当插入了一个叫messages的变量,用于占了个位置
    # ("placeholder", "{messages}"), # 与MessagesPlaceholder("messages")等效写法
    ])
    result = prompt_template.invoke({"messages": [HumanMessage("你好")]})
    print(result)
  • 使用Message组合模版

    • HumanMessage:代表用户的消息
    • AIMessage:代表模型输出的消息
    • SystemMessage:代表系统消息
    • FunctionMessage:表示函数调用的结果,该参数为被调用的函数的名称
    • ToolMessage:表示工具调用的结果,与FunctionMessage不同,是为了匹配OpenAI的function和tool消息类型
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    from langchain_core.messages import SystemMessage, HumanMessage, AIMessage

    sy = SystemMessage(
    content="你是一名起名大师",
    additional_kwargs={"大师姓名": "陈瞎子"}
    )
    hu = HumanMessage(
    content="请问大师叫什么"
    )
    ai = AIMessage(
    content="我叫陈瞎子"
    )
    messages = [sy, hu, ai]
    print(messages)
  • 自定义提示词模版(不常用)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    import os
    from dotenv import load_dotenv
    import inspect

    from langchain_openai import OpenAI
    from langchain.prompts import StringPromptTemplate

    # 加载 .env 文件中的环境变量
    load_dotenv()

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

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

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

    class CustomPromptTemplate(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 = CustomPromptTemplate(input_variables=["function_name"])
    res = a.format(function_name=hello_word)
    print("格式化之后的提示词为==============>")
    print(res)

    api_base = os.getenv("OPENAI_API_BASE")
    api_key = os.getenv("OPENAI_API_KEY")

    llm = OpenAI(
    # model_name="gpt-3.5-turbo",
    temperature=0.2,
    base_url=api_base,
    api_key=api_key,
    )
    print("结合LLM输出的结果==============>")
    msg = llm.invoke(res)
    print(msg)

ChatMessagePromptTemplate

ChatMessagePromptTemplate可以结合 ChatPromptTemplate使用,同时对提示词模板和消息体进行抽象和复用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from langchain_core.prompts import ChatPromptTemplate, ChatMessagePromptTemplate

system_template = ChatMessagePromptTemplate.from_template(
template="你是一位{role}专家,擅长回答{domain}领域的问题。",
role="system",
)

human_template = ChatMessagePromptTemplate.from_template(
template="用户问题:{question}",
role="human",
)

chat_prompt = ChatPromptTemplate.from_messages([
system_template,
human_template,
])

messages = chat_prompt.format_messages(
role="技术",
domain="Web开发",
question="如何构建一个基于Vue的前端应用?"
)

print(messages)

FewShotPromptTemplate(少样本提示模板)

FueShot(少量示例)提示词技巧,通过举例子帮助大模型快速理解新任务,结合代码演示在lunchin中如何使用Few Shot提升回答准确性,强调示例质量与任务相关性的重要性。

FueShout的核心思想是给模型提供示例,模仿输出完成新任务

image-20250829163851831

适用场景

  • 用于少样本学习(Few-Shot Learning),在提示中包含示例(Examples),帮助模型理解任务。
  • 适用于复杂任务(如翻译、分类、推理),需要通过示例引导模型行为。

特点

  • 示例嵌入:通过 examples 参数提供示例输入和输出。
  • 动态示例选择:支持 ExampleSelector 动态选择最相关的示例。
  • 模板格式:通常包含前缀(Prefix)、示例(Examples)和后缀(Suffix)。

ZeroShot(零示例)

会导致低质量回答,代码示例如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI

# 加载 .env 文件中的环境变量
load_dotenv()

api_base = os.getenv("OPENAI_API_BASE")
api_key = os.getenv("OPENAI_API_KEY")

model = ChatOpenAI(
temperature=0.2,
base_url=api_base,
api_key=api_key,
)

res = model.invoke("What is 2 🐦 9?")
print(res)

FewShot(少量示例)

代码示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
# 增加提示词
from langchain_core.prompts import ChatPromptTemplate, FewShotChatMessagePromptTemplate

# 加载 .env 文件中的环境变量
load_dotenv()

api_base = os.getenv("OPENAI_API_BASE")
api_key = os.getenv("OPENAI_API_KEY")

model = ChatOpenAI(
temperature=0.2,
base_url=api_base,
api_key=api_key,
)

# 增加示例组
examples = [
{"input": "2 🐦 2", "output": "4"},
{"input": "2 🐦 3", "output": "5"}
]
# 构造提示词模板
example_prompt = ChatPromptTemplate.from_messages([
("human", "{input}"),
("ai", "{output}"),
])
# 组合示例与提示词
few_shot_prompt = FewShotChatMessagePromptTemplate(
# 提示词模板
example_prompt=example_prompt,
# 示例组
examples=examples,
)
# 打印提示词模板
print("组合之后的提示词为=====================》")
print(few_shot_prompt.invoke({}).to_messages())
# 构造最终提示词
final_prompt = ChatPromptTemplate.from_messages([
("system", "你是一位神奇的数学奇才."),
few_shot_prompt,
("human", "{input}")
])
# 重新提问
chain = final_prompt | model
result = chain.invoke({"input": "what is 2 🐦 9?"})
print("重新提问结果为=====================》")
print(result)

比较实际的一个场景:输入Bug文本 —> 输出Bug类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate

examples = [
{"input": "点击登录按钮无反应", "output": "功能缺失"},
{"input": "加载页面卡顿超过10秒", "output": "性能问题"}
]

example_prompt = PromptTemplate(
input_variables=["input", "output"],
template="Bug描述:{input}\nBug类型:{output}"
)

few_shot_prompt = FewShotPromptTemplate(
# 样本
examples=examples,
# 样板格式
example_prompt=example_prompt,
# 提示词最前的一句话
prefix="请根据以下示例判断Bug类型:",
# 提示词最后面的一句话
suffix="Bug描述:{user_input}\nBug类型:",
# 用户输入的变量
input_variables=["user_input"]
)

print(few_shot_prompt.format(user_input="用户头像无法上传"))

MessagesPlaceholder(插入对话历史)

可将历史对话的信息插入到一个多轮朵花中

1
2
3
4
5
6
7
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

chat_template = ChatPromptTemplate.from_messages([
("system", "你是一个 AI 测试助手"),
MessagesPlaceholder(variable_name="history"),
("human", "{input}")
])

示例选择器

动态示例是指根据任务需求动态选择合适的提示词示例,以适应模型上下文窗口限制并提高相关性。与静态示例不同,动态示例不固定在模板中,而是通过选择器按需筛选示例,如根据长度、语义相似度或向量相似度进行选择,从而优化提示词组成,确保模型输入既符合长度要求又与任务高度相关。

动态提示词示例与静态提示词示例的区别

  • 动态提示词示例可以根据任务需求动态选择合适的提示词内容,而静态示例是写死在模板中的,无法改变。

  • 静态示例的长度固定,可能占用模型上下文窗口,限制灵活性。

  • 动态示例通过参数控制,可以在不同任务中切换不同的提示词内容,优化上下文窗口使用。

动态提示词示例的选择策略

  • 根据长度选择:基于输入和上下文窗口剩余长度动态选择合适的提示词示例。

  • 根据语义相似度选择:通过向量空间计算任务与示例之间的语义匹配度进行筛选。

  • 最大边际相关性(MMR)选择:综合考虑语义相关性和多样性,避免重复信息。

根据长度动态选择提示词示例

使用LengthBasedExampleSelector实现基于长度的动态提示词选择。

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from langchain_core.example_selectors import LengthBasedExampleSelector
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate

# 假设已经有这么多的提示词示例组:
examples = [
{"input": "happy", "output": "sad"},
{"input": "tall", "output": "short"},
{"input": "sunny", "output": "gloomy"},
{"input": "windy", "output": "calm"},
{"input": "高兴", "output": "悲伤"}
]

# 构造提示词模板
example_prompt = PromptTemplate(
input_variables=["input", "output"],
template="原词: {input}\n反义: {output}",
)

# 调用长度示例选择器
example_selector = LengthBasedExampleSelector(
# 传入提示词模板
example_prompt=example_prompt,
# 传入示例组
examples=examples,
# 设置格式化后的提示词最大长度
max_length=25,
)

# 使用小样本提示词模板来实现动态示例的调用
dynamic_prompt = FewShotPromptTemplate(
# 传入示例选择器
example_selector=example_selector,
# 传入提示词模板
example_prompt=example_prompt,
# 传入前缀
prefix="请给出以下词的反义词:",
# 传入后缀
suffix="原词:{adjective}\n反义:",
# 传入输入变量
input_variables=["adjective"],
)

# 小样本获得所有示例,这样可以有效减少输入的提示词长度
print(dynamic_prompt.format(adjective="big"))

# 如果输入长度很长,最终输出会根据长度要求减少(长度溢出,会将示例组进行删除,可能就会匹配不到想要的示例组)
long_string = "really big and huge and massive and gigantic and enormous and large and much bigger than very big"
print(dynamic_prompt.format(adjective=long_string))
  • 优点:提高上下文窗口利用率,减少不必要干扰;支持多任务复用提示词模板。
  • 缺点:基于长度的选择方式较为机械,可能忽略语义相关性(长度溢出,会将示例组进行删除,可能就会匹配不到想要的示例组);语义相似度方法需要额外计算资源。

根据语义相似度选择提示词示例

通过语义相似度匹配输入与示例组中的向量数据,利用余弦相似度算法在向量数据库中搜索最相关的结果,并返回Top K条匹配内容,实现动态筛选和精准输出。

  • 筛选示例组中与输入的语义相似度最高的示例
  • 本质:将问题与示例嵌入向量空间后进行搜索比对
  • 依赖:向量数据库

image-20250902111419077

使用SemanticSimilarityExampleSelector实现基于语义相似度的动态提示词选择。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# 使用最大余弦相似度来检索相关示例,以使示例尽量符合输入
# Use the maximum cosine similarity to retrieve relevant examples to make the examples as close as possible to the input
from langchain_community.vectorstores import Chroma
from langchain_core.example_selectors import SemanticSimilarityExampleSelector
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
from langchain_openai import OpenAIEmbeddings

import os
api_base = os.getenv("OPENAI_API_BASE")
api_key = os.getenv("OPENAI_API_KEY")


example_prompt = PromptTemplate(
input_variables=["input", "output"],
template="原词: {input}\n反义: {output}",
)

# 一组示例包含各种性质的反义词
# Examples of a pretend task of creating antonyms.
examples = [
{"input": "happy", "output": "sad"},
{"input": "tall", "output": "short"},
{"input": "energetic", "output": "lethargic"},
{"input": "sunny", "output": "gloomy"},
{"input": "windy", "output": "calm"},
{"input":"高兴","output":"悲伤"}
]

example_selector = SemanticSimilarityExampleSelector.from_examples(
# 传入示例组.
# Pass in the example group.
examples,
# 使用openAI嵌入来做相似性搜索
# Use openAI embeddings for similarity search
OpenAIEmbeddings(openai_api_key=api_key,openai_api_base=api_base),
# 使用Chroma向量数据库来实现对相似结果的过程存储
# Use the Chroma vector database to implement the process storage of similar results
Chroma,
# 结果条数
# Number of results
k=2,
)

#使用小样本提示词模板
similar_prompt = FewShotPromptTemplate(
# 传入选择器和模板以及前缀后缀和输入变量
# Pass in the selector and template, as well as the prefix and suffix and input variables
example_selector=example_selector,
example_prompt=example_prompt,
prefix="给出每个输入词的反义词",
suffix="原词: {adjective}\n反义:",
input_variables=["adjective"],
)

# 输入一个形容感觉的词语,应该查找近似的 happy/sad 示例
print(similar_prompt.format(adjective="难过"))

根据MMR与最大余弦相似度选择示例

最大边际相关性(MMR)是一种在信息检索中常用的方法,旨在平衡相关性和多样性。它通过选择与输入高度相关且彼此间具有足够差异性的样本来避免重复或过于相似的结果,从而提高检索质量。

  • 筛选示例组中符合MMR规则的示例
  • 本质:将问题与示例嵌入向量空间后进行搜索比对
  • 依赖:向量数据库
  • MMR: 是一种在信息检索中常用的方法,它的目标是在相关性和多样性之间找到一个平衡。MMR会首先找出与输入最相似(即余弦相似度最大)的样本。然后在迭代添加样本的过程中,对于与已选择样本过于接近(即相似度过高)的样本进行惩罚。MMR既能确保选出的样本与输入高度相关,又能保证选出的样本之间有足够的多样性。关注如何在相关性和多样性之间找到一个平衡。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#使用MMR来检索相关示例,以使示例尽量符合输入
# Use MMR to retrieve relevant examples to make the examples as close as possible to the input

import os
from langchain_community.vectorstores import FAISS
from langchain_core.example_selectors import (
MaxMarginalRelevanceExampleSelector,
)
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
from langchain_openai import OpenAIEmbeddings

api_base = os.getenv("OPENAI_API_BASE")
api_key = os.getenv("OPENAI_API_KEY")

#假设已经有这么多的提示词示例组:
# Suppose there are so many prompt examples:
examples = [
{"input":"happy","output":"sad"},
{"input":"tall","output":"short"},
{"input":"sunny","output":"gloomy"},
{"input":"windy","output":"calm"},
{"input":"高兴","output":"悲伤"}
]

#构造提示词模版
# Construct prompt template
example_prompt = PromptTemplate(
input_variables=["input","output"],
template="原词:{input}\n反义:{output}"
)

#调用MMR
# Call MMR
example_selector = MaxMarginalRelevanceExampleSelector.from_examples(
#传入示例组
# Pass in the example group
examples,
#使用openai的嵌入来做相似性搜索
# Use openai's embedding for similarity search
OpenAIEmbeddings(openai_api_base=api_base,openai_api_key=api_key),
#设置使用的向量数据库是什么
# Set what vector database is used
FAISS,
#结果条数
# Number of results
k=2,
)

#使用小样本模版
mmr_prompt = FewShotPromptTemplate(
example_selector=example_selector,
example_prompt=example_prompt,
prefix="给出每个输入词的反义词",
suffix="原词:{adjective}\n反义:",
input_variables=["adjective"]
)

#当我们输入一个描述情绪的词语的时候,应该选择同样是描述情绪的一对示例组来填充提示词模版
# When we enter a word describing emotions, we should choose a pair of examples that also describe emotions to fill the prompt template
print(mmr_prompt.format(adjective="难过"))

使用Partial进行部分格式化效果

提示词模板部分格式化的功能,通过Partial属性实现分步填充参数,适用于异步获取参数值或需动态生成内容(如当前时间)的场景,提升模板使用的灵活性。

部分格式化(Partial Formatting)及其应用场景

示例代码

1
2
3
4
5
6
from langchain.prompts import PromptTemplate

prompt = PromptTemplate.from_template("{foo}---{bar}")
partial_prompt = prompt.partial(foo="foo-test")
print(partial_prompt)
print(partial_prompt.format(bar="bar-test"))

动态内容处理与函数式参数传递

将模板中的参数替换为函数以支持更灵活的格式化逻辑

示例代码:使用函数动态生成当前时间并嵌入提示词模板中

1
2
3
4
5
6
7
8
9
10
11
12
13
# 这些场景非常有用,比如:当你希望提示词被执行的时候,始终是当前的时间
from datetime import datetime
from langchain.prompts import PromptTemplate

def _get_datetime():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

prompt = PromptTemplate(
template="Tell me a {adjective} joke about the day {date}",
input_variables=["adjective", "date"],
)
partial_prompt = prompt.partial(date=_get_datetime)
print(partial_prompt.format(adjective="funny"))

LangChain hub加载提示词管理

Lang Smith 是 LangChain 生态中的商业化产品,主要用于提示词管理,包含可观测性、评估和提示词工程三方面功能。它支持应用监控、AI 应用测试及提示词版本化管理,适合团队协作与长期项目开发使用。

  • 使用hub加载别人分享的提示词模板
  • 使用langsmith sdk来做提示词管理

langchain hub:https://smith.langchain.com/hub

image-20250902135805609

安装依赖

1
pip install -qU langsmith 

从hub上加载提示词

示例代码

1
2
3
4
5
6
7
import os
from langchain import hub

LANGCHAIN_API_KEY=os.environ.get("API_KEY")

prompt = hub.pull("rlm/rag-prompt")
print(prompt)

使用langsmith来管理提示词

  • 创建提示词
  • 测试提示词
  • 迭代提示词

创建提示词后上传到langsmith

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import os
from langsmith import Client
from langchain_core.prompts import ChatPromptTemplate


client = Client(api_key=os.environ.get("API_KEY"))

# Define the prompt

prompt = ChatPromptTemplate([
("system", "你的名字叫Jean,是一名帮助的聊天机器人."),
("user", "{question}"),
])

# Push the prompt

client.push_prompt("test1", object=prompt)

远程拉取自己的提示词并使用DeepSeek测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import os
from langsmith import Client
from langchain_deepseek import ChatDeepSeek


client = Client(api_key=os.environ.get("API_KEY"))

llm = ChatDeepSeek(
model="deepseek-chat",
api_base="xxxxxxxxxxxx",
api_key=os.environ.get("API_KEY"),
temperature=0,
)

# Pull the prompt to use

# You can also specify a specific commit by passing the commit hash "my-prompt:<commit-hash>"

prompt = client.pull_prompt("test1")

# Since our prompt only has one variable we could also pass in the value directly

# The code below is equivalent to formatted_prompt = prompt.invoke("What is the color of the sky?")

formatted_prompt = prompt.invoke({"question": "天空是什么颜色的?"})
print(formatted_prompt)
# Test the prompt

llm.invoke(formatted_prompt)

团队迭代提示词

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import os
from langsmith import Client
from langchain_core.prompts import ChatPromptTemplate

# Connect to the LangSmith client

client = Client(api_key=os.environ.get("API_KEY"))

# Define the prompt to update

new_prompt = ChatPromptTemplate([
("system", "你是一个有趣的机器人. 使用中文回复."),
("user", "{question}"),
])

# Push the updated prompt making sure to use the correct prompt name

# 注意tags可以更方便进行版本管理,你也可以打成v0.0.1这样

client.push_prompt("test1", object=new_prompt, tags=["Chinese"])

常用模板类特性和使用场景对比

常用提示词模板类的继承关系

image-20250915105216387

子类 适用模型类型 输入类型 主要用途
PromptTemplate 文本补全模型 单字符串 生成单轮文本任务的提示
ChatPromptTemplate 聊天模型 多消息列表 模拟多轮对话或角色扮演
FewShotPromptTemplate 所有模型 包含示例的模板 通过示例引导模型完成复杂任务