FunctionCall检查

要验证一个大语言模型(LLM)是否支持 LangChain 的 Tool/Function 调用,可以按照以下步骤进行。这个过程包括查看模型文档、尝试绑定工具函数、发送测试请求以及分析响应结果。以下是详细的步骤和方法:

1. 了解 LangChain 的 Tool/Function 调用机制

首先,确保你了解 LangChain 中 Tool/Function 调用的基本概念。LangChain 允许你将自定义的函数(工具)绑定到语言模型,使其能够在对话过程中调用这些函数来执行特定任务。例如,工具函数可以用来查询数据库、调用外部 API 或执行其他自定义逻辑。

2. 查阅模型的官方文档和 API 说明

大多数支持 Tool/Function 调用的模型会在其官方文档中明确提到这一功能。你需要:

  • 查看 API 文档:查找是否有关于 Function Calls、Tool Integration 或类似功能的说明。
  • 检查支持的参数:例如,OpenAI 的 GPT-4 模型支持 functions 参数,用于定义和调用函数。查看你的模型是否有类似的参数。

3. 尝试绑定工具函数并观察结果

你可以编写一个简单的测试代码,尝试将工具函数绑定到模型,并调用它们。以下是一个示例:

from langchain import ChatOpenAI, Tool, AgentExecutor
from langchain.prompts import ChatPromptTemplate
from langchain.output_parsers import JsonOutputParser

# 定义一个简单的工具函数
def greeting(name: str):
    '''向朋友致欢迎语'''
    return f"你好啊, {name}"

# 创建 LangChain 工具
greeting_tool = Tool(
    name="greeting",
    func=greeting,
    description="向朋友致欢迎语"
)

# 初始化模型(以 OpenAI 为例)
model = ChatOpenAI(model_name="gpt-4", temperature=0)

# 检查模型是否支持工具绑定
try:
    agent = AgentExecutor.from_agent_and_tools(
        agent=... ,  # 根据具体情况选择合适的 Agent
        tools=[greeting_tool],
        verbose=True
    )
    print("模型支持 Tool/Function 调用。")
except Exception as e:
    print(f"模型不支持 Tool/Function 调用: {e}")

注意事项:

  • 根据你使用的具体模型和 LangChain 版本,初始化和绑定工具的方式可能有所不同。
  • 某些模型可能需要特定的权限或配置才能支持 Tool/Function 调用。

4. 发送测试请求并分析响应

如果模型的文档没有明确说明是否支持 Tool/Function 调用,可以通过实际测试来验证。

示例代码:
from langchain import OpenAI, Tool, AgentExecutor
from langchain.prompts import ChatPromptTemplate
from langchain.output_parsers import JsonOutputParser

# 定义工具函数
def greeting(name: str):
    '''向朋友致欢迎语'''
    return f"你好啊, {name}"

# 创建 LangChain 工具
greeting_tool = Tool(
    name="greeting",
    func=greeting,
    description="向朋友致欢迎语"
)

# 初始化模型
model = OpenAI(model_name="gpt-4", temperature=0)

# 定义提示词模板
prompt = ChatPromptTemplate.from_messages(
    [("system",
      """
      您是一名助理,可以使用以下工具。以下是工具的名称和说明:
      工具名称:greeting, 参数:name(str类型),此工具的用途说明:向朋友致欢迎语
      根据用户输入,返回要使用的工具的名称和输入。以包含 "name" 和 "arguments" 键的 JSON blob 形式返回响应。
      """),
     ("user", "{input}")]
)

# 构建链
chain = prompt | model | JsonOutputParser()

# 发送测试请求
response = chain.invoke("我是你的新朋友 —— 张三")
print(response)  # 期望输出:{'name': 'greeting', 'arguments': {'name': '张三'}}

# 执行工具函数
if 'name' in response and 'arguments' in response:
    tool_name = response['name']
    args = response['arguments']
    if tool_name == 'greeting':
        result = greeting(**args)
        print(result)  # 期望输出:你好啊, 张三

解析响应:

  • 如果模型支持 Tool/Function 调用,应该能够识别并返回工具名称及参数。
  • 如果不支持,模型可能会忽略工具调用或返回默认的对话内容。

5. 检查模型的响应元数据

某些 API 会在响应中包含元数据,指示是否尝试调用了函数。例如,OpenAI 的 API 会在响应中包含 function_call 字段。

response = model_with_tool.invoke("你好,我是你的新朋友")
print(response.additional_kwargs.get('function_call'))
  • 如果 function_call 包含函数名称和参数,说明模型尝试调用了工具函数。
  • 如果 function_call 为空或不存在,说明模型未支持工具调用。

6. 使用模型提供的示例或测试用例

一些模型提供了示例代码或测试用例,展示如何使用 Tool/Function 调用。参考这些示例可以帮助你更好地理解和验证模型的支持情况。

7. 咨询模型提供商或社区

如果以上方法无法确定模型是否支持 Tool/Function 调用,可以:

  • 联系模型提供商的技术支持:获取官方确认。
  • 查阅社区论坛或讨论组:例如,LangChain 的 GitHub 仓库、OpenAI 社区等,查看其他用户的经验和建议。

8. 总结

通过以上步骤,你可以系统地验证一个大模型是否支持 LangChain 的 Tool/Function 调用。关键在于结合查看官方文档、编写测试代码、分析响应结果以及寻求社区帮助等多种方法,全面了解模型的功能和限制。

如果在验证过程中遇到具体问题或错误,欢迎进一步交流,我们可以一起探讨解决方案。

官方文档

当然,我很高兴为您详细讲解这份关于 vLLM 的文档。这份文档主要介绍了如何使用 vLLM 进行大型语言模型(LLM)的推理和服务,以及如何实现函数调用(Function Calling)来增强模型的功能。下面,我将逐步解析文档中的各个部分,帮助您全面理解其内容。


1. 什么是 vLLM

vLLM 是一个快速且易于使用的库,专门用于大型语言模型(LLM)的推理和服务。它的主要特点包括:

  • 高效:优化了推理速度,适用于需要快速响应的应用场景。
  • 易用:使用与 transformers 库兼容的分词器(Tokenizer),简化了输入的准备工作。
  • 扩展性:自 v0.6.0 版本起,支持工具调用(Tool Calls),可以自动解析生成的工具调用(如果格式被支持)。

关键特性

  • Tokenizer 兼容:使用 transformers 库中的分词器,无需担心输入格式的问题。
  • 自动解析工具调用:内置辅助函数,能够自动解析支持格式的工具调用,简化开发流程。

2. 工具支持

v0.6.0 版本开始,vLLM 就支持工具调用。工具调用使得模型能够调用外部函数或API,以获取更准确或最新的信息。

安装

确保安装了支持工具使用的版本,例如文档中提到的 v0.6.1.post2。您可以通过以下命令安装或更新 vLLM:

pip install vllm==0.6.1.post2

3. 使用 vLLM 的 OpenAI 兼容 API

本文档主要以 v0.6.1.post2 版本为例,介绍如何使用 vLLM 的 OpenAI 兼容 API,并结合 OpenAI Python 库的 API 客户端。

准备工作

针对 Qwen2.5 模型,分词器配置文件(tokenizer_config.json)已包含对 Hermes 风格工具调用的支持。因此,您只需启动一个与 OpenAI 兼容的 API 服务:

vllm serve Qwen/Qwen2.5-7B-Instruct --enable-auto-tool-choice --tool-call-parser hermes

这里的命令参数说明:

  • Qwen/Qwen2.5-7B-Instruct:指定使用的模型。
  • --enable-auto-tool-choice:启用自动工具选择。
  • --tool-call-parser hermes:指定工具调用解析器为 Hermes 风格。

输入准备

输入与准备代码中的输入相同:

tools = TOOLS
messages = MESSAGES[:]

初始化客户端

使用 OpenAI Python 库初始化 API 客户端:

from openai import OpenAI

openai_api_key = "EMPTY"  # 这里使用空字符串作为 API 密钥
openai_api_base = "http://localhost:8000/v1"  # vLLM 服务的本地地址

client = OpenAI(
    api_key=openai_api_key,
    base_url=openai_api_base,
)

model_name = "Qwen/Qwen2.5-7B-Instruct"  # 模型名称
  • api_key:由于使用本地服务,API 密钥设置为空。
  • api_base:指定 vLLM 服务的地址。

4. 工具调用和结果处理

创建聊天完成(Chat Completion)

通过调用 create 方法,向模型发送请求:

response = client.chat.completions.create(
    model=model_name,
    messages=messages,
    tools=tools,
    temperature=0.7,
    top_p=0.8,
    max_tokens=512,
    extra_body={
        "repetition_penalty": 1.05,
    },
)
  • model:使用的模型名称。
  • messages:对话历史消息。
  • tools:可用的工具列表。
  • temperaturetop_pmax_tokens:生成文本的参数。
  • extra_body:额外的参数,如重复惩罚。

解析工具调用

vLLM 会自动解析工具调用,响应中的主要字段(response.choices[0])可能如下所示:

Choice(
    finish_reason='tool_calls', 
    index=0, 
    logprobs=None, 
    message=ChatCompletionMessage(
        content=None, 
        role='assistant', 
        function_call=None, 
        tool_calls=[
            ChatCompletionMessageToolCall(
                id='chatcmpl-tool-924d705adb044ff88e0ef3afdd155f15', 
                function=Function(arguments='{"location": "San Francisco, CA, USA"}', name='get_current_temperature'), 
                type='function',
            ), 
            ChatCompletionMessageToolCall(
                id='chatcmpl-tool-7e30313081944b11b6e5ebfd02e8e501', 
                function=Function(arguments='{"location": "San Francisco, CA, USA", "date": "2024-10-01"}', name='get_temperature_date'), 
                type='function',
            ),
        ],
    ), 
    stop_reason=None,
)

关键点

  • finish_reason'tool_calls' 表示模型生成了工具调用。
  • tool_calls:包含一个或多个工具调用,每个调用包括:
    • id:工具调用的唯一标识。
    • function:被调用的函数名称及其参数。
    • type:调用类型,通常为 'function'

注意:函数参数是 JSON 格式的字符串,遵循 Qwen-Agent 的格式,而与 transformers 和 Ollama 不同。

处理工具调用

尽管 vLLM 能自动解析工具调用,但在生产环境中,可能会遇到生成的工具调用格式不正确的情况。因此,建议在代码中手动解析工具调用以确保稳定性。

示例代码
messages.append(response.choices[0].message.model_dump())

if tool_calls := messages[-1].get("tool_calls", None):
    for tool_call in tool_calls:
        call_id: str = tool_call["id"]
        if fn_call := tool_call.get("function"):
            fn_name: str = fn_call["name"]
            fn_args: dict = json.loads(fn_call["arguments"])
        
            fn_res: str = json.dumps(get_function_by_name(fn_name)(**fn_args))

            messages.append({
                "role": "tool",
                "content": fn_res,
                "tool_call_id": call_id,
            })
解释
  1. 添加模型生成的消息

    messages.append(response.choices[0].message.model_dump())
    

    将模型生成的消息添加到消息列表中。

  2. 检查是否有工具调用

    if tool_calls := messages[-1].get("tool_calls", None):
    

    如果最新的消息包含 tool_calls,则进行处理。

  3. 遍历每个工具调用

    for tool_call in tool_calls:
        call_id = tool_call["id"]
        if fn_call = tool_call.get("function"):
            fn_name = fn_call["name"]
            fn_args = json.loads(fn_call["arguments"])
            
            fn_res = json.dumps(get_function_by_name(fn_name)(**fn_args))
    
            messages.append({
                "role": "tool",
                "content": fn_res,
                "tool_call_id": call_id,
            })
    
    • 提取调用 ID、函数名称和参数
    • 调用实际的函数get_function_by_name)并获取结果。
    • 将工具调用结果添加到消息列表中,以便后续生成最终响应。

重要提示

  • 工具调用 ID:OpenAI API 使用 tool_call_id 来标识工具调用与结果之间的关系,确保结果能够正确关联到对应的调用。

5. 最终响应

在处理完所有工具调用并将结果添加到消息列表后,再次调用 API 以生成最终响应:

response = client.chat.completions.create(
    model=model_name,
    messages=messages,
    tools=tools,
    temperature=0.7,
    top_p=0.8,
    max_tokens=512,
    extra_body={
        "repetition_penalty": 1.05,
    },
)

messages.append(response.choices[0].message.model_dump())

最终响应的内容(response.choices[0].message.content)示例:

The current temperature in San Francisco is approximately 26.1°C. For tomorrow, the forecasted temperature is around 25.9°C.

6. 比较不同框架

文档通过一个表格对比了 OpenAI APIHugging Face TransformersOllamavLLMQwen-Agent 等不同框架在函数调用(Function Calling)方面的特点。以下是对表格内容的详细解释:

项目OpenAI APIHugging Face transformersOllamavLLMQwen-Agent
类型HTTP APIPython LibraryHTTP APIHTTP APIPython Library
推理后端-PyTorchllama.cppPyTorchHTTP API
模板后端-JinjaGo text/templateJinjaPython
工具/函数工具工具工具工具函数
并行调用默认支持(可配置)默认不支持(可配置)
调用格式单一助手消息带工具调用单一助手消息带工具调用单一助手消息带工具调用单一助手消息带工具调用多个助手消息带函数调用
调用参数格式字符串对象对象字符串字符串
调用结果格式多个工具消息带内容多个工具消息带内容多个工具消息带内容多个工具消息带内容多个函数消息带内容

其他细节

  • SDK 支持

    • OpenAI API:提供 Python、Node.js、Go 和 .NET SDK,并遵循 OpenAPI 标准。
    • Ollama:提供 Python 和 Node.js SDK,具有 OpenAI 兼容的 API,可通过不同的基础 URL 访问。
    • Qwen-Agent:作为一个应用框架,可以自动调用工具,具体介绍见 Qwen-Agent 指南。
  • 模型端函数调用

    • 准确性:函数调用的准确性取决于模型选择正确的函数及其参数。这涉及到深层次和领域特定的知识,模型可能会出错或陷入循环。
    • 协议一致性:即使使用了正确的函数调用模板,模型可能仍会生成额外的文本或无效的 JSON 字符串,导致协议中断。

提升函数调用准确性的建议

  1. 提示工程(Prompt Engineering)

    • 提供更详细的函数描述。
    • 在系统消息中提供指令和示例,帮助模型理解如何使用函数。
  2. 微调(Fine-tuning)

    • 使用自有数据进行微调,以提高模型在特定任务上的表现。

7. 函数调用模板

函数调用模板设计的关键在于以下几个方面:

  1. 描述函数

    • 让模型理解函数的功能和使用方法。
  2. 提示模型

    • 告知模型函数可以被调用,以及如何生成函数调用的格式。
  3. 区分函数调用与其他文本

    • 使模型能够从生成的文本中提取函数调用。
  4. 整合函数结果

    • 使模型能够根据函数调用结果生成最终响应。

经验丰富的提示工程师可以通过上下文学习技术和代表性示例,使任何 LLM 支持函数调用,尽管在准确性和稳定性上可能有所不同,具体取决于任务的复杂性。


示例:ReAct 提示

ReAct 提示 是一种实现函数调用并加入计划(Planning)元素的方法:

  • Thought:显式的推理路径,分析函数和用户查询并进行思考。
  • Action:调用的函数及其参数。
  • Observation:函数调用的结果。
Qwen2 的 ReAct 提示变体

Qwen2 在 ReAct 提示的基础上,进行了结构化的改进,使中间文本更具结构性,类似于 LangChain 的 ReAct 模式:

Answer the following questions as best you can. You have access to the following tools:

{function_name}: Call this tool to interact with the {function_name_human_readable} API. What is the {function_name_human_readable} API useful for? {function_description} Parameters: {function_parameter_descriptions} {argument_formatting_instructions}

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{function_name},{function_name}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin!

Question: {query}
Thought: {some_text}
Action: {function_name}
Action Input: {function_arguments}
Observation: {function_results}
Final Answer: {response}
关键点
  • 无用户/助手对话结构:模板中没有显式的用户和助手角色,模型只是连续生成文本。
  • 代码处理:需要编写代码来检测模型处于哪个步骤,并在过程中添加观察结果,直到生成最终答案。

Qwen-Agent 的 ReAct Chat Agent

大多数编程接口接受消息结构,因此需要在模板和消息结构之间进行适配。Qwen-Agent 中的 ReAct Chat Agent 就是为了简化这种转换而设计的。


8. Qwen2 的函数调用模板

Qwen2 的官方函数调用模板基于 ReAct 提示格式,但在以下几个方面进行了优化:

  1. 区分关键词:如 QuestionThoughtAction 等,避免与生成文本混淆。
  2. 简化流程:使函数调用更加简洁。
  3. 支持多轮对话:适应多轮对话场景。
  4. 增加专业使用的控制:提供更多控制选项以适应特定需求。

示例模板

<|im_start|>system
{system message}

## Tools

You have access to the following tools:

### {function_name_human_readable}

{function_name}: {function_description} Parameters: {function_parameter_descriptions} {argument_formatting_instructions}

### {function_name_human_readable}

{function_name}: {function_description} Parameters: {function_parameter_descriptions} {argument_formatting_instructions}

## When you need to call a tool, please insert the following command in your reply, which can be called zero or multiple times according to your needs:

✿FUNCTION✿: The tool to use, should be one of [{function_name},{function_name}]
✿ARGS✿: The input of the tool
✿RESULT✿: Tool results
✿RETURN✿: Reply based on tool results. Images need to be rendered as ![](url)<|im_end|>
<|im_start|>user
{query}<|im_end|>
<|im_start|>assistant
✿FUNCTION✿: {function_name}
✿ARGS✿: {function_arguments}
✿RESULT✿: {function_result}
✿RETURN✿:{response}<|im_end|>

关键差异

  1. 关键词标识

    • 使用 ✿FUNCTION✿✿ARGS✿ 等特殊标识,避免与普通文本混淆。
  2. 省略 Thought

    • 省略了 Thought 步骤,可能影响某些用例的准确性,但简化了模板。
  3. 多轮对话结构

    • 使用 system-user-assistant 的消息结构,适应多轮对话。
  4. 专业控制

    • 模板中增加了对专业使用场景的支持,如并行调用等。

并行调用示例

<|im_start|>system
You are Qwen, created by Alibaba Cloud. You are a helpful assistant.

Current Date: 2024-09-30

## Tools

You have access to the following tools:

### get_current_temperature

get_current_temperature: Get current temperature at a location. Parameters: {"type": "object", "properties": {"location": {"type": "string", "description": "The location to get the temperature for, in the format \"City, State, Country\"."}, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"], "description": "The unit to return the temperature in. Defaults to \"celsius\"."}}, "required": ["location"]} Format the arguments as a JSON object.

### get_temperature_date

get_temperature_date: Get temperature at a location and date. Parameters: {"type": "object", "properties": {"location": {"type": "string", "description": "The location to get the temperature for, in the format \"City, State, Country\"."}, "date": {"type": "string", "description": "The date to get the temperature for, in the format \"Year-Month-Day\"."}, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"], "description": "The unit to return the temperature in. Defaults to \"celsius\"."}}, "required": ["location", "date"]} Format the arguments as a JSON object.

## Insert the following command in your reply when you need to call N tools in parallel:

✿FUNCTION✿: The name of tool 1, should be one of [get_current_temperature,get_temperature_date]
✿ARGS✿: The input of tool 1
✿FUNCTION✿: The name of tool 2
✿ARGS✿: The input of tool 2
...
✿FUNCTION✿: The name of tool N
✿ARGS✿: The input of tool N
✿RESULT✿: The result of tool 1
✿RESULT✿: The result of tool 2
...
✿RESULT✿: The result of tool N
✿RETURN✿: Reply based on tool results. Images need to be rendered as ![](url)<|im_end|>
<|im_start|>user
What's the temperature in San Francisco now? How about tomorrow?<|im_end|>
<|im_start|>assistant
✿FUNCTION✿: get_current_temperature
✿ARGS✿: {"location": "San Francisco, CA, USA"}
✿FUNCTION✿: get_temperature_date
✿ARGS✿: {"location": "San Francisco, CA, USA", "date": "2024-10-01"}
✿RESULT✿: {"temperature": 26.1, "location": "San Francisco, CA, USA", "unit": "celsius"}
✿RESULT✿: {"temperature": 25.9, "location": "San Francisco, CA, USA", "date": "2024-10-01", "unit": "celsius"}
✿RETURN✿: The current temperature in San Francisco is approximately 26.1°C. For tomorrow, October 1st, 2024, the forecasted temperature will be around 25.9°C.<|im_end|>

关键点

  • 并行调用:可以一次性调用多个工具,并在结果中返回多个 ✿RESULT✿
  • 系统消息中的工具定义:在 system 消息中详细定义了可用的工具及其参数。
  • 特殊符号:使用 ✿FUNCTION✿✿ARGS✿✿RESULT✿✿RETURN✿ 等特殊标识符,便于解析和处理。

9. 其他模板

对于 transformersOllama,还提供了更易于用 Jinja 或 Go 实现的模板,这些模板与 Nous Research 的 Hermes 函数调用模板类似。以下是一个示例:

示例模板

<|im_start|>system
You are Qwen, created by Alibaba Cloud. You are a helpful assistant.

Current Date: 2024-09-30

# Tools

You may call one or more functions to assist with the user query.

You are provided with function signatures within <tools></tools> XML tags:
<tools>
{"type": "function", "function": {"name": "get_current_temperature", "description": "Get current temperature at a location.", "parameters": {"type": "object", "properties": {"location": {"type": "string", "description": "The location to get the temperature for, in the format \"City, State, Country\"."}, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"], "description": "The unit to return the temperature in. Defaults to \"celsius\"."}}, "required": ["location"]}}}
{"type": "function", "function": {"name": "get_temperature_date", "description": "Get temperature at a location and date.", "parameters": {"type": "object", "properties": {"location": {"type": "string", "description": "The location to get the temperature for, in the format \"City, State, Country\"."}, "date": {"type": "string", "description": "The date to get the temperature for, in the format \"Year-Month-Day\"."}, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"], "description": "The unit to return the temperature in. Defaults to \"celsius\"."}}, "required": ["location", "date"]}}}
</tools>

For each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:
<tool_call>
{"name": <function-name>, "arguments": <args-json-object>}
</tool_call><|im_end|>
<|im_start|>user
What's the temperature in San Francisco now? How about tomorrow?<|im_end|>
<|im_start|>assistant
<tool_call>
{"name": "get_current_temperature", "arguments": {"location": "San Francisco, CA, USA"}}
</tool_call>
<tool_call>
{"name": "get_temperature_date", "arguments": {"location": "San Francisco, CA, USA", "date": "2024-10-01"}}
</tool_call><|im_end|>
<|im_start|>user
<tool_response>
{"temperature": 26.1, "location": "San Francisco, CA, USA", "unit": "celsius"}
</tool_response>
<tool_response>
{"temperature": 25.9, "location": "San Francisco, CA, USA", "date": "2024-10-01", "unit": "celsius"}
</tool_response><|im_end|>
<|im_start|>assistant
The current temperature in San Francisco is approximately 26.1°C. Tomorrow, on October 1, 2024, the temperature is expected to be around 25.9°C.<|im_end|>

关键点

  • 系统消息中的工具定义:使用 <tools></tools> 标签包含函数签名的 JSON 对象。
  • 工具调用格式:在助手消息中使用 <tool_call></tool_call> 标签包含函数名称和参数。
  • 工具响应格式:在用户消息中使用 <tool_response></tool_response> 标签包含函数结果。
  • 最终回复:助手根据工具调用结果生成最终回答。

优点

  • 结构化:使用 XML 标签明确区分工具调用和响应,便于解析。
  • 兼容性:适用于支持 XML 标签解析的框架,如 Jinja 和 Go。

10. 如何描述函数给 LLM

描述函数时,应类似于 API 文档的描述方式,确保模型能够有效解析、验证和执行生成的工具调用。推荐使用 JSON Schema 格式,因为它是有效且常见的选择。

示例

{
    "name": "get_current_temperature",
    "description": "Get current temperature at a location.",
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "The location to get the temperature for, in the format \"City, State, Country\"."
            },
            "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"],
                "description": "The unit to return the temperature in. Defaults to \"celsius\"."
            }
        },
        "required": ["location"]
    }
}

关键点

  • 函数名称和描述:清晰描述函数的功能。
  • 参数定义:详细定义每个参数的类型、描述和必要性。
  • 格式要求:指定参数的 JSON 格式,确保模型生成的调用符合规范。

11. 最后总结

函数调用的限制和优点

  1. 限制

    • 协议遵循:模型生成的文本不一定总是严格遵循协议,即使有良好的提示或模板。
    • 模板复杂性:复杂的模板可能增加出错的风险,尤其是依赖模型自身进行推理和保持轨道时。
  2. 优点

    • 增强功能:通过函数调用,模型能够访问外部工具和数据源,提升回答的准确性和实时性。
    • 灵活性:支持多种函数调用模板,适应不同的应用场景和框架。

生产环境中的最佳实践

  • 错误处理:准备好应对协议中断的情况,确保系统在出现问题时能够进行补救或恢复。
  • 模板优化:根据具体的用例,不断优化提示模板,增加更多指令或约束以提高生成质量。
  • 模型微调:如果生成质量无法通过提示工程改善,可以考虑使用自有数据进行模型微调,以提升性能。

鼓励实验

尽管函数调用有其局限性,但通过不断实验和优化,您可以显著提升模型在特定任务中的表现。享受提示工程的乐趣,并根据需求不断改进您的系统!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值