SPB Git

Repository Public

citations.md 16.6 KB 471 lines markdown

1<!-- source: https://docs.x.ai/developers/tools/citations (from https://docs.x.ai/llms-full.txt, retrieved 2026-09-19T05:28:55Z) -->2#### Tools34# Citations56The agent tools API provides two types of citation information: **All Citations** (a complete list of all sources encountered) and **Inline Citations** (markdown-style links embedded directly in the response text).78## All Citations910The `citations` attribute on the `response` object provides a comprehensive list of URLs for all sources the agent encountered during its search process. This list is **always returned by default** — no additional configuration is required.1112Citations are automatically collected from successful tool executions and provide full traceability of the agent's information sources. They are returned when the agentic request completes.1314Note that not every URL in this list will necessarily be directly referenced in the final answer. The agent may examine a source during its research process and determine it is not sufficiently relevant to the user's query, but the URL will still appear in this list for transparency.1516```pythonWithoutSDK17response.citations18```1920```output21[22'https://x.com/i/user/1912644073896206336',23'https://x.com/i/status/1975607901571199086',24'https://x.ai/news',25'https://docs.x.ai/developers/release-notes',26...27]28```2930## Inline Citations3132Inline citations are **markdown-style links** (e.g., `[[1]](https://x.ai/news)`) inserted directly into the response text at the points where the model references sources. In addition to these visible links, **structured metadata** is available on the response object with precise positional information.3334**Important**: Enabling inline citations does not guarantee that the model will cite sources on every answer. The model decides when and where to include citations based on the context and nature of the query.3536### Configuring Inline Citations3738Inline citation behavior differs between the **Responses API** and the **xAI Python SDK** (gRPC chat API).3940The **Responses API** behaviour applies to the following clients:4142* cURL against `/v1/responses`43* Python (OpenAI SDK)44* JavaScript (AI SDK via `xai.responses()`)45* JavaScript (OpenAI SDK)4647| | Responses API(cURL, Python/JS OpenAI SDK, JS AI SDK) | xAI Python SDK |48|---|---|---|49| **Default** | Enabled — response text may include `[[N]](url)` links without extra configuration | Disabled — omit `include`, or do not pass `"inline_citations"` |50| **Enable** | Enabled by default, no additional action needed. | Pass `include=["inline_citations"]` to the `chat.create()` method |51| **Disable** | Pass `include=["no_inline_citations"]` | Disabled by default |5253When inline citations are disabled, the response text will not contain any `[[N]](url)` markdown links. The `annotations` field on `output_text` content blocks may still be present, but annotations only list sources encountered during search — they will not have positional references into the response text.5455#### Enabled (default for Responses API; opt-in for xAI Python SDK)5657```bash customLanguage="bash" highlightedLines="10"58# Inline citations are enabled by default for the Responses API59curl https://api.x.ai/v1/responses \60  -H "Content-Type: application/json" \61  -H "Authorization: Bearer $XAI_API_KEY" \62  -d '{63  "model": "grok-4.6",64  "input": [65    {"role": "user", "content": "What is xAI?"}66  ],67  "tools": [{"type": "web_search"}]68}'69```7071```python customLanguage="pythonXAI" highlightedLines="14"72import os7374from xai_sdk import Client75from xai_sdk.chat import user76from xai_sdk.tools import web_search, x_search7778client = Client(api_key=os.getenv("XAI_API_KEY"))79chat = client.chat.create(80    model="grok-4.6",81    tools=[82        web_search(),83        x_search(),84    ],85    include=["inline_citations"],  # Enable inline citations (opt-in for xAI Python SDK)86)8788chat.append(user("What is xAI?"))89response = chat.sample()9091# Access the response text (includes inline citation markdown)92print(response.content)93```9495```python customLanguage="pythonOpenAISDK" highlightedLines="15"96import os97from openai import OpenAI9899client = OpenAI(100    api_key=os.getenv("XAI_API_KEY"),101    base_url="https://api.x.ai/v1",102)103104response = client.responses.create(105    model="grok-4.6",106    input=[107        {"role": "user", "content": "What is xAI?"}108    ],109    tools=[110        {"type": "web_search"},  # inline citations are enabled by default111    ],112)113114# Get the message output with inline citations115for item in response.output:116    if item.type == "message":117        for content in item.content:118            if content.type == "output_text":119                print(content.text)120```121122```javascript customLanguage="javascriptAISDK" highlightedLines="8"123import { xai } from '@ai-sdk/xai';124import { generateText } from 'ai';125126const { text, sources } = await generateText({127  model: xai.responses('grok-4.6'),128  prompt: 'What is xAI?',129  tools: {130    web_search: xai.tools.webSearch(), // inline citations are enabled by default131  },132});133134// Text includes inline citation markdown135console.log(text);136137// Sources contain all citation URLs138console.log('Sources:', sources);139```140141```javascript customLanguage="javascriptOpenAISDK" highlightedLines="13"142import OpenAI from 'openai';143144const client = new OpenAI({145  apiKey: process.env.XAI_API_KEY,146  baseURL: 'https://api.x.ai/v1',147});148149const response = await client.responses.create({150  model: 'grok-4.6',151  input: [152    { role: 'user', content: 'What is xAI?' }153  ],154  tools: [{ type: 'web_search' }], // inline citations are enabled by default155});156157// Get the message with inline citations158for (const item of response.output) {159  if (item.type === 'message') {160    for (const content of item.content) {161      if (content.type === 'output_text') {162        console.log(content.text);163      }164    }165  }166}167```168169#### Disabled (opt-out for Responses API; default for xAI Python SDK)170171```python customLanguage="pythonOpenAISDK" highlightedLines="17"172import os173from openai import OpenAI174175client = OpenAI(176    api_key=os.getenv("XAI_API_KEY"),177    base_url="https://api.x.ai/v1",178)179180response = client.responses.create(181    model="grok-4.6",182    input=[183        {"role": "user", "content": "What is xAI?"}184    ],185    tools=[186        {"type": "web_search"},187    ],188    include=["no_inline_citations"],  # Disable inline citations189)190191# Response text will not contain inline citation markdown192for item in response.output:193    if item.type == "message":194        for content in item.content:195            if content.type == "output_text":196                print(content.text)197```198199```python customLanguage="pythonRequests" highlightedLines="12"200import os201import requests202203response = requests.post(204    "https://api.x.ai/v1/responses",205    headers={206        "Content-Type": "application/json",207        "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}",208    },209    json={210        "model": "grok-4.6",211        "include": ["no_inline_citations"],212        "input": [213            {"role": "user", "content": "What is xAI?"}214        ],215        "tools": [{"type": "web_search"}],216    },217)218219data = response.json()220for item in data["output"]:221    if item["type"] == "message":222        for content in item["content"]:223            if content["type"] == "output_text":224                print(content["text"])225```226227```bash customLanguage="bash" highlightedLines="6"228curl https://api.x.ai/v1/responses \229  -H "Content-Type: application/json" \230  -H "Authorization: Bearer $XAI_API_KEY" \231  -d '{232  "model": "grok-4.6",233  "include": ["no_inline_citations"],234  "input": [235    {"role": "user", "content": "What is xAI?"}236  ],237  "tools": [{"type": "web_search"}]238}'239```240241### Markdown Citation Format242243When inline citations are enabled, the model will insert markdown-style citation links directly into the response text:244245```output246The 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)247```248249When rendered as markdown, this displays as clickable links:250251> 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)252253The format is `[[N]](url)` where:254255* `N` is the sequential display number for the citation **starting from 1**256* `url` is the source URL257258**Citation numbering**: Citation numbers always start from 1 and increment sequentially. If the same source is cited again later in the response, the original citation number will be reused.259260### Image Embeds261262When `enable_image_search` is enabled on the `web_search` tool, Grok may embed image results as Markdown images instead of numbered text citations:263264```output265Here are images of Starship on the launch pad:266![Why the SpaceX Starship launch pad matters](https://www.astronomy.com/wp-content/uploads/2024/09/starship-test-flight-mission-scaled.jpg)267```268269The format is `![alt](url)` where:270271* `alt` is a short description or title for the image272* `url` is the image source URL273274## Accessing Structured Inline Citation Data275276Structured inline citation data provides precise positional information about each citation in the response text.277278### Response Format279280When inline citations are enabled, each `output_text` content block includes an `annotations` array with structured citation metadata (URL, character offsets, and label):281282```json highlightedLines="16-45"283{284  "created_at": 1781829888,285  "completed_at": 1781829888,286  "id": "5808284d-ae14-9981-9289-73515f67ebda",287  "max_output_tokens": null,288  "model": "grok-4.6",289  "object": "response",290  "output": [291    ...292    {293      "content": [294        {295          "type": "output_text",296          "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 useful 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.",297          "logprobs": [],298          "annotations": [299            {300              "type": "url_citation",301              "url": "https://x.ai/company",302              "start_index": 208,303              "end_index": 235,304              "title": "1"305            },306            {307              "type": "url_citation",308              "url": "https://x.ai/",309              "start_index": 585,310              "end_index": 605,311              "title": "2"312            },313            {314              "type": "url_citation",315              "url": "https://en.wikipedia.org/wiki/XAI_(company)",316              "start_index": 972,317              "end_index": 1022,318              "title": "3"319            },320            {321              "type": "url_citation",322              "url": "https://xai.games/",323              "start_index": 1555,324              "end_index": 1580,325              "title": "4"326            }327          ]328        }329      ],330      "id": "msg_5808284d-ae14-9981-9289-73515f67ebda",331      "role": "assistant",332      "type": "message",333      "status": "completed"334    }335  ],336  "parallel_tool_calls": true,337  "previous_response_id": null,338  "reasoning": {339    "effort": "low",340    "summary": "detailed"341  },342  ...343}344```345346Each citation annotation contains:347348| Field | Type | Description |349|-------|------|-------------|350| `type` | string | Always `"url_citation"` |351| `url` | string | The source URL |352| `start_index` | int | Character position where the citation starts in the response text |353| `end_index` | int | Character position where the citation ends (exclusive) |354| `title` | string | The citation label; for text citations, this is the visible citation number (e.g., "1", "2") |355356Image embeds can also produce annotation metadata. The annotation `title` is not shown in the Markdown image.357358```python customLanguage="pythonXAI"359# After streaming or sampling completes, access the structured inline citations:360for citation in response.inline_citations:361    print(f"Citation [{citation.id}]:")362    print(f"  Position: {citation.start_index} to {citation.end_index}")363    364    # Check citation type365    if citation.HasField("web_citation"):366        print(f"  Web URL: {citation.web_citation.url}")367    elif citation.HasField("x_citation"):368        print(f"  X URL: {citation.x_citation.url}")369```370371```python customLanguage="pythonOpenAISDK"372# Access annotations from the response373for item in response.output:374    if item.type == "message":375        for content in item.content:376            if content.type == "output_text":377                for annotation in content.annotations:378                    print(f"Citation [{annotation.title}]:")379                    print(f"  URL: {annotation.url}")380                    print(f"  Position: {annotation.start_index} to {annotation.end_index}")381```382383```javascript customLanguage="javascriptAISDK"384import { xai } from '@ai-sdk/xai';385import { streamText } from 'ai';386387const { fullStream } = streamText({388  model: xai.responses('grok-4.6'),389  prompt: 'What is xAI?',390  tools: {391    web_search: xai.tools.webSearch(),392  },393});394395// Access sources as they stream in396for await (const part of fullStream) {397  if (part.type === 'source' && part.sourceType === 'url') {398    console.log(`Citation: ${part.url}`);399  }400}401```402403```javascript customLanguage="javascriptOpenAISDK"404// Access annotations from the response405for (const item of response.output) {406  if (item.type === 'message') {407    for (const content of item.content) {408      if (content.type === 'output_text') {409        for (const annotation of content.annotations) {410          console.log(`Citation [${annotation.title}]:`);411          console.log(`  URL: ${annotation.url}`);412          console.log(`  Position: ${annotation.start_index} to ${annotation.end_index}`);413        }414      }415    }416  }417}418```419420```output421Citation [1]:422  Position: 37 to 76423  Web URL: https://x.ai/news/grok-4-fast424Citation [2]:425  Position: 124 to 171426  X URL: https://x.com/xai/status/1234567890427```428429### Using Position Indices430431The `start_index` and `end_index` values follow Python slice convention:432433* **`start_index`**: Character position of the first `[` of the citation434* **`end_index`**: Character position immediately *after* the closing `)` (exclusive)435436Extract the exact citation markdown from the response text using a simple slice:437438```python customLanguage="pythonXAI"439content = response.content440441for citation in response.inline_citations:442    # Extract the markdown link from the response text443    citation_text = content[citation.start_index:citation.end_index]444    print(f"Citation text: {citation_text}")445```446447## Streaming Inline Citations448449During streaming, inline citations are accumulated and available on the final response. The markdown links appear in real-time in the `chunk.content` as the model generates text:450451```python customLanguage="pythonXAI"452for response, chunk in chat.stream():453    # Markdown links appear in chunk.content in real-time454    if chunk.content:455        print(chunk.content, end="", flush=True)456    457    # Inline citations can also be accessed per-chunk during streaming458    for citation in chunk.inline_citations:459        print(f"\nNew citation: [{citation.id}]")460461# After streaming, access all accumulated inline citations462print("\n\nAll inline citations:")463for citation in response.inline_citations:464    url = ""465    if citation.HasField("web_citation"):466        url = citation.web_citation.url467    elif citation.HasField("x_citation"):468        url = citation.x_citation.url469    print(f"  [{citation.id}] {url}")470```471
Files main
Menu

Theme