SpyBara
Go Premium

rest-api-reference/inference/responses.md 2026-10-07 23:59 UTC to 2026-10-08 23:58 UTC

This page contains 26 additions and 26 deletions.

2026
Fri 2 23:57 Thu 8 23:58

Inference API

Responses

The Responses API is the primary interface for text generation, reasoning, and tool use. See the Text Generation guide for usage.


POST /v1/responses

Generates a response based on text or image prompts. The response ID can be used to retrieve the response later or to continue the conversation without repeating prior context. New responses will be stored for 30 days and then permanently deleted.

Request Body

  • background (boolean | null) — (Unsupported) Whether to process the response asynchronously in the background.

  • context_management (array | null) — Optional context-management directives (e.g. compaction). Parsed but not yet executed.

  • include (array | null) — What additional output data to include in the response. Supported values include `reasoning.encrypted_content` (encrypted reasoning tokens) and tool-output options. OpenAI's `message.output_text.logprobs` is accepted for compatibility but silently ignored.

  • input (string | array<object | object | object | object | object>, required) — Content of the input passed to a `/v1/response` request.

  • instructions (string | null) — An alternate way to specify the system prompt. Note that this cannot be used alongside `previous_response_id`, where the system prompt of the previous message will be used.

  • logprobs (boolean | null) — Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the content of message. Not supported by models `grok-4.20` and newer; the field will be silently ignored if set.

  • max_output_tokens (integer | null) — Max number of tokens that can be generated in a response. Only applies to visible output tokens (i.e. does not apply to tokens used for reasoning or function calls). Defaults to 128,000 when unset; set a larger value to allow longer generations.

  • max_turns (integer | null) — Maximum number of agentic tool calling turns allowed for this request. If not set, defaults to the server's global cap. This parameter will be ignored for any non-agentic requests, and for agentic SLOP requests that have neither a server-side tool nor a file attachment.

  • metadata (object) — Not supported. Only maintained for compatibility reasons.

  • min_p (number | null) — Min-p sampling: tokens whose probability is below `min_p` times the probability of the most likely token are excluded from sampling. Disabled when unset.

  • model (string) — Model name for the model to use. Obtainable from <https://console.x.ai/team/default/models> or <https://docs.x.ai/docs/models>.

  • parallel_tool_calls (boolean | null) — Whether to allow the model to run parallel tool calls.

  • previous_response_id (string | null) — The ID of the previous response from the model.

  • prompt_cache_key (string | null) — Plumbed to x-grok-conv-id for Open Responses compatibility, used for routing.

  • reasoning (object)

    • effort (string | null) — Constrains how hard a reasoning model thinks before responding. Higher efforts use more reasoning tokens for deeper thinking. The supported values and the default depend on the model.

    • generate_summary (string | null) — Only included for compatibility.

    • summary (string | null) — A summary of the model's reasoning process. Possible values are `auto`, `concise` and `detailed`. Only included for compatibility. The model shall always return `detailed`.

  • reasoning_effort (string | null) — Non-standard alternative to `reasoning.effort` that accepts the same values. We only look at this if the reasoning field is unset.

  • safety_identifier (string | null) — Supplied by the API client to identify the end user behind this request. A stable string that uniquely identifies each of your users; hash your internal user id or username rather than sending an email or name. Stored with the request metadata so a usage-policy violation can be attributed to that user rather than to the API key.

  • search_parameters (object)

    • from_date (string | null) — Date from which to consider the results in ISO-8601 YYYY-MM-DD. See <https://en.wikipedia.org/wiki/ISO_8601>.

    • max_search_results (integer | null) — Maximum number of search results to use.

    • mode (string | null) — Choose the mode to query realtime data: * `off`: no search performed and no external will be considered. * `on` (default): the model will search in every sources for relevant data. * `auto`: the model choose whether to search data or not and where to search the data.

    • return_citations (boolean | null) — Whether to return citations in the response or not.

    • sources (array | null) — List of sources to search in. If no sources specified, the model will look over the web and X by default.

    • to_date (string | null) — Date up to which to consider the results in ISO-8601 YYYY-MM-DD. See <https://en.wikipedia.org/wiki/ISO_8601>.

  • service_tier ("default" | "priority" | "fast")

  • store (boolean | null) — Whether to store the input message(s) and model response for later retrieval.

  • stream (boolean | null) — If set, partial message deltas will be sent. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a `data: [DONE]` message.

  • temperature (number | null) — What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.

  • text (object)

    • format (object | object | object)
  • tool_choice (string | object)

  • tools (array | null) — A list of tools the model may call in JSON-schema. Currently, only functions and web search are supported as tools. A max of 350 tools are supported.`web_search_preview` tool, if specified, will be overridden by `search_parameters`.

  • top_k (integer | null) — Top-k sampling: only the `top_k` most probable tokens are considered at each sampling step. Disabled when unset.

  • top_logprobs (integer | null) — An integer between 0 and 8 specifying the number of most likely tokens to return at each token position, each with an associated log probability. logprobs must be set to true if this parameter is used. Not supported by models `grok-4.20` and newer; the field will be silently ignored if set.

  • top_p (number | null) — An alternative to sampling with `temperature`, called nucleus sampling, where the model considers the results of the tokens with `top_p` probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. It is generally recommended to alter this or `temperature` but not both.

  • truncation (string | null) — Not supported. Only maintained for compatibility reasons.

  • user (string | null) — A unique identifier representing your end-user, which can help xAI to monitor and detect abuse.

Response Body

  • background (boolean, required) — OpenResponses compatibility fields. Not used at the moment. Just for OpenResponses compatibility. Whether to process the response asynchronously in the background.

  • completed_at (integer | null) — The Unix timestamp (in seconds) for the response completion time. Only set when the response is completed.

  • created_at (integer, required) — The Unix timestamp (in seconds) for the response creation time.

  • error (object) — An error object returned when the model fails to generate a response.

  • frequency_penalty (number, required) — (NOT SUPPORTED in Responses API) Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.

  • id (string, required) — Unique ID of the response.

  • incomplete_details (object | object | object)

  • instructions (string | null) — A system (or developer) message inserted into the model's context.

  • max_output_tokens (integer | null) — Max number of tokens that can be generated in a response. Only applies to visible output tokens (i.e. does not apply to tokens used for reasoning or function calls).

  • max_tool_calls (integer | null) — The maximum number of tool calls allowed for this response.

  • metadata (object, required) — Only included for compatibility.

  • model (string, required) — Model name used to generate the response.

  • object (string, required) — The object type of this resource. Always set to `response`.

  • output (array<object | object | object | object | object | object | object | object | object | object | object | object>, required) — The response generated by the model.

  • parallel_tool_calls (boolean, required) — Whether to allow the model to run parallel tool calls.

  • presence_penalty (number, required) — (NOT SUPPORTED in Responses API) Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.

  • previous_response_id (string | null) — The ID of the previous response from the model.

  • prompt_cache_key (string | null) — The cache key used for the prompt for routing to the correct engine.

  • reasoning (object)

    • effort (string | null) — Constrains how hard a reasoning model thinks before responding. Higher efforts use more reasoning tokens for deeper thinking. The supported values and the default depend on the model.

    • generate_summary (string | null) — Only included for compatibility.

    • summary (string | null) — A summary of the model's reasoning process. Possible values are `auto`, `concise` and `detailed`. Only included for compatibility. The model shall always return `detailed`.

  • safety_identifier (string | null) — A stable identifier used to help detect users of your application that may be violating xAI's usage policies.

  • service_tier ("default" | "priority" | "fast", required)

  • status (string, required) — Status of the response. One of `completed`, `in_progress` or `incomplete`.

  • store (boolean, required) — Whether to store the input message(s) and model response for later retrieval.

  • temperature (number | null) — What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.

  • text (object, required)

    • format (object | object | object)
  • tool_choice (string | object, required) — Parameter to control how model chooses the tools.

    • name (string, required) — Name of the function to use.

    • type (string, required) — Type is always `"function"`.

  • tools (array<object | object | object | object | object | object | object | object | object>, required) — A list of tools the model may call in JSON-schema. Currently, only functions and web search are supported as tools. A max of 350 tools are supported.

  • top_logprobs (integer, required) — An integer between 0 and 8 specifying the number of most likely tokens to return at each token position.

  • top_p (number | null) — An alternative to sampling with `temperature`, called nucleus sampling, where the model considers the results of the tokens with `top_p` probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. It is generally recommended to alter this or `temperature` but not both.

  • truncation (string, required) — The truncation strategy to use for the model response.

  • usage (object)

    • context_details (object)

      • input_tokens (integer, required) — Prompt tokens in the latest context (sourced from `SamplingUsage.context_prompt_tokens`).

      • output_tokens (integer, required) — Completion + reasoning tokens in the latest context (sourced from `SamplingUsage.context_output_tokens`).

    • cost_in_nano_usd (integer | null) — Cost in nano US dollars for this request.

    • cost_in_usd_ticks (integer | null) — Accurate cost of this request in USD ticks, where "tick" is defined as follows: TICKS_IN_USD_CENT: i64 = 100_000_000 which means there is 10'000'000'000 ticks in one *dollar*.

    • input_tokens (integer, required) — Number of input tokens used.

    • input_tokens_details (object, required)

      • cached_tokens (integer, required) — Token cached by xAI from previous requests and reused for this request.
    • num_server_side_tools_used (integer, required) — Number of server side tools used.

    • num_sources_used (integer, required) — Number of sources used (for live search).

    • output_tokens (integer, required) — Number of output tokens used.

    • output_tokens_details (object, required)

      • reasoning_tokens (integer, required) — Tokens generated by the model for reasoning.
    • server_side_tool_usage_details (object)

      • code_interpreter_calls (integer, required) — Number of code interpreter calls.

      • document_search_calls (integer, required) — Number of document search calls.

      • file_search_calls (integer, required) — Number of file search calls.

      • image_generation_calls (integer, required) — Number of image generation calls.

      • mcp_calls (integer, required) — Number of MCP calls.

      • web_search_calls (integer, required) — Number of web search calls.

      • x_posts_fetched (integer, required) — Number of X posts fetched across all X search calls, including nested parent/quote posts and every post of a fetched thread, without de-duplication. X search is billed per fetched item.

      • x_search_calls (integer, required) — Number of X search calls.

      • x_users_fetched (integer, required) — Number of X user profiles fetched across all X search calls, without de-duplication. X search is billed per fetched item.

    • total_tokens (integer, required) — Total tokens used.

  • user (string | null) — A unique identifier representing your end-user, which can help xAI to monitor and detect abuse.

Code Examples

import { xai } from "@ai-sdk/xai";
import { generateText } from "ai";

const result = await generateText({
  model: xai.responses("grok-4.7"),
  prompt: "What is the meaning of life?",
});

console.log(JSON.stringify(result, null, 2));
import os

from openai import OpenAI

client = OpenAI(
    api_key=os.environ["XAI_API_KEY"],
    base_url="https://api.x.ai/v1",
)

response = client.responses.create(
    model="grok-4.7",
    input="What is the meaning of life?",
)

print(response.model_dump_json(indent=2))
curl -s https://api.x.ai/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
    "model": "grok-4.7",
    "input": "What is the meaning of life?"
  }'
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.XAI_API_KEY,
  baseURL: "https://api.x.ai/v1",
});

const response = await client.responses.create({
  model: "grok-4.7",
  input: "What is the meaning of life?",
});

console.log(JSON.stringify(response, null, 2));

**Response example:**

{
  "created_at": 1754475266,
  "id": "ad5663da-63e6-86c6-e0be-ff15effa8357",
  "max_output_tokens": null,
  "model": "latest",
  "object": "response",
  "output": [
    {
      "content": [
        {
          "type": "output_text",
          "text": "101 multiplied by 3 is 303.",
          "logprobs": null,
          "annotations": []
        }
      ],
      "id": "msg_ad5663da-63e6-86c6-e0be-ff15effa8357",
      "role": "assistant",
      "type": "message",
      "status": "completed"
    }
  ],
  "parallel_tool_calls": true,
  "previous_response_id": null,
  "reasoning": null,
  "temperature": null,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [],
  "top_p": null,
  "usage": {
    "input_tokens": 32,
    "input_tokens_details": {
      "cached_tokens": 8
    },
    "output_tokens": 9,
    "output_tokens_details": {
      "reasoning_tokens": 110
    },
    "total_tokens": 151,
    "num_sources_used": 0,
    "num_server_side_tools_used": 0
  },
  "user": null,
  "incomplete_details": null,
  "status": "completed",
  "store": true
}

GET /v1/responses/{response_id}

Retrieve a previously generated response.

Path Parameters

  • response_id (string, required) — The response id returned by a previous create response request.

Response Body

  • background (boolean, required) — OpenResponses compatibility fields. Not used at the moment. Just for OpenResponses compatibility. Whether to process the response asynchronously in the background.

  • completed_at (integer | null) — The Unix timestamp (in seconds) for the response completion time. Only set when the response is completed.

  • created_at (integer, required) — The Unix timestamp (in seconds) for the response creation time.

  • error (object) — An error object returned when the model fails to generate a response.

  • frequency_penalty (number, required) — (NOT SUPPORTED in Responses API) Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.

  • id (string, required) — Unique ID of the response.

  • incomplete_details (object | object | object)

  • instructions (string | null) — A system (or developer) message inserted into the model's context.

  • max_output_tokens (integer | null) — Max number of tokens that can be generated in a response. Only applies to visible output tokens (i.e. does not apply to tokens used for reasoning or function calls).

  • max_tool_calls (integer | null) — The maximum number of tool calls allowed for this response.

  • metadata (object, required) — Only included for compatibility.

  • model (string, required) — Model name used to generate the response.

  • object (string, required) — The object type of this resource. Always set to `response`.

  • output (array<object | object | object | object | object | object | object | object | object | object | object | object>, required) — The response generated by the model.

  • parallel_tool_calls (boolean, required) — Whether to allow the model to run parallel tool calls.

  • presence_penalty (number, required) — (NOT SUPPORTED in Responses API) Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.

  • previous_response_id (string | null) — The ID of the previous response from the model.

  • prompt_cache_key (string | null) — The cache key used for the prompt for routing to the correct engine.

  • reasoning (object)

    • effort (string | null) — Constrains how hard a reasoning model thinks before responding. Higher efforts use more reasoning tokens for deeper thinking. The supported values and the default depend on the model.

    • generate_summary (string | null) — Only included for compatibility.

    • summary (string | null) — A summary of the model's reasoning process. Possible values are `auto`, `concise` and `detailed`. Only included for compatibility. The model shall always return `detailed`.

  • safety_identifier (string | null) — A stable identifier used to help detect users of your application that may be violating xAI's usage policies.

  • service_tier ("default" | "priority" | "fast", required)

  • status (string, required) — Status of the response. One of `completed`, `in_progress` or `incomplete`.

  • store (boolean, required) — Whether to store the input message(s) and model response for later retrieval.

  • temperature (number | null) — What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.

  • text (object, required)

    • format (object | object | object)
  • tool_choice (string | object, required) — Parameter to control how model chooses the tools.

    • name (string, required) — Name of the function to use.

    • type (string, required) — Type is always `"function"`.

  • tools (array<object | object | object | object | object | object | object | object | object>, required) — A list of tools the model may call in JSON-schema. Currently, only functions and web search are supported as tools. A max of 350 tools are supported.

  • top_logprobs (integer, required) — An integer between 0 and 8 specifying the number of most likely tokens to return at each token position.

  • top_p (number | null) — An alternative to sampling with `temperature`, called nucleus sampling, where the model considers the results of the tokens with `top_p` probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. It is generally recommended to alter this or `temperature` but not both.

  • truncation (string, required) — The truncation strategy to use for the model response.

  • usage (object)

    • context_details (object)

      • input_tokens (integer, required) — Prompt tokens in the latest context (sourced from `SamplingUsage.context_prompt_tokens`).

      • output_tokens (integer, required) — Completion + reasoning tokens in the latest context (sourced from `SamplingUsage.context_output_tokens`).

    • cost_in_nano_usd (integer | null) — Cost in nano US dollars for this request.

    • cost_in_usd_ticks (integer | null) — Accurate cost of this request in USD ticks, where "tick" is defined as follows: TICKS_IN_USD_CENT: i64 = 100_000_000 which means there is 10'000'000'000 ticks in one *dollar*.

    • input_tokens (integer, required) — Number of input tokens used.

    • input_tokens_details (object, required)

      • cached_tokens (integer, required) — Token cached by xAI from previous requests and reused for this request.
    • num_server_side_tools_used (integer, required) — Number of server side tools used.

    • num_sources_used (integer, required) — Number of sources used (for live search).

    • output_tokens (integer, required) — Number of output tokens used.

    • output_tokens_details (object, required)

      • reasoning_tokens (integer, required) — Tokens generated by the model for reasoning.
    • server_side_tool_usage_details (object)

      • code_interpreter_calls (integer, required) — Number of code interpreter calls.

      • document_search_calls (integer, required) — Number of document search calls.

      • file_search_calls (integer, required) — Number of file search calls.

      • image_generation_calls (integer, required) — Number of image generation calls.

      • mcp_calls (integer, required) — Number of MCP calls.

      • web_search_calls (integer, required) — Number of web search calls.

      • x_posts_fetched (integer, required) — Number of X posts fetched across all X search calls, including nested parent/quote posts and every post of a fetched thread, without de-duplication. X search is billed per fetched item.

      • x_search_calls (integer, required) — Number of X search calls.

      • x_users_fetched (integer, required) — Number of X user profiles fetched across all X search calls, without de-duplication. X search is billed per fetched item.

    • total_tokens (integer, required) — Total tokens used.

  • user (string | null) — A unique identifier representing your end-user, which can help xAI to monitor and detect abuse.

**Response example:**

{
  "created_at": 1754475266,
  "id": "ad5663da-63e6-86c6-e0be-ff15effa8357",
  "max_output_tokens": null,
  "model": "latest",
  "object": "response",
  "output": [
    {
      "content": [
        {
          "type": "output_text",
          "text": "101 multiplied by 3 is 303.",
          "logprobs": null,
          "annotations": []
        }
      ],
      "id": "msg_ad5663da-63e6-86c6-e0be-ff15effa8357",
      "role": "assistant",
      "type": "message",
      "status": "completed"
    },
    {
      "id": "",
      "summary": [
        {
          "text": "First, the user asked: \"What is 101*3?\"\n\nThis is a simple multiplication: 101 multiplied by 3.\n\nCalculating: 100 * 3 = 300, and 1 * 3 = 3, so 300 + 3 = 303.\n\nI should respond helpfully and directly, as per my system prompt: \"You are a helpful assistant that can answer questions and help with tasks.\"\n\nKeep the response concise and accurate. No need for extra fluff unless it adds value.\n\nFinal answer: 303.",
          "type": "summary_text"
        }
      ],
      "type": "reasoning",
      "status": "completed"
    }
  ],
  "parallel_tool_calls": true,
  "previous_response_id": null,
  "reasoning": null,
  "temperature": null,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [],
  "top_p": null,
  "usage": {
    "prompt_tokens": 32,
    "completion_tokens": 9,
    "total_tokens": 151,
    "prompt_tokens_details": {
      "text_tokens": 32,
      "audio_tokens": 0,
      "image_tokens": 0,
      "cached_tokens": 8
    },
    "completion_tokens_details": {
      "reasoning_tokens": 110,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "num_sources_used": 0
  },
  "user": null,
  "incomplete_details": null,
  "status": "completed",
  "store": true
}

DELETE /v1/responses/{response_id}

Delete a previously generated response.

Path Parameters

  • response_id (string, required) — The response id returned by a previous create response request.

Response Body

  • deleted (boolean, required) — Whether the response was successfully deleted.

  • id (string, required) — The response_id to be deleted.

  • object (string, required) — The deleted object type, which is always `response`.

**Response example:**

{
  "id": "ad5663da-63e6-86c6-e0be-ff15effa8357",
  "object": "response",
  "deleted": true
}

POST /v1/responses/compact

Compacts a full Responses API input window into a shorter canonical window.

Request Body

  • input (string | array<object | object | object | object | object>, required) — Content of the input passed to a `/v1/response` request.

  • model (string, required) — Model to use for compaction summarization (required).

Response Body

  • created_at (integer, required) — Unix timestamp (in seconds) when the compacted conversation was created.

  • id (string, required) — Unique ID for this compaction (e.g. `cmp_<uuid>`).

  • model (string, required) — Model used for the compaction summary.

  • object (string, required) — Always `"response.compaction"`.

  • output (array<object | object | object | object | object>, required) — Compacted output containing a single compaction item. Pass this verbatim as input to the next `/v1/responses` call.

  • usage (object)

    • dropped_message_count (integer, required) — Number of messages dropped/summarized during compaction.

    • input_tokens (integer, required) — Number of tokens in the original (pre-compaction) input.

    • input_tokens_details (object, required) — Breakdown of input tokens for a compaction call.

      • cached_tokens (integer, required) — Number of input tokens that were served from the prompt cache.
    • output_tokens (integer, required) — Number of tokens in the compacted output.

    • output_tokens_details (object, required) — Breakdown of output tokens for a compaction call.

      • reasoning_tokens (integer, required) — Number of reasoning tokens generated during compaction.
    • total_tokens (integer, required) — Total number of tokens used (input + output, including reasoning).

Code Examples

import os

from openai import OpenAI

client = OpenAI(
    api_key=os.environ["XAI_API_KEY"],
    base_url="https://api.x.ai/v1",
)

compacted = client.responses.compact(
    model="grok-4.7",
    input=[
        {"role": "system", "content": "You are a concise and knowledgeable science tutor."},
        {"role": "user", "content": "What is the Higgs boson and why is it important?"},
        {
            "role": "assistant",
            "content": (
                "The Higgs boson is an elementary particle in the Standard Model, predicted by "
                "Peter Higgs in 1964 and confirmed at CERN in 2012. It is the quantum excitation "
                "of the Higgs field, which gives mass to fundamental particles via the Higgs mechanism."
            ),
        },
        {"role": "user", "content": "How does the Higgs mechanism actually work?"},
        {
            "role": "assistant",
            "content": (
                "Through spontaneous symmetry breaking. The Higgs field has a nonzero vacuum value, "
                "and particles acquire mass in proportion to how strongly they couple to it. Photons "
                "do not couple, which is why they remain massless."
            ),
        },
    ],
)

print(compacted.model_dump_json(indent=2))
curl -s https://api.x.ai/v1/responses/compact \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
    "model": "grok-4.7",
    "input": [
      {"role": "system", "content": "You are a concise and knowledgeable science tutor."},
      {"role": "user", "content": "What is the Higgs boson and why is it important?"},
      {"role": "assistant", "content": "The Higgs boson is an elementary particle in the Standard Model, predicted by Peter Higgs in 1964 and confirmed at CERN in 2012. It is the quantum excitation of the Higgs field, which gives mass to fundamental particles via the Higgs mechanism."},
      {"role": "user", "content": "How does the Higgs mechanism actually work?"},
      {"role": "assistant", "content": "Through spontaneous symmetry breaking. The Higgs field has a nonzero vacuum value, and particles acquire mass in proportion to how strongly they couple to it. Photons do not couple, which is why they remain massless."}
    ]
  }'
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.XAI_API_KEY,
  baseURL: "https://api.x.ai/v1",
});

const compacted = await client.responses.compact({
  model: "grok-4.7",
  input: [
    { role: "system", content: "You are a concise and knowledgeable science tutor." },
    { role: "user", content: "What is the Higgs boson and why is it important?" },
    {
      role: "assistant",
      content:
        "The Higgs boson is an elementary particle in the Standard Model, predicted by Peter Higgs in 1964 and confirmed at CERN in 2012. It is the quantum excitation of the Higgs field, which gives mass to fundamental particles via the Higgs mechanism.",
    },
    { role: "user", content: "How does the Higgs mechanism actually work?" },
    {
      role: "assistant",
      content:
        "Through spontaneous symmetry breaking. The Higgs field has a nonzero vacuum value, and particles acquire mass in proportion to how strongly they couple to it. Photons do not couple, which is why they remain massless.",
    },
  ],
});

console.log(JSON.stringify(compacted, null, 2));

**Response example:**

{}