You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Chat模型时向LLM发送的内容及最终文本查看方法

关于LangChain ChatPromptTemplate消息格式与打印的问题

1. 发送给LLM的消息格式

是的,你猜测的格式逻辑是正确的。不同LLM(比如ChatOpenAI)会有自己标准化的角色分隔格式,LangChain会自动把SystemMessage、HumanMessage、AIMessage转换为对应LLM能识别的结构。

以ChatOpenAI为例,对应你示例的消息,实际发送的格式会是:

System: You are a helpful AI bot. Your name is Bob.
Human: Hello, how are you doing?
Assistant: I'm doing well, thanks!
Human: What is your name?

其中LangChain会自动将ai类型的消息映射为LLM对应的角色(比如OpenAI统一用Assistant),无需手动调整。

2. 打印发送给LLM的最终文本

可以通过遍历格式化后的消息列表,拼接角色与内容来实现,直接用以下代码即可:

from langchain_core.prompts import ChatPromptTemplate

template = ChatPromptTemplate.from_messages([
    ("system", "You are a helpful AI bot. Your name is {name}."),
    ("human", "Hello, how are you doing?"),
    ("ai", "I'm doing well, thanks!"),
    ("human", "{user_input}"),
])

messages = template.format_messages(
    name="Bob",
    user_input="What is your name?"
)

# 生成并打印最终发送给LLM的文本
for msg in messages:
    # 适配OpenAI的角色命名规则
    role_map = {"system": "System", "human": "Human", "ai": "Assistant"}
    print(f"{role_map[msg.type]}: {msg.content}")

执行后会输出和LLM实际接收格式完全一致的文本。

内容的提问来源于stack exchange,提问作者BPDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 04:05:11