[LangChain语言模型组件的设计与实现]PromptValue——作为模型核心输入的提示词
在 LangChain 框架中,`PromptValue`是连接提示词模板与语言模型的中间数据层。提示词可以是单纯的字符串文本,还可以是一张图片,它们对应的类型分别为`StringPromptValue`和`ImagePromptValue`。Chat模型的提示词类型继承自`ChatPromptValue`,`ChatPromptValueConcrete`是它的一个子类。ImagePromptV
在 LangChain 框架中,PromptValue是连接提示词模板与语言模型的中间数据层。提示词可以是单纯的字符串文本,还可以是一张图片,它们对应的类型分别为StringPromptValue和ImagePromptValue。Chat模型的提示词类型继承自ChatPromptValue,ChatPromptValueConcrete是它的一个子类。ImagePromptValue仅仅是对单一图片的封装,对于真正多模态解决方案应该利用ChatPromptValue生成具有多媒体内容的消息来实现。如下这样UML类图中框出来的部分就是接下来介绍的内容。
1. PromptValue
LangChain语言模型组件最终会利用对应的客户端采用消息的形式与语言模型交互,所以作为作为输入的PromptValue需要转换成对应的消息列表,如下所示的抽象方法to_messages赋予了所有PromptValue针对消息列表转换的能力。除此之外,它还定义了to_string抽象方法生成一段表示文本。
class PromptValue(Serializable, ABC):
@abstractmethod
def to_string(self) -> str:
@abstractmethod
def to_messages(self) -> list[BaseMessage]
2. StringPromptValue
StringPromptValue用于表示纯文本提示词,其专属类型为“StringPromptValue”。提示词文本通过text字段表示,它也是实现的to_string方法的返回值。实现的to_messages方法利用提示词文本创建一个HumanMessage对象,并返回包含此对象的列表。
class StringPromptValue(PromptValue):
text: str
type: Literal["StringPromptValue"] = "StringPromptValue"
def to_string(self) -> str:
return self.text
def to_messages(self) -> list[BaseMessage]:
return [HumanMessage(content=self.text)]
3. ImagePromptValue
ImagePromptValue是为了支持多模态模型而设计的包装类。它通常封装了一个指向图像资源的ImageURL或 Base64 编码数据。ImagePromptValue允许将视觉信息与文本提示词一起传递给支持视觉能力的模型。它适用于图像识别、视觉问答等需要处理图片输入的任务。
class ImagePromptValue(PromptValue):
image_url: ImageURL
type: Literal["ImagePromptValue"] = "ImagePromptValue"
def to_string(self) -> str:
return self.image_url.get("url", "")
def to_messages(self) -> list[BaseMessage]:
return [HumanMessage(content=[cast("dict", self.image_url)])]
class ImageURL(TypedDict, total=False):
detail: Literal["auto", "low", "high"]
url: str
ImagePromptValue专属类型为“ImagePromptValue”。它的image_url字段返回一个ImageURL对象,该对应利用字段url提供图片的地址,它的detail表示处理图片的颗粒度/解析度,它具有如下三个选项。它的to_string方法返回图片的URL,to_messages返回一个HumanMessage,其内容为根据图片URL构建的字典。
- low:模型处理低分辨率版本(512px * 512px),消耗固定且较少的 Token(约 65-85 tokens),适用于对细节要求不高的场景。
- high: 模型首先查看低分辨率版本,然后对 512px 的切片进行高细节分析,适用于需要识别文字、复杂图表或微小目标的场景(消耗更多 Token)。
- auto: 模型根据图片大小自动决定。
4. ChatPromptValue
ChatPromptValue表示针对Chat模型的提示词。它本质上是对一个消息序列的封装(对应messages字段),实现的to_messages方法直接返回由它构建的列表。ChatPromptValue的to_string方法通过调用get_buffer_string函数得到返回的描述文本。get_buffer_string函数是一个非常实用的辅助函数,它能将复杂的消息序列转换为纯文本字符串。这在调试、日志记录或将对话历史输入给不支持消息格式的传统LLM时非常有用。它默认会将消息序列化为带有角色前缀的单一字符串,针对不同消息类型的角色前缀可以通过对应的参数进行定制。通过将format参数设置为xml可以转换成针对XML的格式化。
class ChatPromptValue(PromptValue):
messages: Sequence[BaseMessage]
def to_string(self) -> str:
return get_buffer_string(self.messages)
def to_messages(self) -> list[BaseMessage]:
return list(self.messages)
def get_buffer_string(
messages: Sequence[BaseMessage],
human_prefix: str = "Human",
ai_prefix: str = "AI",
*,
system_prefix: str = "System",
function_prefix: str = "Function",
tool_prefix: str = "Tool",
message_separator: str = "\n",
format: Literal["prefix", "xml"] = "prefix",
) -> str:
在如下的演示实例中,我们采用默认的角色名称对三个类型分别为SystemMessage、HumanMessage和AIMessage的消息进行了针对“prefix”(默认)和“xml”的格式化。
from langchain_core.messages.utils import get_buffer_string
from langchain_core.messages import AIMessage,HumanMessage,SystemMessage
messages = [
SystemMessage("You are a professional assistant."),
HumanMessage("What is the weather like today?"),
AIMessage("Is is sunny outside.")
]
result = get_buffer_string(messages).split("\n")
assert result[0] == "System: You are a professional assistant."
assert result[1] == "Human: What is the weather like today?"
assert result[2] == "AI: Is is sunny outside."
result = get_buffer_string(messages,format="xml").split("\n")
assert result[0] == '<message type="system">You are a professional assistant.</message>'
assert result[1] == '<message type="human">What is the weather like today?</message>'
assert result[2] == '<message type="ai">Is is sunny outside.</message>'
5. ChatPromptValueConcrete
ChatPromptValueConcrete是ChatPromptValue子类,代表一个“具体的”ChatPromptValue,对应的专属类型为“ChatPromptValueConcrete”。它进一步限制了messages字段的消息类型。
class ChatPromptValueConcrete(ChatPromptValue):
messages: Sequence[AnyMessage]
type: Literal["ChatPromptValueConcrete"] = "ChatPromptValueConcrete"
AnyMessage = Annotated[
Annotated[AIMessage, Tag(tag="ai")]
| Annotated[HumanMessage, Tag(tag="human")]
| Annotated[ChatMessage, Tag(tag="chat")]
| Annotated[SystemMessage, Tag(tag="system")]
| Annotated[FunctionMessage, Tag(tag="function")]
| Annotated[ToolMessage, Tag(tag="tool")]
| Annotated[AIMessageChunk, Tag(tag="AIMessageChunk")]
| Annotated[HumanMessageChunk, Tag(tag="HumanMessageChunk")]
| Annotated[ChatMessageChunk, Tag(tag="ChatMessageChunk")]
| Annotated[SystemMessageChunk, Tag(tag="SystemMessageChunk")]
| Annotated[FunctionMessageChunk, Tag(tag="FunctionMessageChunk")]
| Annotated[ToolMessageChunk, Tag(tag="ToolMessageChunk")],
Field(discriminator=Discriminator(_get_type)),
]
更多推荐



所有评论(0)