🎯 课程主题
通过 ToolStrategy 的 tool_message_content 参数自定义伪工具返回消息的 content,实现消息精简与 token 节省。
📝 核心知识点
1. tool_message_content 参数的作用
- 概念说明:当使用
ToolStrategy进行结构化输出时,LangChain 会生成一个"伪工具"并产生对应的ToolMessage,tool_message_content用于自定义该 ToolMessage 的 content 字段内容。 - 关键细节:
- 默认行为:不设置时,content 显示为完整的结构化输出数据(如 JSON 字符串),内容可能很长。
- 自定义后:可替换为简洁的提示文字(如
"成功抽取信息"),使消息更加友好。 - 不影响最终结果:结构化输出的数据仍完整保存在
response["structured_response"]中。 - 核心价值:减少不必要的 token 消耗,尤其是当字段多、数据量大时效果显著。
🏗️ 架构与工作流
默认行为:
ToolStrategy(schema=ContactInfo)
→ ToolMessage(content='{"name": "小明", "email": "test@163.com", "phone": "130..."}')
自定义后:
ToolStrategy(schema=ContactInfo, tool_message_content="成功抽取信息")
→ ToolMessage(content="成功抽取信息")
无论哪种设置:
response["structured_response"] 始终包含完整的结构化数据
💻 代码实战
from pydantic import BaseModel, Field
from langchain.agents import create_agent
from langchain.agents.structured_output import ToolStrategy
# ========== 定义结构化输出类型 ==========
class ContactInfo(BaseModel):
"""用户联系方式"""
name: str = Field(description="用户姓名")
email: str = Field(description="邮箱地址")
phone: str = Field(description="电话号码")
# ========== 默认行为(不设置 tool_message_content) ==========
agent_default = create_agent(
model=model,
response_format=ToolStrategy(schema=ContactInfo)
)
response = agent_default.invoke({
"messages": [{"role": "user", "content": "小明的邮箱是 test@163.com,电话是 13012341234"}]
})
# 查看 ToolMessage 的 content
for msg in response["messages"]:
msg.pretty_print()
# ToolMessage 会显示:
# content='{"name": "小明", "email": "test@163.com", "phone": "13012341234"}'
# ========== 自定义 tool_message_content ==========
agent_custom = create_agent(
model=model,
response_format=ToolStrategy(
schema=ContactInfo,
tool_message_content="成功抽取信息"
)
)
response = agent_custom.invoke({
"messages": [{"role": "user", "content": "小明的邮箱是 test@163.com,电话是 13012341234"}]
})
# ToolMessage 的 content 变为:
# content="成功抽取信息"
# structured_response 仍然包含完整数据:
print(response["structured_response"])
# ContactInfo(name='小明', email='test@163.com', phone='13012341234')
⚠️ 常见问题与避坑指南
tool_message_content只影响 ToolMessage 的显示内容,不会丢失结构化数据,structured_response 始终完整。- 不会影响模型推理:此参数仅作用于最终返回的消息展示,不影响 Agent 的结构化输出流程。
- token 优化建议:当 schema 字段多(如10+字段)且每条消息都包含完整 JSON 时,设置简短的自定义 content 可显著降低 token 消耗。
💡 个人总结与延伸
- 此参数虽小,但在高频调用、多字段输出的生产场景中,能有效降低 token 成本。
- 建议将 content 设置为有意义的标识文字(如
"客户信息已提取"或"结构化完成"),既节省 token 又便于日志阅读。 - 可配合
response["structured_response"]取完整数据用于业务逻辑,而消息列表中的 ToolMessage 仅作提示用途。