跳转到内容

推理 API

聊天

POST /v1/chat/completions

根据文本/图像聊天提示创建聊天响应。这是向聊天和图像理解模型发送请求的端点。

请求体

  • deferred (boolean | null) — 如果设置为 true,请求将返回一个 request_id。然后您可以通过 GET /v1/chat/deferred-completion/{request_id} 获取延迟响应。

  • frequency_penalty (number | null) — (推理模型不支持) 介于 -2.0 和 2.0 之间的数字。正值会根据新在文本中已有的频率来惩罚新token,降低模型逐字重复相同行的可能性。

  • logit_bias (object | null) — (不支持) 一个将token(由其在tokenizer中的token ID指定)映射到-100到100之间关联偏差值的JSON对象。从数学上讲,该偏差会添加到模型在采样前生成的logits中。确切效果会因模型而异,但-1到1之间的值应该会降低或增加被选中的可能性;像-100或100这样的值应该会导致禁止或 exclusively 选择相关token。

  • logprobs (boolean | null) — 是否返回输出token的对数概率。如果为true,则返回消息内容中返回的每个输出token的对数概率。模型 grok-4.20 和更新版本不支持此功能;如果设置,该字段将被静默忽略。

  • max_completion_tokens (integer | null) — 可生成完成token数量的上限,仅适用于可见输出token(即不用于推理或函数调用的token)。未设置时默认为128,000;设置更大的值以允许更长的生成。

  • max_tokens (integer | null) — [已弃用] 聊天完成中可生成的最大token数。已被 max_completion_tokens 取代。

  • messages (array<object | object | object | object | object>) — 构成聊天对话的消息列表。不同模型支持不同的消息类型,如图像和文本。

  • model (string) — 要使用的模型名称。可从 https://console.x.ai/team/default/modelshttps://docs.x.ai/docs/models 获取。

  • n (integer | null) — 为每个输入消息生成多少个聊天完成选项。请注意,您将根据所有选项中生成的token数量计费。将n保持为1以最小化成本。

  • parallel_tool_calls (boolean | null) — 如果设置为false,模型最多可以执行一个工具调用。

  • presence_penalty (number | null) — (grok-3 和推理模型不支持) 介于 -2.0 和 2.0 之间的数字。正值会根据新token是否已在文本中出现来惩罚它们,增加模型谈论新话题的可能性。

  • prompt_cache_key (string | null) — 用于共享提示前缀的请求之间的最佳粘性路由/提示缓存命中的稳定缓存键 管道到 x-grok-conv-id,与 /v1/responses 相同。

  • reasoning_effort (string | null) — 限制推理模型在响应前思考的程度。仅支持 grok-4.3。可能的值有 none(完全禁用推理)、low(如果未指定则为默认值)、mediumhigh(使用最多的推理token)。

  • response_format (object | object | object)

  • search_parameters (object)

    • from_date (string | null) — 考虑结果的起始日期,格式为ISO-8601 YYYY-MM-DD。请参阅 https://en.wikipedia.org/wiki/ISO_8601

    • max_search_results (integer | null) — 要使用的最大搜索结果数。

    • mode (string | null) — 选择查询实时数据的模式:

      • off:不执行搜索,不考虑外部数据。
      • on(默认):模型将在所有来源中搜索相关数据。
      • auto:模型选择是否搜索数据以及在哪里搜索数据。
    • return_citations (boolean | null) — 是否在响应中返回引用。

    • sources (array | null) — 要搜索的来源列表。如果未指定来源,模型默认会在网络和X上搜索。

    • to_date (string | null) — 考虑结果的结束日期,格式为ISO-8601 YYYY-MM-DD。请参阅 https://en.wikipedia.org/wiki/ISO_8601

  • seed (integer | null) — 如果指定,我们的系统将尽力进行确定性采样,使得具有相同 seed 和参数的重复请求应返回相同结果。不保证确定性,您应该参考 system_fingerprint 响应参数来监控后端的更改。

  • service_tier ("default" | "priority")

  • stop (array | null) — (推理模型不支持) 最多4个序列,API将在这些序列处停止生成更多token。

  • stream (boolean | null) — 如果设置,将发送部分消息增量。当token可用时,它们将作为仅数据的server-sent事件发送,流以 data: [DONE] 消息终止。

  • stream_options (object)

    • include_usage (boolean, required) — 设置在 data: [DONE] 消息之前流式传输的额外块。其他块将在 usage 字段中返回 null
  • temperature (number | null) — 要使用的采样温度,介于0和2之间。较高的值如0.8会使输出更随机,而较低的值如0.2会使输出更专注和确定性。

  • tool_choice (string | object)

  • tools (array | null) — 模型可以在JSON-schema中调用的工具列表。目前,仅支持函数作为工具。用于提供模型可以为其生成JSON输入的函数列表。最多支持128个函数。

  • top_logprobs (integer | null) — 0到8之间的整数,指定在每个token位置返回的最可能token的数量,每个token都有关联的对数概率。如果使用此参数,必须将logprobs设置为true。模型 grok-4.20 和更新版本不支持此功能;如果设置,该字段将被静默忽略。

  • top_p (number | null) — 使用 temperature 采样的替代方法,称为核心采样,其中模型考虑具有 top_p 概率质量的token结果。因此0.1意味着只考虑构成前10%概率质量的token。通常建议修改此参数或 temperature,但不要同时修改两者。

  • user (string | null) — 代表最终用户的唯一标识符,可以帮助xAI监控和检测滥用行为。

  • web_search_options (object)

    • filters (object) — 仅包含用于兼容性。

    • search_context_size (string | null) — 此字段包含用于与OpenAI API兼容。它映射到 max_search

    • user_location (object) — 仅包含用于兼容性。

响应体

  • choices (array<object>, required) — 来自模型的响应选项列表。长度对应于请求体中的 n(默认为1)。

    • finish_reason (string | null) — 完成原因。"stop" 表示推理已达到模型定义的或用户在 stop 中提供的停止序列。"length" 表示推理结果已达到模型允许的最大token长度或用户在 max_tokens 中定义的值。在流式模式中,当块不是最后一个时,为 "end_turn"null

    • index (integer, required) — 响应选项中选项的索引,从0开始。

    • logprobs (object)

      • content (array | null) — 返回的每个输出token的对数概率数组。
    • message (object, required)

      • content (string | null) — 消息的内容。

      • reasoning_content (string | null) — 模型生成的推理痕迹。

      • refusal (string | null) — 如果模型无法生成响应,模型给出的原因。如果模型能够生成,则为null。

      • role (string, required) — 消息所属的角色,模型的响应始终为 "assistant"

      • tool_calls (array | null) — 模型要求用户执行的工具调用列表。

  • citations (array | null) — 模型用来回答的所有外部页面列表。

  • created (integer, required) — 聊天完成创建时间,Unix时间戳。

  • id (string, required) — 聊天响应的唯一ID。

  • model (string, required) — 用于创建聊天完成的模型ID。

  • object (string, required) — 对象类型,始终为 "chat.completion"

  • output_files (array | null) — 响应期间生成的文件(例如,由代码执行工具生成)。 仅在包含 code_execution_files_output 时填充。

  • service_tier ("default" | "priority", required) — 请求的处理层。确定调度优先级和计费。

  • system_fingerprint (string | null) — 系统指纹,用于指示xAI系统配置更改。

  • usage (object)

    • completion_tokens (integer, required) — 使用的完成token总数。

    • completion_tokens_details (object, required) — 完成使用详情。

      • accepted_prediction_tokens (integer, required) — 预测中出现在完成中的token数量。

      • audio_tokens (integer, required) — 模型生成的音频输入token。

      • reasoning_tokens (integer, required) — 模型为推理生成的token。

      • rejected_prediction_tokens (integer, required) — 预测中未出现在完成中的token数量。

    • cost_in_usd_ticks (integer, required) — 此请求的准确成本,以USD ticks为单位,其中"tick"定义如下: TICKS_IN_USD_CENT: i64 = 100_000_000 这意味着每美元中有10'000'000'000个ticks。

    • num_sources_used (integer, required) — 使用的单个实时搜索源数量。

    • prompt_tokens (integer, required) — 使用的提示token总数。

    • prompt_tokens_details (object, required) — 提示使用详情。

      • audio_tokens (integer, required) — 使用的音频提示token。

      • cached_tokens (integer, required) — xAI从前面的请求缓存并在此请求中重用的token。

      • image_tokens (integer, required) — 使用的图像提示token。

      • text_tokens (integer, required) — 使用的文本提示token总数(缓存+非缓存文本token)。

    • total_tokens (integer, required) — 使用的token总数,提示token和完成token数量的总和。

请求示例:

json
{
  "messages": [
    {
      "role": "system",
      "content": "You are a helpful assistant that can answer questions and help with tasks."
    },
    {
      "role": "user",
      "content": "What is 101*3?"
    }
  ],
  "model": "latest"
}

响应示例:

json
{
  "id": "a3d1008e-4544-40d4-d075-11527e794e4a",
  "object": "chat.completion",
  "created": 1752854522,
  "model": "latest",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "101 multiplied by 3 is 303.",
        "refusal": null
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 32,
    "completion_tokens": 9,
    "total_tokens": 135,
    "prompt_tokens_details": {
      "text_tokens": 32,
      "audio_tokens": 0,
      "image_tokens": 0,
      "cached_tokens": 6
    },
    "completion_tokens_details": {
      "reasoning_tokens": 94,
      "audio_tokens": 0,
      "accepted_prediction_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "num_sources_used": 0
  },
  "system_fingerprint": "fp_3a7881249c"
}

POST /v1/responses

根据文本或图像提示生成响应。响应ID可用于稍后检索响应或继续对话而无需重复先前的上下文。新响应将存储30天,然后永久删除。

请求体

  • background (boolean | null) — (不支持) 是否在后台异步处理响应。

  • context_management (array | null) — 可选的上下文管理指令(例如压缩)。已解析但尚未执行。

  • include (array | null) — 在响应中包含哪些额外输出数据。支持的值包括 reasoning.encrypted_content(加密的推理token)和工具输出选项。 OpenAI的 message.output_text.logprobs 被接受用于兼容性,但会被静默忽略。

  • input (string | array<object | object | object | object | object>, required) — 传递给 /v1/response 请求的输入内容。

  • instructions (string | null) — 指定系统提示的替代方法。注意,这不能与 previous_response_id 一起使用,将使用前一条消息的系统提示。

  • logprobs (boolean | null) — 是否返回输出token的对数概率。如果为true,则返回消息内容中返回的每个输出token的对数概率。模型 grok-4.20 和更新版本不支持此功能;如果设置,该字段将被静默忽略。

  • max_output_tokens (integer | null) — 响应中可生成的最大token数。这包括输出和推理token。未设置时默认为128,000;设置更大的值以允许更长的生成。

  • max_turns (integer | null) — 此请求允许的代理工具调用轮次的最大数量。 如果未设置,则默认为服务器的全局上限。 对于任何非代理请求,此参数将被忽略。

  • metadata (object) — 不支持。仅维护用于兼容性原因。

  • min_p (number | null) — Min-p采样:排除概率低于最可能token的 min_p 倍的token。未设置时禁用。

  • model (string) — 要使用的模型名称。可从 https://console.x.ai/team/default/modelshttps://docs.x.ai/docs/models 获取。

  • parallel_tool_calls (boolean | null) — 是否允许模型运行并行工具调用。

  • previous_response_id (string | null) — 模型先前响应的ID。

  • prompt_cache_key (string | null) — 管道到 x-grok-conv-id 以实现开放响应兼容性,用于路由。

  • reasoning (object)

    • effort (string | null) — 限制推理模型在响应前思考的程度。仅支持 grok-4.3。可能的值有 none(完全禁用推理)、low(如果未指定则为默认值)、mediumhigh(使用最多的推理token)。

    • generate_summary (string | null) — 仅包含用于兼容性。

    • summary (string | null) — 模型推理过程的摘要。可能的值有 autoconcisedetailed。仅包含用于兼容性。模型将始终返回 detailed

  • reasoning_effort (string | null) — 推理配置的替代方案 reasoning_effort。这是一个非标准字段,旨在改善用户体验。仅在未设置推理字段时才查看此字段。

  • search_parameters (object)

    • from_date (string | null) — 考虑结果的起始日期,格式为ISO-8601 YYYY-MM-DD。请参阅 https://en.wikipedia.org/wiki/ISO_8601

    • max_search_results (integer | null) — 要使用的最大搜索结果数。

    • mode (string | null) — 选择查询实时数据的模式:

      • off:不执行搜索,不考虑外部数据。
      • on(默认):模型将在所有来源中搜索相关数据。
      • auto:模型选择是否搜索数据以及在哪里搜索数据。
    • return_citations (boolean | null) — 是否在响应中返回引用。

    • sources (array | null) — 要搜索的来源列表。如果未指定来源,模型默认会在网络和X上搜索。

    • to_date (string | null) — 考虑结果的结束日期,格式为ISO-8601 YYYY-MM-DD。请参阅 https://en.wikipedia.org/wiki/ISO_8601

  • service_tier ("default" | "priority")

  • store (boolean | null) — 是否存储输入消息和模型响应以便稍后检索。

  • stream (boolean | null) — 如果设置,将发送部分消息增量。当token可用时,它们将作为仅数据的server-sent事件发送,流以 data: [DONE] 消息终止。

  • temperature (number | null) — 要使用的采样温度,介于0和2之间。较高的值如0.8会使输出更随机,而较低的值如0.2会使输出更专注和确定性。

  • text (object)

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

  • tools (array | null) — 模型可以在JSON-schema中调用的工具列表。目前,仅支持函数和网络搜索作为工具。最多支持128个工具。如果指定了 web_search_preview 工具,它将被 search_parameters 覆盖。

  • top_k (integer | null) — Top-k采样:在每个采样步骤中只考虑 top_k 个最可能的token。未设置时禁用。

  • top_logprobs (integer | null) — 0到8之间的整数,指定在每个token位置返回的最可能token的数量,每个token都有关联的对数概率。如果使用此参数,必须将logprobs设置为true。模型 grok-4.20 和更新版本不支持此功能;如果设置,该字段将被静默忽略。

  • top_p (number | null) — 使用 temperature 采样的替代方法,称为核心采样,其中模型考虑具有 top_p 概率质量的token结果。因此0.1意味着只考虑构成前10%概率质量的token。通常建议修改此参数或 temperature,但不要同时修改两者。

  • truncation (string | null) — 不支持。仅维护用于兼容性原因。

  • user (string | null) — 代表最终用户的唯一标识符,可以帮助xAI监控和检测滥用行为。

响应体

  • background (boolean, required) — 开放响应兼容性字段。 目前未使用。仅用于开放响应兼容性。 是否在后台异步处理响应。

  • completed_at (integer | null) — 响应完成时间的Unix时间戳(以秒为单位)。仅在响应完成时设置。

  • created_at (integer, required) — 响应创建时间的Unix时间戳(以秒为单位)。

  • error (object) — 模型无法生成响应时返回的错误对象。

  • frequency_penalty (number, required) — (响应API不支持) 正值会根据新token在文本中已有的频率来惩罚它们,降低模型逐字重复相同行的可能性。

  • id (string, required) — 响应的唯一ID。

  • incomplete_details (object | object | object)

  • safety_identifier (string | null) — 用于帮助检测可能违反 xAI 使用政策的你的应用程序用户的稳定标识符。

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

  • status (string, required) — 响应的状态。值为 `completed`、`in_progress` 或 `incomplete` 之一。

  • store (boolean, required) — 是否存储输入消息和模型响应以便以后检索。

  • temperature (number | null) — 使用的采样温度,介于 0 和 2 之间。较高的值如 0.8 会使输出更随机,而较低的值如 0.2 会使输出更聚焦和确定性。

  • text (object, required)

    • format (object | object | object)
  • tool_choice (string | object, required) — 控制模型如何选择工具的参数。

    • name (string, required) — 要使用的函数名称。

    • type (string, required) — 类型始终为 `"function"`。

  • tools (array&lt;object | object | object | object | object | object | object | object>, required) — 模型可能在 JSON-schema 中调用的工具列表。目前,仅支持函数和网页搜索作为工具。最多支持 128 个工具。

  • top_logprobs (integer, required) — 介于 0 和 8 之间的整数,指定在每个令牌位置返回的最可能的令牌数量。

  • top_p (number | null) — 使用 `temperature` 采样的替代方法,称为核心采样,其中模型考虑具有 `top_p` 概率质量的令牌结果。因此 0.1 意味着只考虑构成前 10% 概率质量的令牌。通常建议修改此参数或 `temperature`,但不要同时修改两者。

  • truncation (string, required) — 用于模型响应的截断策略。

  • usage (object)

    • context_details (object)

      • input_tokens (integer, required) — 最新上下文中的提示令牌(源自 `SamplingUsage.context_prompt_tokens`)。

      • output_tokens (integer, required) — 最新上下文中的完成 + 推理令牌(源自 `SamplingUsage.context_output_tokens`)。

    • cost_in_nano_usd (integer | null) — 此请求的成本,以纳美元为单位。

    • cost_in_usd_ticks (integer | null) — 此请求的精确成本,以美元 tick 为单位,其中 "tick" 定义如下: TICKS_IN_USD_CENT: i64 = 100_000_000 这意味着在 1 美元中有 10'000'000'000 个 tick。

    • input_tokens (integer, required) — 使用的输入令牌数量。

    • input_tokens_details (object, required)

      • cached_tokens (integer, required) — xAI 从之前的请求中缓存并在此请求中重用的令牌。
    • num_server_side_tools_used (integer, required) — 使用的服务器端工具数量。

    • num_sources_used (integer, required) — 使用的源数量(用于实时搜索)。

    • output_tokens (integer, required) — 使用的输出令牌数量。

    • output_tokens_details (object, required)

      • reasoning_tokens (integer, required) — 模型为推理生成的令牌。
    • server_side_tool_usage_details (object)

      • code_interpreter_calls (integer, required) — 代码解释器调用次数。

      • document_search_calls (integer, required) — 文档搜索调用次数。

      • file_search_calls (integer, required) — 文件搜索调用次数。

      • image_generation_calls (integer, required) — 图像生成调用次数。

      • mcp_calls (integer, required) — MCP 调用次数。

      • web_search_calls (integer, required) — 网页搜索调用次数。

      • x_search_calls (integer, required) — X 搜索调用次数。

    • total_tokens (integer, required) — 使用的总令牌数。

  • user (string | null) — 代表你的终端用户的唯一标识符,可以帮助 xAI 监控和检测滥用。

Code Examples

bash
curl -s https://api.x.ai/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
    "model": "grok-4.5",
    "input": "What is the meaning of life?"
  }'
javascript
import { xai } from "@ai-sdk/xai";
import { generateText } from "ai";

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

console.log(JSON.stringify(result, null, 2));
python
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.5",
    input="What is the meaning of life?",
)

print(response.model_dump_json(indent=2))
javascript
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.5",
  input: "What is the meaning of life?",
});

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

**响应示例:**

json
{
  "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
}

POST /v1/responses/compact

将完整的 Responses API 输入窗口压缩为更短的标准窗口。

Request Body

  • input (string | array&lt;object | object | object | object | object>, required) — 传递给 `/v1/response` 请求的输入内容。

  • model (string, required) — 用于压缩摘要的模型(必需)。

Response Body

  • created_at (integer, required) — 压缩对话创建时的 Unix 时间戳(以秒为单位)。

  • id (string, required) — 此压缩的唯一 ID(例如 `cmp_<uuid>`)。

  • model (string, required) — 用于压缩摘要的模型。

  • object (string, required) — 始终为 `"response.compaction"`。

  • output (array&lt;object | object | object | object | object>, required) — 包含单个压缩项目的压缩输出。 将此原样作为输入传递给下一个 `/v1/responses` 调用。

  • usage (object)

    • dropped_message_count (integer, required) — 压缩期间被丢弃/摘要的消息数量。

    • input_tokens (integer, required) — 原始(压缩前)输入中的令牌数量。

    • input_tokens_details (object, required) — 压缩调用的输入令牌细分。

      • cached_tokens (integer, required) — 从提示缓存中提供的输入令牌数量。
    • output_tokens (integer, required) — 压缩输出中的令牌数量。

    • output_tokens_details (object, required) — 压缩调用的输出令牌细分。

      • reasoning_tokens (integer, required) — 压缩期间生成的推理令牌数量。
    • total_tokens (integer, required) — 使用的总令牌数(输入 + 输出,包括推理)。

Code Examples

bash
curl -s https://api.x.ai/v1/responses/compact \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
    "model": "grok-4.5",
    "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."}
    ]
  }'
python
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.5",
    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))
javascript
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.5",
  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));

**响应示例:**

json
{}

GET /v1/responses/{response_id}

检索先前生成的响应。

Path Parameters

  • response_id (string, required) — 之前创建响应请求返回的响应 ID。

Response Body

  • background (boolean, required) — OpenResponses 兼容性字段。 目前未使用。仅用于 OpenResponses 兼容性。 是否在后台异步处理响应。

  • completed_at (integer | null) — 响应完成时间的 Unix 时间戳(以秒为单位)。仅在响应完成时设置。

  • created_at (integer, required) — 响应创建时间的 Unix 时间戳(以秒为单位)。

  • error (object) — 模型无法生成响应时返回的错误对象。

  • frequency_penalty (number, required) — (Responses API 中不支持) 正值会根据新令牌在文本中已有的频率对其进行惩罚,从而降低模型逐字重复同一行的可能性。

  • id (string, required) — 响应的唯一 ID。

  • incomplete_details (object | object | object)

  • instructions (string | null) — 插入到模型上下文中的系统(或开发者)消息。

  • max_output_tokens (integer | null) — 响应中可以生成的最大令牌数。这包括输出和推理令牌。

  • max_tool_calls (integer | null) — 此响应允许的最大工具调用次数。

  • metadata (object, required) — 仅包含用于兼容性。

  • model (string, required) — 用于生成响应的模型名称。

  • object (string, required) — 此资源的对象类型。始终设置为 `response`。

  • output (array&lt;object | object | object | object | object | object | object | object | object | object>, required) — 模型生成的响应。

  • parallel_tool_calls (boolean, required) — 是否允许模型运行并行工具调用。

  • presence_penalty (number, required) — (Responses API 中不支持) 正值会根据新令牌是否出现在文本中对其进行惩罚,从而增加模型讨论新主题的可能性。

  • previous_response_id (string | null) — 模型之前响应的 ID。

  • prompt_cache_key (string | null) — 用于提示的路由到正确引擎的缓存密钥。

  • reasoning (object)

    • effort (string | null) — 限制推理模型在响应前思考的难度。仅支持 `grok-4.3`。可能值为 `none`(完全禁用推理)、`low`(如果未指定则为默认值)、`medium` 和 `high`(使用最多的推理令牌)。

    • generate_summary (string | null) — 仅包含用于兼容性。

    • summary (string | null) — 模型推理过程的摘要。可能值为 `auto`、`concise` 和 `detailed`。仅包含用于兼容性。模型应始终返回 `detailed`。

  • safety_identifier (string | null) — 用于帮助检测可能违反 xAI 使用政策的你的应用程序用户的稳定标识符。

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

  • status (string, required) — 响应的状态。值为 `completed`、`in_progress` 或 `incomplete` 之一。

  • store (boolean, required) — 是否存储输入消息和模型响应以便以后检索。

  • temperature (number | null) — 使用的采样温度,介于 0 和 2 之间。较高的值如 0.8 会使输出更随机,而较低的值如 0.2 会使输出更聚焦和确定性。

  • text (object, required)

    • format (object | object | object)
  • tool_choice (string | object, required) — 控制模型如何选择工具的参数。

    • name (string, required) — 要使用的函数名称。

    • type (string, required) — 类型始终为 `"function"`。

  • tools (array&lt;object | object | object | object | object | object | object | object>, required) — 模型可能在 JSON-schema 中调用的工具列表。目前,仅支持函数和网页搜索作为工具。最多支持 128 个工具。

  • top_logprobs (integer, required) — 介于 0 和 8 之间的整数,指定在每个令牌位置返回的最可能的令牌数量。

  • top_p (number | null) — 使用 `temperature` 采样的替代方法,称为核心采样,其中模型考虑具有 `top_p` 概率质量的令牌结果。因此 0.1 意味着只考虑构成前 10% 概率质量的令牌。通常建议修改此参数或 `temperature`,但不要同时修改两者。

  • truncation (string, required) — 用于模型响应的截断策略。

  • usage (object)

    • context_details (object)

      • input_tokens (integer, required) — 最新上下文中的提示令牌(源自 `SamplingUsage.context_prompt_tokens`)。

      • output_tokens (integer, required) — 最新上下文中的完成 + 推理令牌(源自 `SamplingUsage.context_output_tokens`)。

    • cost_in_nano_usd (integer | null) — 此请求的成本,以纳美元为单位。

    • cost_in_usd_ticks (integer | null) — 此请求的精确成本,以美元 tick 为单位,其中 "tick" 定义如下: TICKS_IN_USD_CENT: i64 = 100_000_000 这意味着在 1 美元中有 10'000'000'000 个 tick。

    • input_tokens (integer, required) — 使用的输入令牌数量。

    • input_tokens_details (object, required)

      • cached_tokens (integer, required) — xAI 从之前的请求中缓存并在此请求中重用的令牌。
    • num_server_side_tools_used (integer, required) — 使用的服务器端工具数量。

    • num_sources_used (integer, required) — 使用的源数量(用于实时搜索)。

    • output_tokens (integer, required) — 使用的输出令牌数量。

    • output_tokens_details (object, required)

      • reasoning_tokens (integer, required) — 模型为推理生成的令牌。
    • server_side_tool_usage_details (object)

      • code_interpreter_calls (integer, required) — 代码解释器调用次数。

      • document_search_calls (integer, required) — 文档搜索调用次数。

      • file_search_calls (integer, required) — 文件搜索调用次数。

      • image_generation_calls (integer, required) — 图像生成调用次数。

      • mcp_calls (integer, required) — MCP 调用次数。

      • web_search_calls (integer, required) — 网页搜索调用次数。

      • x_search_calls (integer, required) — X 搜索调用次数。

    • total_tokens (integer, required) — 使用的总令牌数。

  • user (string | null) — 代表你的终端用户的唯一标识符,可以帮助 xAI 监控和检测滥用。

**响应示例:**

json
{
  "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}

删除先前生成的响应。

Path Parameters

  • response_id (string, required) — 之前创建响应请求返回的响应 ID。

Response Body

  • deleted (boolean, required) — 响应是否已成功删除。

  • id (string, required) — 要删除的 response_id。

  • object (string, required) — 已删除的对象类型,始终为 `response`。

**响应示例:**

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

GET /v1/chat/deferred-completion/{request_id}

尝试获取先前启动的延迟完成的结果。如果请求已完成,则返回 `200 Success` 和响应体。当请求正在处理中时,返回 `202 Accepted`。

Path Parameters

  • request_id (string, required) — 之前延迟聊天请求返回的延迟请求 ID。

Response Body

  • choices (array&lt;object>, required) — 来自模型的响应选择列表。长度对应于请求体中的 `n`(默认为 1)。

    • finish_reason (string | null) — 完成原因。`"stop"` 表示推理已达到模型定义的或用户在 `stop` 中提供的停止序列。`"length"` 表示推理结果已达到模型允许的最大令牌长度或用户在 `max_tokens` 中定义的值。`"end_turn` 或流式模式中的 `null`(当块不是最后一个时)。

    • index (integer, required) — 响应选择中的选择索引,从 0 开始。

    • logprobs (object)

      • content (array | null) — 返回的每个输出令牌的对数概率数组。
    • message (object, required)

      • content (string | null) — 消息内容。

      • reasoning_content (string | null) — 模型生成的推理跟踪。

      • refusal (string | null) — 如果模型无法生成响应,模型给出的原因。如果模型能够生成,则为 null。

      • role (string, required) — 消息所属的角色,来自模型的响应始终为 `"assistant"`。

      • tool_calls (array | null) — 模型要求用户执行的工具调用列表。

  • citations (array | null) — 模型用来回答的所有外部页面列表。

  • created (integer, required) — 聊天完成创建时间,以 Unix 时间戳表示。

  • id (string, required) — 聊天响应的唯一 ID。

  • model (string, required) — 用于创建聊天的模型 ID。

  • object (string, required) — 对象类型,始终为 `"chat.completion"`。

  • output_files (array | null) — 响应期间生成的文件(例如,由代码执行工具生成)。 仅在包含 `code_execution_files_output` 时填充。

  • service_tier ("default" | "priority", required) — 请求的处理层。确定调度优先级和计费。

  • system_fingerprint (string | null) — 系统指纹,用于指示 xAI 系统配置更改。

  • usage (object)

    • completion_tokens (integer, required) — 使用的完成令牌总数。

    • completion_tokens_details (object, required) — 完成使用详情。

      • accepted_prediction_tokens (integer, required) — 出现在完成中的预测中的令牌数量。

      • audio_tokens (integer, required) — 模型生成的音频输入令牌。

      • reasoning_tokens (integer, required) — 模型为推理生成的令牌。

      • rejected_prediction_tokens (integer, required) — 未出现在完成中的预测中的令牌数量。

    • cost_in_usd_ticks (integer, required) — 此请求的精确成本,以美元 tick 为单位,其中 "tick" 定义如下: TICKS_IN_USD_CENT: i64

本文档为 docs.x.ai 全站中文翻译,由 AI 自动翻译生成。代码示例请以原文为准。