likes
comments
collection
share

LLM代码实现-Qwen(Function Calling)

作者站长头像
站长
· 阅读数 8

简介

Function Calling 是一种让 Chat Completion 模型调用外部函数的能力,可以让模型不仅仅根据自身的数据库知识进行回答,而是可以额外挂载一个函数库,然后根据用户提问去函数库检索,按照实际需求调用外部函数并获取函数运行结果,再基于函数运行结果进行回答,或者是通过函数调用来调用工具。

Qwen 官方给出的 Function Calling 方法是基于 openai 接口的,这篇文章就从如何利用 Qwen 仿 OpenAI 接口开始写起。

OpenAI_API

在 Qwen 官方给出的代码中有一个 openai_api.py 脚本,可以在 _get_args() 函数中对参数进行配置后运行 (主要需要修改模型路径)。

def _get_args():
    parser = ArgumentParser()
    parser.add_argument(
        "-c",
        "--checkpoint-path",
        type=str,
        default="qwen/Qwen-1_8B-Chat",
        help="Checkpoint name or path, default to %(default)r",
    )
    parser.add_argument(
        "--api-auth", help="API authentication credentials"
    )
    parser.add_argument(
        "--cpu-only", action="store_true", help="Run demo with CPU only"
    )
    parser.add_argument(
        "--server-port", type=int, default=8000, help="Demo server port."
    )
    parser.add_argument(
        "--server-name",
        type=str,
        default="0.0.0.0",
        help="Demo server name. Default: 127.0.0.1, which is only visible from the local computer."
             " If you want other computers to access your server, use 0.0.0.0 instead.",
    )
    parser.add_argument("--disable-gc", action="store_true",
                        help="Disable GC after each response generated.")

    args = parser.parse_args()
    return args

修改完成后运行:

python openai_api.py

接着可以运行以下代码以调用接口进行对话:

import openai
import json


openai.api_base = 'http://localhost:8000/v1'
openai.api_key = 'none'


def call_qwen(messages):
    response = openai.ChatCompletion.create(model='Qwen', messages=messages)
    response = response.choices[0]['message']
    response = json.loads(json.dumps(response, ensure_ascii=False))
    
    print('input:', messages)
    print('output:', response)
    
    return response


if __name__ == '__main__':
    messages = [{'role': 'user', 'content': '你好'}]
    response = call_qwen(messages)

Function Calling

首先介绍一下 Function Calling 的具体流程。

  1. 使用用户查询和函数参数中定义的一组外部函数库。
  2. 模型可以选择调用任意外部函数;如果是这样,内容将是符合自定义架构的字符串化 JSON 对象(注意:模型可能会生成无效的 JSON 或幻觉参数)。
  3. 在代码中将字符串解析为 JSON,并使用提供的参数调用函数(如果存在)。
  4. 通过将函数响应追加为新消息来再次调用模型,并让模型将结果汇总返回给用户。

外部函数库

首先我们需要定义一个外部函数库,这个函数库是一个列表,可以添加多个函数,列表中每个函数都为 json 格式,每个函数格式固定,以下是一个关于控制开关灯光的函数例子。

functions = [
    {
        "name_for_human": "灯光控制",
        "name_for_model": "contral",
        "description_for_model": "灯光控制可以帮助用户开关灯"
                                 + " Format the arguments as a JSON object.",
        "parameters": [
            {
                "name": "switch",
                "description": "用于控制灯的开关,若为True则为开灯,若为false则为关灯",
                "required": True,
                "schema": {"type": "bool"},
            }
        ],
    }
]

# 各参数作用

# "name_for_human":函数名字(对人类)
# "name_for_model":函数名字(对模型)
# "description_for_model":描述函数的作用,让模型能够判断什么时候调用这个函数
# "parameters":返回结果中的参数,该键对应的值为一个列表,可以返回多个参数
#     "name":参数的名字
#     "description":参数的描述,用于让模型判断这个参数填入什么
#     "required":这个参数是否是必要的
#     "schema":可以指定这个参数的数据类型

调用函数库方式如下,这里创建了一个 contral 函数假装调用了接口来进行开关灯操作:

import openai
import json


openai.api_base = "http://localhost:8006/v1"
openai.api_key = "none"


def contral(response):
    if response.choices[0].message.function_call:
        result = eval(response.choices[0].message.function_call.arguments)
        switch = "开灯" if result["switch"] else "关灯"

        print(switch)


def call_qwen(messages, functions=None):
    print(messages)
    if functions:
        response = openai.ChatCompletion.create(
            model="Qwen", messages=messages, functions=functions
        )
    else:
        response = openai.ChatCompletion.create(model="Qwen", messages=messages)

    print(response)
    result = response.choices[0].message.function_call
    if result:
        if result.name == "contral":
            contral(response)

    print(response.choices[0].message.content)
    return response


if __name__ == "__main__:
    functions = [
        {
            "name_for_human": "灯光控制",
            "name_for_model": "contral",
            "description_for_model": "灯光控制可以帮助用户开关灯"
                                     + " Format the arguments as a JSON object.",
            "parameters": [
                {
                    "name": "switch",
                    "description": "用于控制灯的开关,若为True则为开灯,若为false则为关灯",
                    "required": True,
                    "schema": {"type": "bool"},
                }
            ],
        }
    ]

    messages = [{"role": "user", "content": "帮我开一下灯"}]
    call_qwen(messages, functions)

返回结果如下:

# messages
[{'role': 'user', 'content': '帮我开一下灯'}]

# response
{
  "model": "Qwen",
  "object": "chat.completion",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Thought: \u9700\u8981\u4f7f\u7528\u706f\u5149\u63a7\u5236API\u6765\u5b9e\u73b0\u5f00\u706f\u64cd\u4f5c",
        "function_call": {
          "name": "contral",
          "arguments": "{\"switch\": True}"
        }
      },
      "finish_reason": "function_call"
    }
  ],
  "created": 1706839240
}

# switch
开灯

# response.choices[0].message.content(json 会导致"content"中的中文会变为Unicode,取出来后就是正常的)
Thought: 需要使用灯光控制API来实现开灯操作

Function Calling 是一种非常有用的功能,可以让Chat Completion模型更加灵活地应对各种场景比如自动发邮件、控制机械臂、上网搜索用户提问中的相关信息后回答,调用其他厂家的 api 接口……通过调用外部函数进行输出格式化,可以让Chat Completion模型更加贴合实际需求,并提供更加优质、高效、个性化的服务。怎么用就取决于大家的想象力了。