Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/phpaisdk/xai/llms.txt

Use this file to discover all available pages before exploring further.

Tool calling lets you expose PHP functions to a Grok model so it can decide when to invoke them mid-conversation. The model returns a structured tool call in its response; the SDK executes the matching handler and, if needed, feeds the result back for a final answer. The aisdk/xai provider handles all serialisation through the shared ChatRequestBuilder from aisdk/openai-compatible, so tool definitions written for any OpenAI-compatible provider work identically with Grok.

How Tool Calling Works

When you attach tools to a Generate::text() call, ChatRequestBuilder serialises them into the standard tools array in the request body, with each entry following the OpenAI function format. The xAI API returns a tool_calls field in the response when the model chooses to invoke a function; ChatResponseParser unpacks this back into the SDK’s portable response shape. Tool calling is declared as a supported capability for the following model families in resources/models.json:
  • grok-4*
  • grok-3*
  • grok-2*

Defining a Tool

Tools are defined using Tool::define() from aisdk/core and passed to the ->tools() builder method. Provide a name, a human-readable description, a parameter schema, and a PHP handler closure:
use AiSdk\Generate;
use AiSdk\Tool;
use AiSdk\XAI;

$result = Generate::text()
    ->model(XAI::model('grok-4'))
    ->prompt('What is the weather in Paris?')
    ->tools([
        Tool::define(
            name: 'get_weather',
            description: 'Returns current weather for a city',
            parameters: [
                'city' => ['type' => 'string', 'description' => 'City name'],
            ],
            handler: fn(array $args) => ['temperature' => 22, 'unit' => 'C'],
        ),
    ])
    ->run();
The model will call get_weather with ['city' => 'Paris'], receive ['temperature' => 22, 'unit' => 'C'] from your handler, and incorporate that data into its final text response.
The full Tool::define() signature — including how to declare required parameters, nested schemas, and multi-turn tool loops — is provided by aisdk/core. Refer to the core SDK documentation for the complete API. The xAI provider handles serialisation to the OpenAI-compatible function_call format automatically; no provider-specific configuration is needed.

Supported Models

Model patternTool calling support
grok-4* (e.g. grok-4, grok-4.3)✅ Yes
grok-3* (e.g. grok-3, grok-3-mini)✅ Yes
grok-2* (e.g. grok-2-vision)✅ Yes

Build docs developers (and LLMs) love