PHP无法直接调用Qwen的函数调用能力,只能通过DashScope等支持OpenAI兼容接口的API服务间接使用;需配置tools、tool_choice,检查模型是否支持function calling,并安全解析tool_calls响应。

PHP 无法直接调用 Qwen 的函数调用(Function Calling)能力,因为 Qwen 的 function calling 是模型侧的推理机制,不是 HTTP 接口或 SDK 提供的可编程接口;你实际能对接的,是「带 function calling 能力的 API 服务」——比如 DashScope、OpenRouter 或自部署的 vLLM + OpenAI 兼容层,它们把 Qwen 模型封装成支持 tools 参数的 OpenAI-style 接口。
PHP 调用 Qwen function calling 必须走 OpenAI 兼容 API
Qwen 官方不提供原生 PHP SDK,也不开放底层 function calling 的 token-level 控制。所有“让 Qwen 执行函数”的行为,都依赖上游服务在请求中解析 tools、tool_choice,并在响应中返回 tool_calls 字段。PHP 做的只是标准 HTTP 请求和 JSON 解析。
- 必须使用支持 OpenAI v1/chat/completions 格式的后端(如 DashScope 的
/v1/services/aigc/text-generation/generation启用enable_function_calling) - 请求体必须包含
tools数组(每个元素含type、function,其中function.name和function.parameters需符合 JSON Schema) - 不能只传
functions(旧版 OpenAI 参数),Qwen 系列模型后端普遍只认tools - 响应里若出现
finish_reason: "tool_calls",说明模型触发了函数调用,此时要提取message.tool_calls并执行对应逻辑
常见错误:PHP 发起请求后收不到 tool_calls
不是 PHP 写错了,而是配置或模型选择出了问题。最常踩的坑有三个:
- 用了 Qwen2-7B-Instruct 这类基础对话模型——它根本不支持 function calling,必须换用明确标注「Function Calling」的版本,例如
qwen2.5-72b-instruct(DashScope)或qwen2.5-32b-instruct(Fireworks) -
tool_choice设成了"none"或没传,导致服务跳过工具选择逻辑;应设为"auto"或指定{"type": "function", "function": {"name": "xxx"}} - PHP cURL 未设置
Content-Type: application/json,或json_encode()后没检查是否输出了null(比如parameters里用了 PHP 引用或不可序列化对象) - 某些平台(如早期 DashScope)要求额外 header:
X-DashScope-OssResourceResolve: true,否则tools被静默忽略
PHP 示例:发送带 tools 的请求并安全提取 tool_calls
以下代码片段聚焦关键路径,省略异常重试和日志,仅展示结构正确性:
立即学习“PHP免费学习笔记(深入)”;
$payload = [
'model' => 'qwen2.5-32b-instruct',
'messages' => [['role' => 'user', 'content' => '查上海今天天气']],
'tools' => [[
'type' => 'function',
'function' => [
'name' => 'get_weather',
'description' => '获取指定城市的实时天气',
'parameters' => [
'type' => 'object',
'properties' => ['city' => ['type' => 'string']],
'required' => ['city']
]
]
]],
'tool_choice' => 'auto'
];
$json = json_encode($payload, JSON_UNESCAPED_UNICODE);
$response = file_get_contents('https://api.fireworks.ai/inference/v1/chat/completions', [
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/json\r\nAuthorization: Bearer {$api_key}",
'content' => $json
]
]);
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new Exception('Invalid JSON response');
}
// 安全提取 tool_calls(注意:可能不存在,也可能为 null)
$toolCalls = $data['choices'][0]['message']['tool_calls'] ?? null;
if (is_array($toolCalls) && !empty($toolCalls)) {
foreach ($toolCalls as $call) {
if ($call['function']['name'] === 'get_weather') {
$args = json_decode($call['function']['arguments'], true);
// 执行真实天气查询逻辑
$weather = get_weather($args['city']);
}
}
}
重点:不要假设 tool_calls 一定存在;$call['function']['arguments'] 是字符串,必须 json_decode;Qwen 输出的 JSON 可能带多余空格或换行,json_decode 第二个参数设为 true 更稳妥。
真正难的不是 PHP 怎么发请求,而是确认你用的 endpoint 是否真把 Qwen 的 function calling 能力打开了——很多文档写得模糊,得自己抓包看响应字段,或者直接 curl 测试原始 JSON 返回。



















