资讯动态

CAMEL 消息转换中的 Hermes 风格函数调用格式化:`HermesFunctionFormatter` 协议解析与实战

发布时间:2026/9/13 23:31:29 来源:尧图企业网站定制
CAMEL 消息转换中的 Hermes 风格函数调用格式化HermesFunctionFormatter协议解析与实战【免费下载链接】camel CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org项目地址: https://gitcode.com/GitHub_Trending/ca/camel本文聚焦 CAMEL 项目中camel.messages.conversion.sharegpt.hermes模块对应 API 文档入口系统讲解 Hermes 风格的函数调用tool call / tool response在 ShareGPT 消息格式中的表示、序列化与解析机制。读者将掌握HermesFunctionFormatter的格式化与提取 API、与BaseMessage/FunctionCallingMessage的双向转换链路以及如何在数据生成等场景中落地使用。模块定位ShareGPT 消息体系中的 Hermes 实现在 CAMEL 的消息转换体系中camel.messages.conversion包负责把对话数据在多种格式之间互转详见 包文档。其中 ShareGPT 格式是一类被广泛用于开源数据集与微调管线的对话表示——每条消息包含from角色与value内容两个字段。函数调用能力在此基础上以文本协议的形式编码进value中。camel.messages.conversion.sharegpt.hermes子包入口见 sharegpt/hermes/init.py提供了Hermes 风格的函数调用格式实现即 NousResearch Hermes 系列模型使用的基于tool_call/tool_responseXML 标签的文本协议。该子包对外只导出一个类from .hermes_function_formatter import HermesFunctionFormatter __all__ [ HermesFunctionFormatter, ]从源码结构看格式化器体系采用抽象基类 具体格式实现的分层设计FunctionCallFormatter 是泛型抽象基类定义了四个抽象方法extract_tool_calls、extract_tool_response、format_tool_call、format_tool_response并通过CallT/ResponseT两个类型变量约束具体的工具调用/响应类型HermesFunctionFormatter继承该基类用 Hermes 文本协议填充这四类操作。这意味着未来接入其他函数调用格式如 Anthropic、Mistral 的协议时只需新增一个 Formatter 子类上层消息转换逻辑无需改动。核心数据结构HermesToolCall与HermesToolResponse在 hermes_function_formatter.py 中定义了两个数据类它们是格式化的承载对象class HermesToolResponse(ToolResponse): rRepresents a single tool/function call with validation pass class HermesToolCall(ToolCall): rRepresents a single tool/function call with validation pass两者分别继承自camel.messages.conversion包中基于 Pydantic 的ToolCall与ToolResponse定义见 conversation_models.py。这些基类自带严格的字段约束ToolCallname字段长度限制 1256arguments必须是Dict[str, Any]且通过field_validator强制要求 JSON 可序列化否则抛出ValueError(Arguments must be JSON-serializable)ToolResponsename字段同样限制 1256content可以是任意 JSON 可序列化的字面量或对象同样有field_validator校验。两个基类都配置了extra: forbid即遇到未知字段会直接报错避免脏数据悄悄混入。从源码结构看Hermes 子类当前以空类形式存在其作用是为该协议固化独立的类型标注HermesFunctionFormatter[HermesToolCall, HermesToolResponse]使类型检查与后续扩展更清晰。格式化方法把工具调用写进文本协议HermesFunctionFormatter提供两个写方向的方法源码 L114-L153format_tool_call(content, func_name, args)将一次函数调用序列化为 Hermes 格式字符串tool_call_dict {name: func_name, arguments: args} tool_call_json json.dumps(tool_call_dict, ensure_asciiFalse) if content: return f{content}\ntool_call\n{tool_call_json}\n/tool_call return ftool_call\n{tool_call_json}\n/tool_call注意两个实现细节其一参数使用json.dumps且ensure_asciiFalse保证中文等非 ASCII 内容不被转义便于人读与后续微调其二content非空时作为前缀拼在tool_call之前保留模型在调用工具前的自然语言叙述如 Let me check Teslas stock fundamentals.。生成的典型形态Let me check Teslas stock fundamentals. tool_call {name: get_stock_fundamentals, arguments: {symbol: TSLA}} /tool_callformat_tool_response(func_name, result)将工具执行结果序列化为tool_response块response_dict {name: func_name, content: result} response_json json.dumps(response_dict, ensure_asciiFalse) return ftool_response\n{response_json}\n/tool_response典型形态tool_response {name: get_stock_fundamentals, content: {symbol: TSLA, company_name: Tesla, Inc., sector: Consumer Cyclical, pe_ratio: 49.604652}} /tool_response提取方法从模型输出中还原结构化对象extract_tool_calls(message)源码 L65-L87用正则从消息文本中抓取全部工具调用pattern rtool_call\s*({.*?})\s*/tool_call matches re.finditer(pattern, message, re.DOTALL)re.DOTALL让.能匹配换行符因此支持跨多行的 JSON 负载{.*?}采用非贪婪匹配避免多个连续tool_call块互相吞并。每个匹配块经_loads解析后用HermesToolCall.model_validate校验。单个块解析失败时不会中断整体流程而是打印Warning: Failed to parse tool call: ...并跳过体现容忍单点失败的设计。extract_tool_response(message)源码 L89-L112与之对称使用tool_response标签提取单个响应解析失败返回None。两者的返回类型分别为List[HermesToolCall]与Optional[HermesToolResponse]。_loads的双通道容错解析解析的关键在于静态方法_loads源码 L45-L63try: return json.loads(raw) except json.JSONDecodeError: return ast.literal_eval(raw)它先按标准 JSON 解析失败时回退到ast.literal_eval以兼容早期 CAMEL 版本输出的 Pythonrepr风格负载单引号字符串、True/False/None字面量。这一兼容性设计有测试专门背书test_hermes_extract_tool_calls_parses_legacy_repr_payloadtest/messages/test_func_message.py验证了如下旧格式仍能正确解析tool_call {name: note_tool, arguments: {city: London, active: True}} /tool_call双向转换链路与 ShareGPT 消息模型的集成HermesFunctionFormatter的真正价值体现在与 CAMEL 消息模型的集成中。BaseMessage.from_sharegpt与BaseMessage.to_sharegptcamel/messages/base.py默认即使用HermesFunctionFormatter()作为函数格式ShareGPT → CAMELfrom_sharegpt将 ShareGPT 消息映射为 CAMEL 角色system→system、human→user、gpt→assistant、tool→assistant随后对gpt消息调用extract_tool_calls对tool消息调用extract_tool_response命中时生成FunctionCallingMessagefunc_name/args/result均被结构化填充并把content中残留的tool_call块通过正则剔除保留干净的自然语言CAMEL → ShareGPTFunctionCallingMessage.to_sharegptcamel/messages/func_message.py根据result is None判断是调用还是响应分别走format_tool_call与format_tool_response产出fromgpt或fromtool的 ShareGPT 消息。若设置了mask_output则响应内容会被替换为[MASKED]以保护敏感信息。此外ShareGPT 会话层还有ShareGPTConversationconversation_models.py负责校验消息顺序会话必须以system或human开头tool消息必须紧跟包含tool_call的gpt消息gpt消息前面只能是human或tool。这保证了往返转换后的对话流在逻辑上是自洽的。测试验证往返不变量仓库的单元测试test/messages/test_func_message.py从多个角度锁定了 Hermes 格式的行为完整往返test_convert_function_call_and_response_to_from_sharegpt_hermes验证to_sharegpt()产物包含tool_call标签且经from_sharegpt还原后与原始FunctionCallingMessage相等非字符串参数保真test_hermes_sharegpt_roundtrip_preserves_non_string_args覆盖了含撇号字符串、布尔值、None、浮点数的参数集确保to_sharegpt() → from_sharegpt()往返不丢失或损坏参数测试注释明确说明早期版本因 Pythonrepr序列化会破坏这类数据旧数据兼容前述 legacyrepr负载解析测试保证了历史序列化数据仍可读。实战场景生成带真实函数调用的训练数据HermesFunctionFormatter最典型的落地场景是数据生成。仓库提供的 cookbook Data Generation with Real Function Calls and Hermes Format 展示了完整流水线先用ChatAgent基于工具 schema 生成拟人化用户查询再用携带真实工具如MathToolkit、SearchToolkit的 agent 执行查询最后把agent.memory中的消息统一通过msg.to_sharegpt(HermesFunctionFormatter())转成 ShareGPT 格式并落盘为 JSON。其中系统提示词明确要求模型将每个函数调用封装在tool_call /tool_callXML 标签中与本文介绍的解析协议严格对应。若想快速体验双向转换可直接运行仓库自带的 examples/conversion.py它构造了一段包含系统提示、用户提问、tool_call工具调用、tool_response工具响应与最终回答的 ShareGPT 会话先转为 CAMEL 消息再转回 ShareGPT验证信息无损。小结camel.messages.conversion.sharegpt.hermes模块以HermesFunctionFormatter为核心为 ShareGPT 消息体系提供了一套完整、健壮的 Hermes 风格函数调用协议实现Pydantic 数据模型保证结构合法tool_call/tool_response标签与 JSON 负载保证文本可读、可训练_loads的双通道解析保证新旧数据兼容而from_sharegpt/to_sharegpt的默认集成则让任何 CAMEL 消息流都能低成本地与 Hermes 生态对接。无论是构造微调数据集还是与其他采用 Hermes 协议的工具链互通它都是值得优先了解的入口。【免费下载链接】camel CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org项目地址: https://gitcode.com/GitHub_Trending/ca/camel创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价