API / call-a-function-with-grok-api

API

Call a function with the Grok API

Call a function with the Grok API

You define a custom tool (name, description, JSON Schema), put it in tools[], and the model returns a tool_call. You run the function locally, send the result back, and the model continues. Call POST https://api.x.ai/v1/responses with model grok-4.6. Get a key and credits at console.x.ai.

Define the tool

Each tool is type: "function" with name, description, and parameters (JSON Schema). Max 200 tools per request. The parameters root must be type: "object" (or oneOf / anyOf of objects) or you get 400.

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

Continue after the call

On the Responses API, output items arrive as type: "function_call". Continue with previous_response_id and an input item type: "function_call_output" that carries the call_id and your result.

Python with the official SDK uses tool() and tool_result(). If response.tool_calls is set, append the response, execute locally, append tool_result, then sample again.

Control the loop

  • tool_choice: auto (default), required, none, or force a named function.
  • Parallel calls are on by default. Set parallel_tool_calls: false to disable. Process every call before you continue.
  • Built-in tools (web_search, x_search) run on xAI servers. Custom function tools pause and return to you. Mixing both is allowed.
  • When streaming, the function call arrives in one chunk.

Pitfalls

  • A parameters root that is not an object (or oneOf/anyOf of objects) returns 400.
  • Cap is 200 tools per request.
  • Parallel calls mean you may get several tool_calls at once. Run all of them before the next sample.
  • Console API credits are a separate bill from SuperGrok's weekly pool on grok.com.