工具

Function Calling

查看 Markdown

定义模型可在对话期间调用的自定义工具。模型请求调用后,由你在本地执行并返回结果。借此可集成数据库、API 和任何外部系统。

  1. 使用名称、说明和参数 JSON Schema 定义 tool

  2. 在请求中包含 tool

  3. 模型会返回 tool_call,表示需要外部数据

  4. 在本地执行函数并返回结果

  5. 模型会根据你的结果继续执行


工作原理

Developer
Grok
执行工具
{ temp: "73", condition: "sunny" }
用户查询与工具定义
"Is it warm in Palo Alto?"
get_weather(location)
工具调用
get_weather("PA")
工具结果
...之前的所有消息
{ temp: "73", condition: "sunny" }
模型响应
"It's a nice 73 °F in PA!"

快速入门

curl https://api.x.ai/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
  "model": "grok-4.7",
  "input": [
    {"role": "user", "content": "What is the temperature in San Francisco?"}
  ],
  "tools": [
    {
      "type": "function",
      "name": "get_temperature",
      "description": "Get current temperature for a location",
      "parameters": {
        "type": "object",
        "properties": {
          "location": {"type": "string", "description": "City name"},
          "unit": {"type": "string", "enum": ["celsius", "fahrenheit"], "default": "fahrenheit"}
        },
        "required": ["location"]
      }
    }
  ]
}'

使用 Pydantic 定义 tool

使用 Pydantic 模型创建类型安全的参数 Schema:

from typing import Literal
from pydantic import BaseModel, Field
from xai_sdk.chat import tool

class TemperatureRequest(BaseModel):
    location: str = Field(description="City and state, e.g. San Francisco, CA")
    unit: Literal["celsius", "fahrenheit"] = Field("fahrenheit", description="Temperature unit")

class CeilingRequest(BaseModel):
    location: str = Field(description="City and state, e.g. San Francisco, CA")

# Generate JSON schema from Pydantic models
tools = [
    tool(
        name="get_temperature",
        description="Get current temperature for a location",
        parameters=TemperatureRequest.model_json_schema(),
    ),
    tool(
        name="get_ceiling",
        description="Get current cloud ceiling for a location",
        parameters=CeilingRequest.model_json_schema(),
    ),
]

处理 tool call

当模型要使用 tool 时,执行函数并返回结果:

import json

def get_temperature(location: str, unit: str = "fahrenheit") -> dict:
    # In production, call a real weather API
    temp = 59 if unit == "fahrenheit" else 15
    return {"location": location, "temperature": temp, "unit": unit}

def get_ceiling(location: str) -> dict:
    return {"location": location, "ceiling": 15000, "unit": "ft"}

tools_map = {
    "get_temperature": get_temperature,
    "get_ceiling": get_ceiling,
}

chat.append(user("What's the weather in Denver?"))
response = chat.sample()

# Process tool calls
if response.tool_calls:
    chat.append(response)

    for tool_call in response.tool_calls:
        name = tool_call.function.name
        args = json.loads(tool_call.function.arguments)

        result = tools_map[name](**args)
        chat.append(tool_result(json.dumps(result)))

    response = chat.sample()

print(response.content)

结合内置 tool

function calling 可与内置智能体 tool 配合使用。模型可以先使用 Web Search,再调用你的自定义函数:

from xai_sdk.chat import tool
from xai_sdk.tools import web_search, x_search

tools = [
    web_search(),                    # Built-in: runs on xAI servers
    x_search(),                      # Built-in: runs on xAI servers
    tool(                            # Custom: runs on your side
        name="save_to_database",
        description="Save research results to the database",
        parameters={
            "type": "object",
            "properties": {
                "data": {"type": "string", "description": "Data to save"}
            },
            "required": ["data"]
        },
    ),
]

chat = client.chat.create(
    model="grok-4.7",
    tools=tools,
)

混合使用 tool 时:

  • 内置 tool 会在 xAI 服务端自动执行

  • 自定义 tool 会暂停执行并返回给你处理

完整的 tool loop 示例请参阅 高级用法


tool 选择

控制模型何时使用 tool:

行为
"auto"模型决定是否调用 tool(默认)
"required"模型必须调用至少一个 tool
"none"禁用 function calling
{"type": "function", "function": {"name": "..."}}强制使用指定 tool

并行 function calling

默认启用并行函数调用,模型可在单个响应中请求多个工具调用。继续前请处理全部调用:

Python

# response.tool_calls may contain multiple calls
for tool_call in response.tool_calls:
    result = tools_map[tool_call.function.name](**json.loads(tool_call.function.arguments))
    # Append each result...

在请求中设置 parallel_tool_calls: false 可禁用。


tool Schema 参考

字段必需说明
name唯一标识符(每个请求最多 350 个工具)
descriptiontool 的作用,帮助模型决定何时使用它
parameters定义函数输入的 JSON Schema

参数 Schema

JSON

{
  "type": "object",
  "properties": {
    "location": {
      "type": "string",
      "description": "City name"
    },
    "unit": {
      "type": "string",
      "enum": ["celsius", "fahrenheit"],
      "default": "celsius"
    }
  },
  "required": ["location"]
}

某个 parameters Schema 的根必须是对象("type": "object");请将其他类型嵌套在 properties 中。根 anyOfoneOf 也可用,但每个分支本身都必须是对象,因此可定义接受多个对象变体之一的 tool:

JSON

{
  "oneOf": [
    {
      "type": "object",
      "properties": {
        "kind": { "const": "email" },
        "address": { "type": "string" }
      },
      "required": ["kind", "address"]
    },
    {
      "type": "object",
      "properties": {
        "kind": { "const": "sms" },
        "phone": { "type": "string" }
      },
      "required": ["kind", "phone"]
    }
  ]
}

完整 Vercel AI SDK 示例

Vercel AI SDK 会自动处理 tool 定义、执行和请求/响应循环:

JavaScript

import { xai } from '@ai-sdk/xai';
import { streamText, tool, stepCountIs } from 'ai';
import { z } from 'zod';

const result = streamText({
  model: xai.responses('grok-4.7'),
  tools: {
    getCurrentTemperature: tool({
      description: 'Get current temperature for a location',
      inputSchema: z.object({
        location: z.string().describe('City and state, e.g. San Francisco, CA'),
        unit: z.enum(['celsius', 'fahrenheit']).default('fahrenheit'),
      }),
      execute: async ({ location, unit }) => ({
        location,
        temperature: unit === 'fahrenheit' ? 59 : 15,
        unit,
      }),
    }),
    getCurrentCeiling: tool({
      description: 'Get current cloud ceiling for a location',
      inputSchema: z.object({
        location: z.string().describe('City and state'),
      }),
      execute: async ({ location }) => ({
        location,
        ceiling: 15000,
        ceiling_type: 'broken',
        unit: 'ft',
      }),
    }),
  },
  stopWhen: stepCountIs(5),
  prompt: "What's the temperature and cloud ceiling in San Francisco?",
});

for await (const chunk of result.fullStream) {
  switch (chunk.type) {
    case 'text-delta':
      process.stdout.write(chunk.text);
      break;
    case 'tool-call':
      console.log(`Tool call: ${chunk.toolName}`, chunk.input);
      break;
    case 'tool-result':
      console.log(`Tool result: ${chunk.toolName}`, chunk.output);
      break;
  }
}

最后更新:2026 年 9 月 4 日