help.khb.com 对话模型 Function Calling

Function Calling

Function Calling 函数调用能力让模型能够按照预定义的结构化输出 JSON 字符串,实现对外部工具和 API 的调用,完成更复杂的任务。本指南将帮助您了解 Function Calling 的工作原理与使用方式。

1. 工作原理

Function Calling 主要分为以下几步:

  1. 开发者向模型提供一组预定义的工具函数 (tools),每个函数包含名称、描述和参数 schema。
  2. 模型根据用户问题,判断是否需要调用某个/某些工具,并以 JSON 格式返回调用参数。
  3. 开发者解析参数,在自己环境执行该函数 (例如查询数据库、调用外部 API)。
  4. 将执行结果回传给模型。
  5. 模型结合工具返回结果,生成最终答复。

2. 基本请求结构

from openai import OpenAI
import json

client = OpenAI(
    api_key="YOUR_KHB_API_KEY",
    base_url="https://khb.net.cn/v1"
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "查询指定城市的天气",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "城市名称,如 北京"}
                },
                "required": ["city"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="Qwen/Qwen2.5-72B-Instruct",
    messages=[
        {"role": "user", "content": "北京今天天气怎么样?"}
    ],
    tools=tools,
    tool_choice="auto"
)

tool_call = response.choices[0].message.tool_calls[0]
args = json.loads(tool_call.function.arguments)
print("模型想调用:", tool_call.function.name, "参数:", args)

3. 完整对话流程

import json
from openai import OpenAI

client = OpenAI(
    api_key="YOUR_KHB_API_KEY",
    base_url="https://khb.net.cn/v1"
)

def get_weather(city: str) -> str:
    # 实际场景中,这里应调用真实的天气 API
    return f"{city} 当前晴,温度 25°C,湿度 40%"

messages = [{"role": "user", "content": "北京今天天气怎么样?"}]
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "查询指定城市的天气",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string"}
                },
                "required": ["city"]
            }
        }
    }
]

# 第一次调用
response = client.chat.completions.create(
    model="Qwen/Qwen2.5-72B-Instruct",
    messages=messages,
    tools=tools,
    tool_choice="auto"
)

msg = response.choices[0].message
messages.append(msg)

# 如果模型决定调用工具
if msg.tool_calls:
    for tool_call in msg.tool_calls:
        args = json.loads(tool_call.function.arguments)
        result = get_weather(**args)
        messages.append({
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": result
        })

# 第二次调用:模型结合工具结果生成最终答复
response = client.chat.completions.create(
    model="Qwen/Qwen2.5-72B-Instruct",
    messages=messages
)
print(response.choices[0].message.content)

4. 最佳实践

  • 清晰的函数描述:为每个工具提供简洁明确的描述,有助于模型判断何时调用。
  • 严格的参数 schema:使用 JSON Schema 描述参数,确保模型输出符合预期。
  • 工具调用上限:避免在一次请求中提供过多工具,可能影响模型判断的准确性。
  • 错误处理:工具执行失败时,应将错误信息回传给模型,让模型决定后续行为。

5. 支持的模型

KHB 算力平台上的多数主流大语言模型均支持 Function Calling 能力,具体可在 模型广场 查询。

Related Post