Transformers 工具调用与 RAG:基于 apply_chat_template 的完整实战指南

发布时间:2026/9/10 8:03:09
Transformers 工具调用与 RAG:基于 apply_chat_template 的完整实战指南 Transformers 工具调用与 RAG基于 apply_chat_template 的完整实战指南【免费下载链接】transformers Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformersPreTrainedTokenizerBase.apply_chat_template是 Transformers 将结构化对话角色消息、工具定义、检索文档渲染为模型可读 token 序列的统一入口。本指南以 docs/source/ko/chat_extras.md 为骨架结合 tokenization_utils_base.py 与 chat_template_utils.py 的源码实现系统讲解如何在工具Tool与检索增强生成RAG场景下正确使用聊天模板。读完你将掌握工具函数的编写规范、JSON Schema 的自动生成与手动构造、带tool_calls的多轮调用闭环以及基于documents参数的 RAG 注入流程。一、apply_chat_template 的多参数能力apply_chat_template除了接收常规的conversation消息列表外还支持字符串、列表、字典等几乎所有类型的附加参数。从 tokenization_utils_base.py 的签名可以看到与本主题直接相关的两个关键参数是toolslist[dict | Callable] | None可供模型调用的函数列表每个工具以 JSON Schema 形式传入或直接传入可调用函数由库自动转换documentslist[dict[str, str]] | NoneRAG 场景下注入给模型的文档列表每个文档为含title与text键的字典。源码内部的调用链见 tokenization_utils_base.py会将这些参数合并进模板关键字最终交给render_jinja_template完成渲染随后通过self(rendered_chat, ...)完成分词输出可直接喂给model.generate()的输入。二、工具Tools实战2.1 工具函数的编写规范工具是 LLM 为完成特定任务而调用的函数可通过实时信息、计算工具或数据库访问扩展对话式智能体的能力。编写工具时应遵循以下规则函数名应能准确描述其功能函数参数必须写在函数签名中并包含类型提示不要写在Args块里函数须包含 Google 风格 的 docstring可包含返回类型与Returns块但大多数工具型模型会忽略返回值因此可省略。示例获取指定位置当前温度与风速的工具。def get_current_temperature(location: str, unit: str) - float: Gets the current temperature at a location. Args: location: The location to get the temperature for, in the format city, country unit: The unit to return the temperature in. (choices: [celsius, fahrenheit]) Returns: The current temperature at the specified location, in the specified unit, as a float. return 22. # 真实实现中应查询天气服务 def get_current_wind_speed(location: str) - float: Gets the current wind speed in km/h at a location. Args: location: The location to get the wind speed for, in the format city, country Returns: The current wind speed at the specified location, in km/h, as a float. return 6. # 真实实现中应查询天气服务 tools [get_current_temperature, get_current_wind_speed]2.2 加载支持工具调用的模型加载一个支持工具使用的模型与对应 tokenizer例如 NousResearch/Hermes-2-Pro-Llama-3-8B、Mixtral 等更大规模的模型。import torch from transformers import AutoModelForCausalLM, AutoTokenizer tokenizer AutoTokenizer.from_pretrained(NousResearch/Hermes-2-Pro-Llama-3-8B) model AutoModelForCausalLM.from_pretrained( NousResearch/Hermes-2-Pro-Llama-3-8B, torch_dtypetorch.bfloat16, device_mapauto, )2.3 将 tools 传入聊天模板并生成首个工具调用构造一条用户天气查询消息将messages与工具列表tools一起传给apply_chat_template再把结果作为模型输入生成文本messages [ { role: system, content: You are a bot that responds to weather queries. You should reply with the unit used in the queried location., }, {role: user, content: Hey, whats the temperature in Paris right now?}, ] inputs tokenizer.apply_chat_template( messages, toolstools, add_generation_promptTrue, return_dictTrue, return_tensorspt, ) inputs {k: v for k, v in inputs.items()} outputs model.generate(**inputs, max_new_tokens128) print(tokenizer.decode(outputs[0][len(inputs[input_ids][0]):]))模型按 docstring 中定义的格式以正确的参数调用了get_current_temperature将 Paris 推断为 Paris, France并判定温度单位应使用摄氏度tool_call {arguments: {location: Paris, France, unit: celsius}, name: get_current_temperature} /tool_call|im_end|2.4 回填工具执行结果并继续对话将get_current_temperature函数及其参数放入tool_call字典并作为assistant角色而非system或user追加到消息列表让模型读取函数输出并与用户继续对话。[!WARNING] OpenAI API 以 JSON 字符串形式表达tool_call而 Transformers 要求字典格式若混用可能报错或导致模型行为异常。Llama 系模型tool_call {name: get_current_temperature, arguments: {location: Paris, France, unit: celsius}} messages.append({role: assistant, tool_calls: [{type: function, function: tool_call}]}) inputs tokenizer.apply_chat_template( messages, toolstools, add_generation_promptTrue, return_dictTrue, return_tensorspt, ) inputs {k: v for k, v in inputs.items()} out model.generate(**inputs, max_new_tokens128) print(tokenizer.decode(out[0][len(inputs[input_ids][0]):]))The temperature in Paris, France right now is approximately 12°C (53.6°F).|im_end|Mistral / Mixtral 模型Mistral 与 Mixtral 模型额外要求tool_call_id它是一个 9 位字母数字字符串需赋给tool_call字典的id键。tool_call_id 9Ae3bDc2F tool_call {name: get_current_temperature, arguments: {location: Paris, France, unit: celsius}} messages.append( {role: assistant, tool_calls: [{type: function, id: tool_call_id, function: tool_call}]} ) inputs tokenizer.apply_chat_template( messages, toolstools, add_generation_promptTrue, return_dictTrue, return_tensorspt, ) inputs {k: v for k, v in inputs.items()} out model.generate(**inputs, max_new_tokens128) print(tokenizer.decode(out[0][len(inputs[input_ids][0]):]))从源码看tools参数在模板不支持函数调用时不会产生任何效果见 tokenization_utils_base.py多模板模型还会依据是否传入tools自动选择tool_use模板见 tokenization_utils_base.py。三、工具 JSON Schema 的生成与手工构造3.1 自动转换get_json_schemaapply_chat_template会把函数自动转换为 JSON Schema 后注入聊天模板。LLM 看不到函数内部代码——它只关心函数的定义与参数。若工具遵循上文规则库会自动完成转换也可调用get_json_schema手动查看与调试实现位于 chat_template_utils.py。from transformers.utils import get_json_schema def multiply(a: float, b: float): A function that multiplies two numbers Args: a: The first number to multiply b: The second number to multiply return a * b schema get_json_schema(multiply) print(schema){ type: function, function: { name: multiply, description: A function that multiplies two numbers, parameters: { type: object, properties: { a: { type: number, description: The first number to multiply }, b: { type: number, description: The second number to multiply } }, required: [a, b] } } }源码细节见 chat_template_utils.py表明get_json_schema依赖inspect.getdoc解析 Google 风格 docstring并通过类型提示映射 JSON 类型int → integer、float → number、str → string、bool → boolean映射见 chat_template_utils.py。docstring 缺失或参数缺少描述时会抛出DocstringParsingException。此外参数描述末尾的(choices: [tea, coffee])会被解析为 schema 的enum字段方法中的隐式self/cls会被忽略。[!WARNING] 保持函数签名简单、参数数量最小化。相比带嵌套参数的复杂函数简单函数更易被模型理解与正确使用。3.2 手工编写 Schema你可以直接编辑或从零编写 schema从而为更复杂的函数灵活定义精确描述再传给apply_chat_template# 无参数函数 current_time { type: function, function: { name: current_time, description: Get the current local time as a string., parameters: {type: object, properties: {}}, }, } # 带两个数字参数的完整函数 multiply { type: function, function: { name: multiply, description: A function that multiplies two numbers, parameters: { type: object, properties: { a: {type: number, description: The first number to multiply}, b: {type: number, description: The second number to multiply}, }, required: [a, b], }, }, } model_input tokenizer.apply_chat_template(messages, tools[current_time, multiply])四、RAG通过 documents 参数注入检索文档检索增强生成RAG模型在返回查询结果前先检索文档获取额外信息以扩展模型已有知识。对 RAG 模型在apply_chat_template中增加documents参数即可它必须是一个文档列表其中每个文档是含title与content键的单个字典。[!TIP]documents参数并未被广泛支持许多模型拥有会忽略documents的聊天模板。确认模型是否支持阅读模型卡或执行print(tokenizer.chat_template)检查模板中是否包含documents键。Command-R 与 Command-R 均在 RAG 聊天模板中支持documents。构造要传给模型的文档列表documents [ { title: The Moon: Our Age-Old Foe, text: Man has always dreamed of destroying the moon. In this essay, I shall..., }, { title: The Sun: Our Age-Old Friend, text: Although often underappreciated, the sun provides several notable benefits..., }, ]在apply_chat_template中设置chat_templaterag并生成回复from transformers import AutoTokenizer, AutoModelForCausalLM # 加载模型与 tokenizer tokenizer AutoTokenizer.from_pretrained(CohereForAI/c4ai-command-r-v01-4bit) model AutoModelForCausalLM.from_pretrained(CohereForAI/c4ai-command-r-v01-4bit, device_mapauto) device model.device # 确认模型所在设备 # 定义对话输入 conversation [{role: user, content: What has Man always dreamed of?}] input_ids tokenizer.apply_chat_template( conversationconversation, documentsdocuments, chat_templaterag, tokenizeTrue, add_generation_promptTrue, return_tensorspt, ).to(device) # 生成回复 generated_tokens model.generate( input_ids, max_new_tokens100, do_sampleTrue, temperature0.3, ) # 解码生成文本并输出 generated_text tokenizer.decode(generated_tokens[0]) print(generated_text)从 tokenization_utils_base.py 的文档可知documents同样遵循模板不支持 RAG 则该参数无效的约定且官方推荐每个文档使用title与text两个键。多模板模型如 Command-R 系列会将chat_templaterag解析为模板字典中名为rag的条目解析逻辑见 tokenization_utils_base.py。五、小结与进一步阅读通过apply_chat_template的tools与documents参数可以在不手写 Jinja 模板的前提下为对话模型注入函数调用能力与检索上下文形成用户提问 → 模型发起工具调用 → 回填结果 → 继续对话以及注入文档 → 基于文档作答两条完整链路。编写工具时遵循签名含类型提示 Google 风格 docstring的规范即可获得高质量 JSON Schema复杂场景可借助get_json_schema预览或手工构造 schema。相关可深入阅读的资料聊天模板整体概念与编写方式docs/source/en/chat_templating_writing.md聊天内容模式docs/source/en/chat_content_patterns.md模型响应解析docs/source/en/chat_response_parsing.md核心实现tokenization_utils_base.py 与 chat_template_utils.py【免费下载链接】transformers Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.项目地址: https://gitcode.com/GitHub_Trending/tra/transformers创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

关于本文作者

来自尧图内容编辑团队

尧图内容编辑团队 内容团队

尧图内容编辑团队

本文由尧图网络内容编辑团队执笔。团队由资深项目经理、前端工程师与设计师组成,所有内容均来自亲手交付的真实项目,先讲清问题、再给出可落地的解法。尧图深耕北京网站建设十年,服务过京华建材集团、智造科技等各行业客户,把一线经验沉淀为可复用的行业观察。

  • 十年建站经验,覆盖建材、制造、服务、文创等
  • 项目经理把关选题与事实准确性
  • 工程师与设计师联合撰写专业细节
  • 统一编辑规范,保证文风与排版一致
  • 每月复盘转化数据,迭代选题方向

延伸阅读

相关资讯与近期热门内容

深度阅读推荐

建站决策前值得细读的三篇

网站改版的5个关键决策
2024-08-12

网站改版的5个关键决策

什么时候该改版、改到什么程度、如何避免流量掉光,京华建材集团改版复盘给出答案。

获取专属建站方案

看完文章,把您的行业与预算告诉我们,免费获取一份量身定制的官网建设方案与报价。

立即免费咨询