工具
Collections Search Tool
Collections search tool 使 Grok 能够搜索已上传的知识库(collection),从文档中检索相关信息,从而提供更准确且 context 更相关的 response。该 tool 特别适合分析财务报告、法律合同或技术文档等复杂资料;Grok 可以自主搜索多个文档并综合信息,回答复杂的分析问题。
有关 Collections 的介绍,请参阅 Collections 文档。
主要能力
文档检索:跨已上传文件和 collection 搜索相关信息
Semantic Search:根据含义和 context 查找文档,而不仅依赖 keyword
知识库集成:将专有数据与 Grok reasoning 无缝集成
RAG 应用:支持 retrieval-augmented generation workflow
多格式支持:跨 PDF、文本文件、CSV 和其他受支持格式进行搜索
何时使用 Collections Search
Collections search tool 特别适用于:
企业知识库:需要 Grok 引用内部文档和政策时
金融分析:跨多个文档分析 SEC filing、财报和财务报表
客户支持:构建可根据产品文档回答问题的 chatbot
研究与尽职调查:综合学术论文、技术报告或行业分析中的信息
合规与法律:确保 response 以官方指南和法规为依据
个人知识管理:整理和查询个人文档 collection
SDK 支持
Collections search tool 可通过多个 SDK 和 API 使用,其命名约定有所不同:
| SDK/API | Tool 名称 | 说明 |
|---|---|---|
| xAI SDK | collections_search | xAI SDK native implementation |
| OpenAI Responses API | file_search | 兼容 OpenAI API 格式 |
所有与 Responses API 兼容的 SDK 也支持该 tool。
实现示例
端到端金融分析示例
以下完整示例展示如何使用 collections search tool 分析 Tesla 的 SEC filing,涵盖:
创建用于文档存储的 collection
并发上传多个财务文档(10-Q 和 10-K filing)
使用 Grok 和 collections search,以 agentic 方式跨文档分析并综合信息
启用 code execution,使 model 能在需要时高效执行计算和数学分析。
接收带 citation 的 response 和 tool usage 信息
该模式适用于任何需要搜索多个文档并对其进行 reasoning 的文档分析 workflow。
import asyncio
import os
import httpx
from xai_sdk import AsyncClient
from xai_sdk.chat import user
from xai_sdk.proto import collections_pb2
from xai_sdk.tools import code_execution, collections_search
TESLA_10_Q_PDF_URL = "https://ir.tesla.com/_flysystem/s3/sec/000162828025045968/tsla-20250930-gen.pdf"
TESLA_10_K_PDF_URL = "https://ir.tesla.com/_flysystem/s3/sec/000162828025003063/tsla-20241231-gen.pdf"
async def main():
client = AsyncClient(api_key=os.getenv("XAI_API_KEY"), management_api_key=os.getenv("XAI_MANAGEMENT_API_KEY"))
# Step 1: Create a collection for Tesla SEC filings
response = await client.collections.create("tesla-sec-filings")
print(f"Created collection: {response.collection_id}")
# Step 2: Upload documents to the collection concurrently
async def upload_document(
url: str, name: str, collection_id: str, http_client: httpx.AsyncClient
) -> None:
pdf_response = await http_client.get(url, timeout=30.0)
pdf_content = pdf_response.content
print(f"Uploading {name} document to collection")
response = await client.collections.upload_document(
collection_id=collection_id,
name=name,
data=pdf_content,
)
# Poll until document is processed and ready for search
response = await client.collections.get_document(response.file_metadata.file_id, collection_id)
print(f"Waiting for document {name} to be processed")
while response.status != collections_pb2.DOCUMENT_STATUS_PROCESSED:
await asyncio.sleep(3)
response = await client.collections.get_document(response.file_metadata.file_id, collection_id)
print(f"Document {name} processed")
# Upload both documents concurrently
async with httpx.AsyncClient() as http_client:
await asyncio.gather(
upload_document(TESLA_10_Q_PDF_URL, "tesla-10-Q-2024.pdf", response.collection_id, http_client),
upload_document(TESLA_10_K_PDF_URL, "tesla-10-K-2024.pdf", response.collection_id, http_client),
)
# Step 3: Create a chat with collections search enabled
chat = client.chat.create(
model="grok-4.5", # Use a reasoning model for better analysis
tools=[
collections_search(
collection_ids=[response.collection_id],
),
code_execution(),
],
include=["verbose_streaming"],
)
# Step 4: Ask a complex analytical question that requires searching multiple documents
chat.append(
user(
"How many consumer vehicles did Tesla produce in total in 2024 and 2025? "
"Show your working and cite your sources."
)
)
# Step 5: Stream the response and display reasoning progress
is_thinking = True
async for response, chunk in chat.stream():
# View server-side tool calls as they happen
for tool_call in chunk.tool_calls:
print(f"\\nCalling tool: {tool_call.function.name} with arguments: {tool_call.function.arguments}")
if response.usage.reasoning_tokens and is_thinking:
print(f"\\rThinking... ({response.usage.reasoning_tokens} tokens)", end="", flush=True)
if chunk.content and is_thinking:
print("\\n\\nFinal Response:")
is_thinking = False
if chunk.content and not is_thinking:
print(chunk.content, end="", flush=True)
latest_response = response
# Step 6: Review citations and tool usage
print("\\n\\nCitations:")
print(latest_response.citations)
print("\\n\\nUsage:")
print(latest_response.usage)
print(latest_response.server_side_tool_usage)
print("\\n\\nTool Calls:")
print(latest_response.tool_calls)
if __name__ == "__main__":
asyncio.run(main())示例输出
运行上面的 Python xAI SDK 示例时,会看到类似以下输出,展示从创建 collection 到最终分析 response 的完整 workflow:
Created collection: collection_3be0eec8-ee8e-4a18-a9d4-fb70a3150d64
Uploading tesla-10-K-2024.pdf document to collection
Uploading tesla-10-Q-2024.pdf document to collection
Waiting for document tesla-10-K-2024.pdf to be processed
Waiting for document tesla-10-Q-2024.pdf to be processed
Document tesla-10-Q-2024.pdf processed
Document tesla-10-K-2024.pdf processed
Thinking... (199 tokens)
Calling tool: collections_search with arguments: {"query":"Tesla total vehicle production 2024","limit":10}
Thinking... (370 tokens)
Calling tool: collections_search with arguments: {"query":"Tesla total vehicles produced 2024","limit":5}
Thinking... (370 tokens)
Calling tool: collections_search with arguments: {"query":"Tesla vehicles produced 2025 Q1 Q2 Q3","limit":5}
Thinking... (477 tokens)
Calling tool: collections_search with arguments: {"query":"Tesla production and deliveries 2024 all quarters","limit":10}
Thinking... (477 tokens)
Calling tool: collections_search with arguments: {"query":"Tesla production and deliveries 2025 Q1 Q2 Q3","limit":10}
Thinking... (569 tokens)
Calling tool: collections_search with arguments: {"query":"Tesla total production 2024 full year consumer vehicles","limit":5}
Thinking... (776 tokens)
Calling tool: collections_search with arguments: {"query":"Tesla annual vehicle production 2024 total","limit":5}
Thinking... (1148 tokens)
Calling tool: collections_search with arguments: {"query":"Tesla Q4 2024 production and deliveries","limit":5}
Thinking... (1240 tokens)
Calling tool: collections_search with arguments: {"query":"Tesla Q1 2024 vehicle production","limit":3}
Thinking... (1240 tokens)
Calling tool: collections_search with arguments: {"query":"Tesla Q2 2024 vehicle production","limit":3}
Thinking... (1240 tokens)
Calling tool: collections_search with arguments: {"query":"Tesla Q3 2024 vehicle production","limit":3}
Thinking... (1240 tokens)
Calling tool: collections_search with arguments: {"query":"Tesla Q4 2024 vehicle production","limit":3}
Thinking... (2804 tokens)
Calling tool: collections_search with arguments: {"query":"Tesla vehicle production nine months 2024","limit":5}
Thinking... (3352 tokens)
Final Response:
### Working
To answer this question, I used the collections_search tool to query Tesla's official
financial filings (10-K and 10-Q reports) for production numbers. Tesla reports vehicle
production and deliveries quarterly, and consumer vehicles refer to passenger vehicles
like Model 3, Model Y, Model S, Model X, and Cybertruck (excluding Tesla Semi or other
non-consumer products).
#### Step 1: 2024 Production
Based on Tesla's official quarterly production and delivery reports (aggregated from SEC
filings and press releases referenced in the collections), Tesla produced **1,773,443
consumer vehicles in 2024**.
- Q1 2024: 433,371 produced
- Q2 2024: 410,831 produced
- Q3 2024: 469,796 produced
- Q4 2024: 459,445 produced
#### Step 2: 2025 Production
The Q3 2025 10-Q filing explicitly states: "In 2025, we produced approximately 1,220,000
consumer vehicles [...] through the third quarter."
- This is the sum of Q1, Q2, and Q3 2025 production
- Q4 2025 data is not available as of November 13, 2025
#### Step 3: Total for 2024 and 2025
- 2024 full year: 1,773,443
- 2025 (through Q3): 1,220,000
- **Total: 2,993,443 consumer vehicles**
Citations:
['collections://collection_3be0eec8-ee8e-4a18-a9d4-fb70a3150d64/files/file_d4d1a968-9037-4caa-8eca-47a1563f28ab',
'collections://collection_3be0eec8-ee8e-4a18-a9d4-fb70a3150d64/files/file_ff41a42e-6cdc-4ca1-918a-160644d52704']
Usage:
completion_tokens: 1306
prompt_tokens: 383265
total_tokens: 387923
prompt_text_tokens: 383265
reasoning_tokens: 3352
cached_prompt_text_tokens: 177518
{'SERVER_SIDE_TOOL_COLLECTIONS_SEARCH': 13}
Tool Calls:
... (omitted for brevity)理解 Collections Citation
使用 collections search tool 时,citation 使用一种特殊 URI 格式,以唯一标识 source document:
collections://collection_id/files/file_id例如:
collections://collection_3be0eec8-ee8e-4a18-a9d4-fb70a3150d64/files/file_d4d1a968-9037-4caa-8eca-47a1563f28ab格式解析:
collections://:protocol identifier,表示这是基于 collection 的 citationcollection_id:被搜索 collection 的唯一 identifier(例如collection_3be0eec8-ee8e-4a18-a9d4-fb70a3150d64)files/:表示 file-level reference 的 path segmentfile_id:被引用特定文档文件的唯一 identifier(例如file_d4d1a968-9037-4caa-8eca-47a1563f28ab)
这些 citation 表示 Grok 在搜索和分析过程中引用的全部 collection 文档。每个 citation 都指向 collection 中的特定文件,因此可以准确追溯哪些已上传文档参与了最终 response。
主要观察结果
自主搜索策略:Grok 自主对文档执行 13 次不同搜索,逐步细化 query,以查找特定季度和年度产量数据。
Reasoning 过程:输出显示 reasoning token 逐步累积(199 → 3,352 token),展示 model 在生成最终 response 前如何思考问题。
被引用的 Source:所有信息都以已上传文档为依据,并带有具体 file citation,确保透明且可验证。
结构化分析:最终 response 分解方法、展示计算,并明确说明假设和限制(例如 2025 年 Q4 数据尚不可用)。
Token 效率:大量 cached prompt token(177,518)表明 collections search tool 能够跨多个 query 高效复用 context。
将 Collections Search 与 Web Search/X Search 结合
一种强大模式是将 collections search tool 与 web search/x-search 结合,用于回答同时需要内部知识库和实时外部信息的问题。这样可以在以专有数据为依据的同时,结合当前市场情报、新闻和公众情绪进行复杂分析。
示例:内部数据 + 市场情报
基于上面的 Tesla 示例,根据内部文档中的产量数据,分析市场分析师如何看待 Tesla 的表现:
import asyncio
import httpx
from xai_sdk import AsyncClient
from xai_sdk.chat import user
from xai_sdk.proto import collections_pb2
from xai_sdk.tools import code_execution, collections_search, web_search, x_search
# ... (collection creation and document upload same as before)
async def hybrid_analysis(client: AsyncClient, collection_id: str, model: str) -> None:
# Enable collections search, web search, and code execution
chat = client.chat.create(
model=model,
tools=[
collections_search(
collection_ids=[collection_id],
),
web_search(), # Enable web search for external data
x_search(), # Enable x-search for external data
code_execution(), # Enable code execution for calculations
],
include=["verbose_streaming"],
)
# Ask a question that requires both internal and external information
chat.append(
user(
"Based on Tesla's actual production figures in my documents (collection), what is the "
"current market and analyst sentiment on their 2024-2025 vehicle production performance?"
)
)
is_thinking = True
async for response, chunk in chat.stream():
for tool_call in chunk.tool_calls:
print(f"\\nCalling tool: {tool_call.function.name} with arguments: {tool_call.function.arguments}")
if response.usage.reasoning_tokens and is_thinking:
print(f"\\rThinking... ({response.usage.reasoning_tokens} tokens)", end="", flush=True)
if chunk.content and is_thinking:
print("\\n\\nFinal Response:")
is_thinking = False
if chunk.content and not is_thinking:
print(chunk.content, end="", flush=True)
latest_response = response
print("\\n\\nCitations:")
print(latest_response.citations)
print("\\n\\nTool Usage:")
print(latest_response.server_side_tool_usage)工作原理
同时提供 collections_search() 和 web_search()/x_search() tool 时,Grok 会自主确定最佳搜索策略:
先进行内部分析:搜索已上传的 Tesla SEC filing,提取实际产量数据
收集外部 Context:执行 web/x-search,查找分析师报告、市场情绪和产量预期
综合分析:结合两类数据源,全面比较实际表现与市场预期
被引用的 Source:同时返回内部文档 citation(使用
collections://URI)与外部 web source citation(使用https://URL)
示例输出模式
Thinking... (201 tokens)
Calling tool: collections_search with arguments: {"query":"Tesla vehicle production figures 2024 2025","limit":20}
Thinking... (498 tokens)
Calling tool: collections_search with arguments: {"query":"Tesla quarterly vehicle production and deliveries 2024 2025","limit":20}
Thinking... (738 tokens)
Calling tool: web_search with arguments: {"query":"Tesla quarterly vehicle production and deliveries 2024 2025","num_results":10}
Thinking... (738 tokens)
Calling tool: web_search with arguments: {"query":"market and analyst sentiment Tesla vehicle production performance 2024 2025","num_results":10}
Thinking... (1280 tokens)
Final Response
... (omitted for brevity)Hybrid Search 使用场景
该模式适用于:
市场分析:将内部财务数据与外部市场情绪及竞品表现进行比较
竞争情报:对照行业报告和竞品公告分析产品表现
合规验证:交叉核对内部政策、当前监管要求和行业标准
战略规划:基于专有数据和实时市场状况制定业务决策
客户研究:结合内部客户数据与外部评价、社交情绪和市场趋势