工具
概览
xAI API 支持 tool calling,使 Grok 能够执行文本生成之外的操作,例如搜索 Web、执行代码、查询数据或调用自定义 function。Tool 扩展了 API 的能力边界,可用于构建强大且具有交互性的应用。
Tool 类型
xAI API 提供两类 tool:
| 类型 | 说明 | 示例 |
|---|---|---|
| Built-in Tool | 由 xAI 管理并自动执行的 server-side tool | Web Search、X Search、Code Interpreter、Image Generation、Collections Search |
| Function Calling | 由你定义、可供 model 调用的 custom function | Database query、API call、custom business logic |
Built-in tool 在 xAI server 上运行;你提供 tool 配置,API 负责执行并返回结果。Function calling 允许你定义 model 可以请求的 tool,从而完全控制 tool 被调用时发生的操作。
定价
Tool request 的价格由两部分组成:token usage 和 tool invocation。由于 model 可能调用多个 tool 来回答 query,费用会随复杂度增加。
有关 Tool 定价的更多信息,请查看 定价页面。
工作原理
在请求中提供 tool 后,xAI API 可以使用这些 tool 收集信息或执行操作:
分析 query,确定需要哪些信息或操作
决定下一步操作:发起 tool call,或提供最终答案
执行 tool(built-in tool),或返回 tool call request(function calling)
处理结果,并持续执行直到收集到足够信息
返回最终 response,并在适用时提供 citation
快速入门
curl https://api.x.ai/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $XAI_API_KEY" \
-d '{
"model": "grok-4.5",
"stream": true,
"input": [
{
"role": "user",
"content": "What are the latest updates from xAI?"
}
],
"tools": [
{ "type": "web_search" },
{ "type": "x_search" },
{ "type": "code_interpreter" }
]
}'Citation
API 会自动返回通过 tool 收集的信息所对应的 source URL。有关访问和使用 citation data 的详情,请参阅 Citation。
下一步
Function Calling,定义 model 可以调用的 custom tool
Web Search,搜索 Web 并浏览页面
X Search,搜索 X 帖子、用户和 thread
Code Execution,在 sandbox 中执行 Python 代码
Image Generation,在 conversation 中生成和编辑图像
Collections Search,查询已上传文档
Citation,访问 source URL 和 inline citation