Skip to content

Prompt 基础类文档

Prompt Base Class Documentation

本模块定义了 Prompt 系统的基础类。 This module defines the base classes for the Prompt system.

BasePrompt 类

BasePrompt Class

BasePrompt 是所有具体 Prompt 实现的抽象基类。它负责将 PromptContext 格式化为字符串或多模态内容,以供 LLM 使用。 BasePrompt is an abstract base class for all concrete prompt implementations. It is responsible for formatting a PromptContext into a string or multimodal content for use by an LLM.

Bases: TFBaseModel, ABC

additional_kwargs_schema property

additional_kwargs_schema: Optional[JsonSchemaValue]

在Prompt设计中,是通过对当前上下文中的信息填充到Prompt中Template模板渲染进而得到最终的提示词。

目前的上下文有以下几类:

  1. 用户输入的内容,对于用户输入内容的渲染,可以使用UserInputPrompt及其子类进行构建
  2. 记忆Recall回来的内容,而记忆Recall回来的内容又分为以下几个子类: a. Conversation 对话内容,对于Conversation的内容,使用ConversationPrompt及其子类进行渲染 b. Document 文档内容,对于Document的内容,使用MemoPrompt及其子类进行渲染 c. Knowledge 知识内容,对于Knowledge的内容,使用KnowledgePrompt及其子类进行渲染
  3. 工具Tool的内容,对于Tool的内容,使用ToolPrompt及其子类进行渲染
  4. 另外用户可以自定义一些静态内容,用于在渲染时填充,这类静态内容以Examples的形式存在。对于这类内容,用户可以 使用ExamplesPrompt配合ExampleSelector进行选择。因为ExampleSelector的存在,这类内容也具备的动态性,因为每次Loader均是以Selector 的策略为准则进行选择的,所以每次Loader的内容均是不同的。对于这类内容,用户可以使用ExamplesPrompt及其子类进行渲染
  5. 与之上所有的情况不同,还有一类内容,允许用户在发问的时候,作为元数据传入,这类内容属于对第一类内容的补充,或者说是对第一类内容的补充信息。 比如说用户在发问的时候,可能会有一些额外的信息需要传入,比如(当前工作项目的根目录)。这类数据是结构化的,与其放在用户输入的自然语言中, 效果不如直接传入一个结构化的对象。同时这类内容有一定的复用性,可能会在同一个Session或者不同UserInput连续生效,因此这类内容作为一个独立的 上下文信息单元存在。这就是UserInput中的AdditionKwargs。这类内容使用AdditionInfoPrompt及其子类进行渲染

以上所有情况中:1,2,3,4均属于纯动态内容,其特点是每次随着用户输入在改变,而且数据源是固定的,比如存储于某个向量库,或者PG数据库,再或者与作为配置存在于配置文件内。 但是第5类内容是需要区别对待的,因为它依赖于用户或者前置系统进行动态输入,在TFRobot内部,没有预存储能力,也不会有任何动态策略为其动态生成。因此第5类内容有个最大的特点: AdditionInfoPrompt渲染是否成功在TFRobot-Chain内部无法保障。因为其依赖外部系统的输入。

故而在BasePrompt中设立了此字段,用于记录与表征当前Prompt的渲染是否依赖于某些特殊的AdditionalInfo值,及其数据结构要求。一旦有要求,通过此字段对外暴露,可以方便指导用户或者外部系统进行填入。

Notes

注意,不要在编写BasePrompt滥用此方法,这个方法并不等同于Template.params_schema,而是描述对于CurrentInput.AdditionalKwargs的要求。一般意义上, 等同于AdditionalInfoPrompt.template.params_schema。但并非绝对一致,因为有可能类的封装作者会有自己的理解与实现。但本质上对当前用户输入消息的额外元数据的要求描述。 其意义代表如果不按此要求传入额外的元数据,Prompt渲染随时可能会崩溃。

Returns:

Type Description
Optional[JsonSchemaValue]

Optional[JsonSchemaValue]: The additional kwargs schema. Defaults to None. | 附加参数模式. 默认值为None,即不要求额外参数

validate_prompt

validate_prompt() -> Self

主要判断当前的Template的参数要求是否是忽略其它字段。因为在渲染时会将上下文全部传入,所以用于Prompt的Template不可以Forbid多余字段。可以使用Ignore来实现类似要求

Returns:

Name Type Description
Any Self

The validated value. | 已验证的值。

Source code in tfrobot/brain/chain/prompt/base.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
@model_validator(mode="after")
def validate_prompt(self) -> Self:
    """
    主要判断当前的Template的参数要求是否是忽略其它字段。因为在渲染时会将上下文全部传入,所以用于Prompt的Template不可以Forbid多余字段。可以使用Ignore来实现类似要求

    Returns:
        Any: The validated value. | 已验证的值。
    """
    tmp = self.template
    if tmp.params_schema is not None and isinstance(tmp.params_schema, TypeAdapter):
        if is_base_model_wrapped_by_type_adapter(tmp.params_schema):
            if get_core_cls_of_type_adapter(tmp.params_schema).model_config.get("extra") == "forbid":
                raise ValueError("The params_schema should not be set to forbid.")
            if not get_core_cls_of_type_adapter(tmp.params_schema).model_config.get("arbitrary_types_allowed"):
                raise ValueError("The params_schema should set to arbitrary_types_allowed.")

    return self

format_2_str abstractmethod

format_2_str(ctx: PromptContext) -> str

Format the prompt context to a string. | 将提示上下文格式化为字符串。

Parameters:

Name Type Description Default
ctx PromptContext

The prompt context. | 提示上下文。

required

Returns:

Name Type Description
str str

The formatted prompt. | 格式化后的提示。

Source code in tfrobot/brain/chain/prompt/base.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
@abstractmethod
def format_2_str(self, ctx: PromptContext) -> str:
    """
    Format the prompt context to a string. | 将提示上下文格式化为字符串。

    Args:
        ctx(PromptContext): The prompt context. | 提示上下文。

    Returns:
        str: The formatted prompt. | 格式化后的提示。
    """
    ...

format_2_multimodal abstractmethod

format_2_multimodal(ctx: PromptContext) -> tuple[str, dict[str, dict[str, Path | Url | bytes]]]

Format the prompt context to a string and multimodal content. | 将提示上下文格式化为字符串与多模态记录字典。

Parameters:

Name Type Description Default
ctx PromptContext

The prompt context. | 提示上下文。

required

Returns:

Type Description
tuple[str, dict[str, dict[str, Path | Url | bytes]]]

tuple[str, dict[str, dict[str, Path | Url | bytes]]]: The formatted prompt and multimodal content. | 格式化后的Prompt提示及多模态内容字典。

Source code in tfrobot/brain/chain/prompt/base.py
103
104
105
106
107
108
109
110
111
112
113
114
115
@abstractmethod
def format_2_multimodal(self, ctx: PromptContext) -> tuple[str, dict[str, dict[str, Path | Url | bytes]]]:
    """
    Format the prompt context to a string and multimodal content. | 将提示上下文格式化为字符串与多模态记录字典。

    Args:
        ctx(PromptContext): The prompt context. | 提示上下文。

    Returns:
        tuple[str, dict[str, dict[str, Path | Url | bytes]]]: The formatted prompt
            and multimodal content. | 格式化后的Prompt提示及多模态内容字典。
    """
    ...

WrapPrompt 类

WrapPrompt Class

WrapPrompt 用于包装现有的 Prompt 列表,允许在它们周围添加额外的信息或结构。它首先渲染内部包装的 Prompts,然后使用其结果以及额外的上下文来渲染自身的模板。 WrapPrompt is used to wrap a list of existing prompts, allowing additional information or structure to be added around them. It first renders the internally wrapped prompts and then uses their result, along with additional context, to render its own template.

Bases: BasePrompt

在Prompt使用过程中会有一个场景。需要包装用户之前的所有Prompt形成一个新的Prompt,比如说用户已经自定义了自己的Prompt,但是在某个场景下需要将用户的Prompt包装一下,比如说加上一些额外的信息。

实现这样的能力有两个方法,因为LLM prompts均是以list形成的,所以可以动态向list头部与尾部添加新的Prompt实现包裹。 但也可以用这个类,直接将原Prompts装到一个WrapPrompt实例中,然后使用这个新实例替换原来的Prompts。这样就可以实现包装的效果。

其工作原理是调用自身 wrapped_prompts先进行format_2_str,然后再调用自身的template进行format_2_str,只是format时多传入一个wrapped_str参数, 这个参数代码wrapped_prompts的渲染结果。

additional_kwargs_schema property

additional_kwargs_schema: Optional[JsonSchemaValue]

附加参数的schema

Returns:

Type Description
Optional[JsonSchemaValue]

Optional[JsonSchemaValue]: 附加参数的schema

format_2_str

format_2_str(ctx: PromptContext) -> str

Format the prompt context to a string. | 将提示上下文格式化为字符串。

Parameters:

Name Type Description Default
ctx PromptContext

The prompt context. | 提示上下文。

required

Returns:

Name Type Description
str str

The formatted prompt. | 格式化后的提示。

Source code in tfrobot/brain/chain/prompt/base.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def format_2_str(self, ctx: PromptContext) -> str:
    """
    Format the prompt context to a string. | 将提示上下文格式化为字符串。

    Args:
        ctx (PromptContext): The prompt context. | 提示上下文。

    Returns:
        str: The formatted prompt. | 格式化后的提示。
    """
    wrapped_str = "\n".join([prompt.format_2_str(ctx) for prompt in self.wrapped_prompts])
    ctx_dict = ctx.model_dump(mode="json")
    ctx_dict.update({"wrapped_str": wrapped_str})
    return self.template.render(params=ctx_dict)

format_2_multimodal

format_2_multimodal(ctx: PromptContext) -> tuple[str, dict[str, dict[str, Path | Url | bytes]]]

将上下文渲染为字符串与多模态记录

Parameters:

Name Type Description Default
ctx PromptContext

上下文

required

Returns:

Type Description
tuple[str, dict[str, dict[str, Path | Url | bytes]]]

tuple[str, dict[str, dict[str, Path | Url | bytes]]]: 格式化后的Prompt提示及多模态内容

Source code in tfrobot/brain/chain/prompt/base.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
def format_2_multimodal(self, ctx: PromptContext) -> tuple[str, dict[str, dict[str, Path | Url | bytes]]]:
    """
    将上下文渲染为字符串与多模态记录

    Args:
        ctx (PromptContext): 上下文

    Returns:
        tuple[str, dict[str, dict[str, Path | Url | bytes]]]: 格式化后的Prompt提示及多模态内容
    """
    wrapped_str = "\n".join([prompt.format_2_str(ctx) for prompt in self.wrapped_prompts])
    ctx_dict = ctx.model_dump(mode="json")
    ctx_dict.update({"wrapped_str": wrapped_str})
    return self.template.multimodal_render(params=ctx_dict)