使用LLaMA-Factory微调大模型的function calling能力

发布时间:2025-08-07 18:32:50编辑:Run阅读(38)

    引言:

    Agent(智能体)是当今 LLM(大模型)应用的热门话题[1],通过任务分解(task planning)、工具调用(tool using)和多智能体协作(multi-agent cooperation)等途径,LLM Agent 有望突破传统语言模型能力界限,体现出更强的智能水平。在这之中,调用外部工具解决问题成为 LLM Agent 必不可缺的一项技能,模型根据用户问题从工具列表中选择恰当的工具,同时生成工具调用参数,综合工具返回结果和上下文信息总结出答案。通过调用外部工具,LLM 能够获取到实时、准确的知识,大大降低了生成中的幻觉(hallucination)现象,使 LLM 的任务解决能力得到长足的提升。工具调用能力的获得离不开模型微调,尽管使用 ReAct 提示或其他预训练模型也能实现类似效果,但对于定制化或更加广泛的工具,对模型做进一步微调能有效地提升工具使用能力。本文将会使用 LLaMA Factory 的 Agent Tuning 功能训练出自己专属的 LLM Agent。

    如何使用大模型的函数调用(function calling)功能,这样就能让大模型调用成千上万的工具API,赋予大模型更多的外部知识,使得大模型能力变得更加强大。


    训练框架:

    LLaMA Factory 是一个涵盖预训练、指令微调到 RLHF 阶段的开源全栈大模型微调框架,具备高效、易用、可扩展的优点,配备有零代码可视化的一站式网页微调界面 LLaMA Board。


    模型与数据:

    基座模型选择的是:通义千问3-4B, 数据集可以在HuggingFace找到function calling相关的数据集,盖数据集包含用户(human)、模型(gpt)、工具调用(function_call)和工具调用结果(observation)四种不同角色,以及工具列表(tools)字段。下面是数据集中的一个样本示例:

    {
      "conversations": [
        {
          "from": "human",
          "value": "I saw a dress that I liked. It was originally priced at $200 but it's on sale for 20% off. Can you tell me how much it will cost after the discount?"
        },
        {
          "from": "function_call",
          "value": "{\"name\": \"calculate_discount\", \"arguments\": {\"original_price\": 200, \"discount_percentage\": 20}}"
        },
        {
          "from": "observation",
          "value": "{\"discounted_price\": 160}"
        },
        {
          "from": "gpt",
          "value": "The dress will cost you $160 after the 20% discount."
        }
      ],
      "tools": "[{\"name\": \"calculate_discount\", \"description\": \"Calculate the discounted price\", \"parameters\": {\"type\": \"object\", \"properties\": {\"original_price\": {\"type\": \"number\", \"description\": \"The original price of the item\"}, \"discount_percentage\": {\"type\": \"number\", \"description\": \"The percentage of discount\"}}, \"required\": [\"original_price\", \"discount_percentage\"]}}]"
    }

    模型下载:git clone https://www.modelscope.cn/Qwen/Qwen3-4B.git

    image.png

    数据集下载:

    https://huggingface.co/datasets/llamafactory/glaive_toolcall_zh

    https://huggingface.co/datasets/llamafactory/alpaca_gpt4_zh

    https://huggingface.co/datasets/SDUIRLab/fuzi-mingcha-v1_0-data/blob/main/oaast_sft_zh.json
    image.png


    环境准备:

    LLaMA Factory的环境搭建参考文章:

    LLaMA Factory本地部署https://py3study.com/Article/details/id/20107.html


    训练流程:

    启动LLaMA-Factory webui,执行命令:llamafactory-cli webui

    image.png

    打开浏览器,在地址栏输入 http://127.0.0.1:7860/  进入 LLaMA Board。

    image.png





关键字

上一篇: 自定义搭建一个Agent系统

下一篇: 没有了