Skip to content

Tool Calling 入门 #96

@QingyaFan

Description

@QingyaFan

tool-calling与function-calling

functions have been deprecated, and tools are the way forward.
Tools: A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. 1

Tool/Function Calling 都是连接模型和外部的数据、系统的桥梁。2 简单来说,function是tool的子集,模型除了 function-calling,还可以 api-calling(现在叫 GPT Actions 3),等等,function、api都被统一在tool 的概念之下。很多时候,Tool Calling和Function Calling并没有明显的区分,例如在LangChain中,基本指的是一件事。

API Calling:

GPT Actions provide a viable alternative: developers can now simply describe the schema of an API call, configure authentication, and add in some instructions to the GPT, and ChatGPT provides the bridge between the user's natural language questions and the API layer. 3

Tool Calling和Function Calling详细对比:

特性 Tool Calling Function Calling
目标 调用通用工具、外部接口 调用明确定义的代码函数
灵活性 高:可以调用多种工具,可能涉及多种协议 中:依赖预定义函数,受限于实现
实现方式 使用 API、CLI、插件等多种形式 主要是结构化数据的函数接口
适用场景 复杂、多工具协作场景 任务明确、需要函数式抽象的场景

OpenAI 兼容的 Tool Calling

各家模型提供商有不同的工具调用规范,例如调用模型接口时传入的tools参数,以及生成的工具调用的响应。在这两方面,anthropic和openai就有不同。

因为社区的开源模型一般会遵循openai的标准,推理引擎会提供openai api兼容的web服务,所以,这里咱们主要讲openai的工具调用。

image

函数调用并不是模型调用函数,而是模型根据 user query 生成函数调用的函数名和参数,再由模型调用者决定是否执行函数,执行完成后还需要把执行结果feed back给模型,最后的模型输出才是最终结果。4

tool-calling请求

那么模型怎么知道都有哪些函数可以调用呢?我们需要在请求API的参数中指定:

completion = client.chat.completions.create(
    model="qwen2.5-72b-instruct-quantized.w8a8",
    messages=[{"role": "user", "content": query}],
    tools=tools,
)

tools 就是指定的在这次API调用中可以使用的工具描述,model 根据提供的tools来选择使用哪一个或多个解决用户提出的问题。描述规范如下:

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string"}
                },
            },
        },
    }
]

chat complete API 只支持 function 类型的工具,assistants API 支持 [built-in tools](https://platform.openai.com/docs/assistants/tools)

tool-calling响应

请求 tool calling 会有几种情况,例如超出model的max input tokens数量,或者响应内容非法。我们需要判断是否正常响应了 tool_calls 类型的内容:

finished_reason = completion['choices'][0]['message']['finish_reason']

if finished_reason == "length":
    print("Error: The conversation was too long for the context window.")
if finished_reason == "content_filter":
    print("Error: The content was filtered due to policy violations.")

if finished_reason == "tool_calls" or (our_api_request_forced_a_tool_call and finished_reason == "stop"):
    print("model made a tool call")
elif finished_reason == "stop":
    print("model responded directly to user")
else:
    print("Unexpected finish reason:", finished_reason)

todo 2567

prompt对工具调用的影响

可以用few-shot prompt来加强tool calling的效果。 8

最佳实践

When designing tools to be used by a model, it is important to keep in mind that: 9

  • Models that have explicit tool-calling APIs will be better at tool calling than non-fine-tuned models.
  • Models will perform better if the tools have well-chosen names and descriptions.
  • Simple, narrowly scoped tools are easier for models to use than complex tools.
  • Asking the model to select from a large list of tools poses challenges for the model.

OpenAI的文档里也给了几个最佳实践10

  • 单个调用传给model的tools数量要少于 20,这样model更能准确命中需要调用的函数。
  • 微调模型可提高function calling的精度,尤其tools很大量的情况下。

Footnotes

  1. https://community.openai.com/t/functions-vs-tools-what-is-the-difference/603277/3

  2. https://platform.openai.com/docs/guides/function-calling 2

  3. https://platform.openai.com/docs/actions/introduction#how-gpt-actions-work 2

  4. https://platform.openai.com/docs/guides/function-calling#lifecycle

  5. https://docs.vllm.ai/en/latest/getting_started/examples/openai_chat_completion_client_with_tools.html

  6. https://cookbook.openai.com/examples/how_to_call_functions_with_chat_models

  7. https://huggingface.co/docs/transformers/main/en/chat_templating#advanced-tool-use--function-calling

  8. https://python.langchain.com/docs/how_to/function_calling/?utm_source=chatgpt.com#few-shot-prompting

  9. https://python.langchain.com/docs/concepts/tool_calling/

  10. https://platform.openai.com/docs/guides/function-calling#best-practices

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions