跳转到内容

工具

引用

代理工具 API 提供两种类型的引用信息:全部引用(所有遇到来源的完整列表)和行内引用(直接嵌入响应文本中的 Markdown 风格链接)。

全部引用

response 对象上的 citations 属性提供了代理在搜索过程中遇到的所有来源的 URL 完整列表。此列表默认总是返回—不需要额外的配置。

引用从成功的工具执行中自动收集,并提供代理信息来源的完全可追溯性。它们在代理请求完成时返回。

请注意,此列表中的每个 URL 不一定会直接引用在最终答案中。代理在研究过程中可能会检查某个来源,并确定它与用户查询的相关性不足,但出于透明度考虑,该 URL 仍会出现在此列表中。

python
response.citations
text
[
'https://x.com/i/user/1912644073896206336',
'https://x.com/i/status/1975607901571199086',
'https://x.ai/news',
'https://docs.x.ai/developers/release-notes',
...
]

行内引用

行内引用是** Markdown 风格的链接**(例如,[[1]](https://x.ai/news)),在模型引用来源的位置直接插入到响应文本中。除了这些可见链接外,结构化元数据也可在响应对象上获取,其中包含精确的位置信息。

重要:启用行内引用并不保证模型会在每个回答中都引用来源。模型根据查询的上下文和性质决定何时以及何地包含引用。

配置行内引用

行内引用行为在响应 APIxAI Python SDK (gRPC 聊天 API) 之间有所不同。

响应 API 的行为适用于以下客户端:

  • 针对 /v1/responses 的 cURL
  • Python (OpenAI SDK)
  • JavaScript (通过 xai.responses() 的 AI SDK)
  • JavaScript (OpenAI SDK)
响应 API (cURL, Python/JS OpenAI SDK, JS AI SDK)xAI Python SDK
默认已启用 — 响应文本可能包含 [[N]](url) 链接,无需额外配置已禁用 — 省略 include,或不传递 "inline_citations"
启用默认启用,无需额外操作。chat.create() 方法传递 include=["inline_citations"]
禁用传递 include=["no_inline_citations"]默认禁用

当行内引用被禁用时,响应文本将不包含任何 [[N]](url) Markdown 链接。output_text 内容块上的 annotations 字段可能仍然存在,但注释只列出搜索过程中遇到的来源—它们不会对响应文本有位置引用。

已启用(响应 API 的默认设置;xAI Python SDK 的可选启用)

bash
# Inline citations are enabled by default for the Responses API
curl https://api.x.ai/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
  "model": "grok-4.5",
  "input": [
    {"role": "user", "content": "What is xAI?"}
  ],
  "tools": [{"type": "web_search"}]
}'
python
import os

from xai_sdk import Client
from xai_sdk.chat import user
from xai_sdk.tools import web_search, x_search

client = Client(api_key=os.getenv("XAI_API_KEY"))
chat = client.chat.create(
    model="grok-4.5",
    tools=[
        web_search(),
        x_search(),
    ],
    include=["inline_citations"],  # Enable inline citations (opt-in for xAI Python SDK)
)

chat.append(user("What is xAI?"))
response = chat.sample()

# Access the response text (includes inline citation markdown)
print(response.content)
python
import os
from openai import OpenAI

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

response = client.responses.create(
    model="grok-4.5",
    input=[
        {"role": "user", "content": "What is xAI?"}
    ],
    tools=[
        {"type": "web_search"},  # inline citations are enabled by default
    ],
)

# Get the message output with inline citations
for item in response.output:
    if item.type == "message":
        for content in item.content:
            if content.type == "output_text":
                print(content.text)
javascript
import { xai } from '@ai-sdk/xai';
import { generateText } from 'ai';

const { text, sources } = await generateText({
  model: xai.responses('grok-4.5'),
  prompt: 'What is xAI?',
  tools: {
    web_search: xai.tools.webSearch(), // inline citations are enabled by default
  },
});

// Text includes inline citation markdown
console.log(text);

// Sources contain all citation URLs
console.log('Sources:', sources);
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: [
    { role: 'user', content: 'What is xAI?' }
  ],
  tools: [{ type: 'web_search' }], // inline citations are enabled by default
});

// Get the message with inline citations
for (const item of response.output) {
  if (item.type === 'message') {
    for (const content of item.content) {
      if (content.type === 'output_text') {
        console.log(content.text);
      }
    }
  }
}

已禁用(响应 API 的可选禁用;xAI Python SDK 的默认设置)

python
import os
from openai import OpenAI

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

response = client.responses.create(
    model="grok-4.5",
    input=[
        {"role": "user", "content": "What is xAI?"}
    ],
    tools=[
        {"type": "web_search"},
    ],
    include=["no_inline_citations"],  # Disable inline citations
)

# Response text will not contain inline citation markdown
for item in response.output:
    if item.type == "message":
        for content in item.content:
            if content.type == "output_text":
                print(content.text)
python
import os
import requests

response = requests.post(
    "https://api.x.ai/v1/responses",
    headers={
        "Content-Type": "application/json",
        "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}",
    },
    json={
        "model": "grok-4.5",
        "include": ["no_inline_citations"],
        "input": [
            {"role": "user", "content": "What is xAI?"}
        ],
        "tools": [{"type": "web_search"}],
    },
)

data = response.json()
for item in data["output"]:
    if item["type"] == "message":
        for content in item["content"]:
            if content["type"] == "output_text":
                print(content["text"])
bash
curl https://api.x.ai/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
  "model": "grok-4.5",
  "include": ["no_inline_citations"],
  "input": [
    {"role": "user", "content": "What is xAI?"}
  ],
  "tools": [{"type": "web_search"}]
}'

Markdown 引用格式

当启用行内引用时,模型会将 Markdown 风格的引用链接直接插入到响应文本中:

text
The latest announcements from xAI, primarily from their official X account (@xai) and website (x.ai/news), date back to November 19, 2025.[[1]](https://x.ai/news/)[[2]](https://x.ai/)[[3]](https://x.com/i/status/1991284813727474073)

当渲染为 Markdown 时,这显示为可点击的链接:

xAI 的最新公告主要来自其官方 X 账号 (@xai) 和网站 (x.ai/news),日期可追溯至 2025 年 11 月 19 日。[1][2][3]

格式为 [[N]](url),其中:

  • N 是引用的从 1 开始的连续显示编号
  • url 是来源 URL

引用编号:引用编号始终从 1 开始并连续递增。如果同一来源在响应的后面部分再次被引用,将重用原始引用编号。

图片嵌入

当在 web_search 工具上启用 enable_image_search 时,Grok 可能会将图片结果作为 Markdown 图片而不是编号文本引用进行嵌入:

text
Here are images of Starship on the launch pad:
![Why the SpaceX Starship launch pad matters](https://www.astronomy.com/wp-content/uploads/2024/09/starship-test-flight-mission-scaled.jpg)

格式为 ![alt](url),其中:

  • alt 是图片的简短描述或标题
  • url 是图片来源 URL

访问结构化行内引用数据

结构化行内引用数据提供响应文本中每个引用的精确位置信息。

响应格式

当启用行内引用时,每个 output_text 内容块都包含一个 annotations 数组,其中包含结构化引用元数据(URL、字符偏移量和标签):

json
{
  "created_at": 1781829888,
  "completed_at": 1781829888,
  "id": "5808284d-ae14-9981-9289-73515f67ebda",
  "max_output_tokens": null,
  "model": "grok-4.5",
  "object": "response",
  "output": [
    ...
    {
      "content": [
        {
          "type": "output_text",
          "text": "**xAI is an artificial intelligence company founded by Elon Musk in March 2023.** Its stated mission is to \"understand the universe\" by building advanced AI systems that accelerate human scientific discovery.[[1]](https://x.ai/company)\n\n### Key Details\n- **Flagship product**: Grok, a family of frontier AI models focused on reasoning, code, voice, image generation, and video. These are trained on massive infrastructure, including what the company describes as the world's largest supercluster (Colossus). Grok powers chatbots, APIs, and multimodal tools available via a unified API.[[2]](https://x.ai/)\n- **Current status (as of mid-2026)**: xAI operates as a subsidiary of SpaceX following an acquisition in February 2026. It is also connected to the X social platform (formerly Twitter), which xAI effectively became the parent of in 2025. The company has expanded into data centers and enterprise AI offerings (e.g., integrations with Amazon Bedrock and Databricks).[[3]](https://en.wikipedia.org/wiki/XAI_(company))\n- **Headquarters and team**: Based in the Stanford Research Park in Palo Alto, California. It was initially founded with a team of AI researchers and is led by Elon Musk as CEO.\n\nxAI positions itself as building maximally truth-seeking AI, distinct from other labs in its approach. Its official website (x.ai) highlights developer tools, API access, and ongoing model releases. Note that there is an unrelated blockchain/gaming project called Xai (xai.games), but the primary reference to \"xAI\" in this context is Musk's AI venture.[[4]](https://xai.games/)\n\nFor the latest updates, check x.ai or @xai on X.",
          "logprobs": [],
          "annotations": [
            {
              "type": "url_citation",
              "url": "https://x.ai/company",
              "start_index": 208,
              "end_index": 235,
              "title": "1"
            },
            {
              "type": "url_citation",
              "url": "https://x.ai/",
              "start_index": 585,
              "end_index": 605,
              "title": "2"
            },
            {
              "type": "url_citation",
              "url": "https://en.wikipedia.org/wiki/XAI_(company)",
              "start_index": 972,
              "end_index": 1022,
              "title": "3"
            },
            {
              "type": "url_citation",
              "url": "https://xai.games/",
              "start_index": 1555,
              "end_index": 1580,
              "title": "4"
            }
          ]
        }
      ],
      "id": "msg_5808284d-ae14-9981-9289-73515f67ebda",
      "role": "assistant",
      "type": "message",
      "status": "completed"
    }
  ],
  "parallel_tool_calls": true,
  "previous_response_id": null,
  "reasoning": {
    "effort": "low",
    "summary": "detailed"
  },
  ...
}

每个引用注释包含:

字段类型描述
typestring始终为 "url_citation"
urlstring来源 URL
start_indexint引用在响应文本中开始的字符位置
end_indexint引用在响应文本中结束的字符位置(不包括)
titlestring引用标签;对于文本引用,这是可见的引用编号(例如,"1"、"2")

图片嵌入也可以生成注释元数据。注释 title 不会显示在 Markdown 图片中。

python
# After streaming or sampling completes, access the structured inline citations:
for citation in response.inline_citations:
    print(f"Citation [{citation.id}]:")
    print(f"  Position: {citation.start_index} to {citation.end_index}")
    
    # Check citation type
    if citation.HasField("web_citation"):
        print(f"  Web URL: {citation.web_citation.url}")
    elif citation.HasField("x_citation"):
        print(f"  X URL: {citation.x_citation.url}")
python
# Access annotations from the response
for item in response.output:
    if item.type == "message":
        for content in item.content:
            if content.type == "output_text":
                for annotation in content.annotations:
                    print(f"Citation [{annotation.title}]:")
                    print(f"  URL: {annotation.url}")
                    print(f"  Position: {annotation.start_index} to {annotation.end_index}")
javascript
import { xai } from '@ai-sdk/xai';
import { streamText } from 'ai';

const { fullStream } = streamText({
  model: xai.responses('grok-4.5'),
  prompt: 'What is xAI?',
  tools: {
    web_search: xai.tools.webSearch(),
  },
});

// Access sources as they stream in
for await (const part of fullStream) {
  if (part.type === 'source' && part.sourceType === 'url') {
    console.log(`Citation: ${part.url}`);
  }
}
javascript
// Access annotations from the response
for (const item of response.output) {
  if (item.type === 'message') {
    for (const content of item.content) {
      if (content.type === 'output_text') {
        for (const annotation of content.annotations) {
          console.log(`Citation [${annotation.title}]:`);
          console.log(`  URL: ${annotation.url}`);
          console.log(`  Position: ${annotation.start_index} to ${annotation.end_index}`);
        }
      }
    }
  }
}
text
Citation [1]:
  Position: 37 to 76
  Web URL: https://x.ai/news/grok-4-fast
Citation [2]:
  Position: 124 to 171
  X URL: https://x.com/xai/status/1234567890

使用位置索引

start_indexend_index 值遵循 Python 切片约定:

  • start_index:引用的第一个 [ 的字符位置
  • end_index:紧接在结束 ) 之后(不包括)的字符位置

使用简单的切片从响应文本中提取确切的引用 Markdown:

python
content = response.content

for citation in response.inline_citations:
    # Extract the markdown link from the response text
    citation_text = content[citation.start_index:citation.end_index]
    print(f"Citation text: {citation_text}")

流式行内引用

在流式传输过程中,行内引用会被累积并可在最终响应中获取。当模型生成文本时,Markdown 链接实时出现在 chunk.content 中:

python
for response, chunk in chat.stream():
    # Markdown links appear in chunk.content in real-time
    if chunk.content:
        print(chunk.content, end="", flush=True)
    
    # Inline citations can also be accessed per-chunk during streaming
    for citation in chunk.inline_citations:
        print(f"\nNew citation: [{citation.id}]")

# After streaming, access all accumulated inline citations
print("\n\nAll inline citations:")
for citation in response.inline_citations:
    url = ""
    if citation.HasField("web_citation"):
        url = citation.web_citation.url
    elif citation.HasField("x_citation"):
        url = citation.x_citation.url
    print(f"  [{citation.id}] {url}")

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