工具
集合搜索工具
集合搜索工具使 Grok 能够搜索您上传的知识库(集合),从而从您的文档中检索相关信息,以提供更准确和上下文相关的回答。该工具在分析复杂文档(如财务报告、法律合同或技术文档)时特别强大,Grok 可以在其中自主搜索多个文档并综合信息以回答复杂的分析问题。
有关集合的介绍,请查看集合文档。
核心功能
- 文档检索:在已上传的文件和集合中搜索以查找相关信息
- 语义搜索:根据含义和上下文查找文档,而不仅仅是关键词
- 知识库集成:将您的专有数据与 Grok 的推理能力无缝集成
- RAG 应用:支持检索增强生成工作流
- 多格式支持:可搜索 PDF、文本文件、CSV 和其他支持的格式
何时使用集合搜索
集合搜索工具在以下场景中特别有价值:
- 企业知识库:当您需要 Grok 引用内部文档和政策时
- 财务分析:分析多个文档中的 SEC 文件、收益报告和财务报表
- 客户支持:构建能够基于产品文档回答问题的聊天机器人
- 研究与尽职调查:综合学术论文、技术报告或行业分析中的信息
- 合规与法律:确保回答基于您的官方指南和规定
- 个人知识管理:组织和查询您的个人文档集合
SDK 支持
集合搜索工具在多个 SDK 和 API 中可用,但命名约定不同:
| SDK/API | 工具名称 | 描述 |
|---|---|---|
| xAI SDK | collections_search | 原生 xAI SDK 实现 |
| OpenAI Responses API | file_search | 与 OpenAI API 格式兼容 |
该工具也支持所有与 Responses API 兼容的 SDK。
实现示例
端到端财务分析示例
此综合示例展示了如何使用集合搜索工具分析特斯拉的 SEC 文件。它包括:
- 创建用于文档存储的集合
- 同时上传多个财务文档(10-Q 和 10-K 文件)
- 使用带集合搜索的 Grok 以智能方式分析和综合跨文档信息
- 启用代码执行,使模型在需要时能够进行计算和数学分析
- 获取带引用的回答和工具使用信息
此模式适用于任何需要搜索和推理多个文档的文档分析工作流。
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())import os
from openai import OpenAI
# Using OpenAI SDK with xAI API (requires pre-created collection)
api_key = os.getenv("XAI_API_KEY")
client = OpenAI(
api_key=api_key,
base_url="https://api.x.ai/v1",
)
# Note: You must create the collection and upload documents first using either the xAI console (console.x.ai) or the xAI SDK
# The collection_id below should be replaced with your actual collection ID
response = client.responses.create(
model="grok-4.5",
input=[
{
"role": "user",
"content": "How many consumer vehicles did Tesla produce in total in 2024 and 2025? Show your working and cite your sources.",
},
],
tools=[
{
"type": "file_search",
"vector_store_ids": ["your_collection_id_here"], # Replace with actual collection ID
"max_num_results": 10
},
{"type": "code_interpreter"}, # Enable code execution for calculations
],
)
print(response)import { createOpenAI } from '@ai-sdk/openai';
import { streamText } from 'ai';
const openai = createOpenAI({
baseURL: 'https://api.x.ai/v1',
apiKey: process.env.XAI_API_KEY,
});
const result = streamText({
model: openai('grok-4.5'),
prompt: 'What documents do you have access to?',
tools: {
file_search: openai.tools.fileSearch({
vectorStoreIds: ['your-vector-store-id'],
maxNumResults: 5,
}),
},
});import os
import requests
# Using raw requests (requires pre-created collection)
url = "https://api.x.ai/v1/responses"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"
}
payload = {
"model": "grok-4.5",
"input": [
{
"role": "user",
"content": "How many consumer vehicles did Tesla produce in total in 2024 and 2025? Show your working and cite your sources."
}
],
"tools": [
{
"type": "file_search",
"vector_store_ids": ["your_collection_id_here"], # Replace with actual collection ID
"max_num_results": 10,
},
{"type": "code_interpreter"} # Enable code execution for calculations
]
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())# Using curl (requires pre-created collection)
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": "How many consumer vehicles did Tesla produce in total in 2024 and 2025? Show your working and cite your sources."
}
],
"tools": [
{
"type": "file_search",
"vector_store_ids": ["your_collection_id_here"],
"max_num_results": 10
},
{
"type": "code_interpreter"
}
]
}'示例输出
当您运行上面的 Python xAI SDK 示例时,您将看到如下输出,展示了从集合创建到最终分析回答的完整工作流:
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)理解集合引用
使用集合搜索工具时,引用遵循特殊的 URI 格式,可唯一标识源文档:
collections://collection_id/files/file_id例如:
collections://collection_3be0eec8-ee8e-4a18-a9d4-fb70a3150d64/files/file_d4d1a968-9037-4caa-8eca-47a1563f28ab格式分解:
collections://:协议标识符,表示这是基于集合的引用collection_id:所搜索集合的唯一标识符(例如,collection_3be0eec8-ee8e-4a18-a9d4-fb70a3150d64)files/:表示文件级引用的路径段file_id:所引用特定文档文件的唯一标识符(例如,file_d4d1a968-9037-4caa-8eca-47a1563f28ab)
这些引用代表了 Grok 在搜索和分析过程中引用的您集合中的所有文档。每个引用指向集合中的特定文件,使您可以准确追溯哪些上传的文档促成了最终回答。
关键观察
自主搜索策略:Grok 在文档中自主执行 13 次不同的搜索,逐步优化查询以查找特定的季度和年度生产数据。
推理过程:输出显示推理令牌累积(199 → 3,352 个令牌),展示了模型在生成最终回答前如何思考问题。
引用来源:所有信息都基于上传的文档和特定的文件引用,确保透明度和可验证性。
结构化分析:最终回答分解了方法论,展示了计算,并明确说明了假设和限制(例如,2025 年第四季度数据尚未公布)。
令牌效率:注意大量缓存提示令牌(177,518 个)——这展示了集合搜索工具如何有效地在多个查询中重用上下文。
结合集合搜索与网络搜索/X-搜索
最强大的模式之一是将集合搜索工具与网络搜索/x-search 结合使用,以回答需要同时使用内部知识库和实时外部信息的问题。这 enables 复杂的分析,使回答基于您的专有数据,同时整合当前的市场情报、新闻和公众情绪。
示例:内部数据 + 市场情报
基于上面的特斯拉示例,让我们分析市场分析师如何根据我们内部文档中的生产数据看待特斯拉的表现:
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() 工具时,Grok 会自主确定最佳搜索策略:
- 内部分析优先:搜索您上传的特斯拉 SEC 文件以提取实际生产数据
- 外部上下文收集:执行网络/x-search 搜索以查找分析师报告、市场情绪和生产预期
- 综合分析:结合两个数据源提供全面分析,比较实际表现与市场预期
- 引用来源:返回来自您内部文档(使用
collections://URI)和外部网络来源(使用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)混合搜索的用例
此模式在以下场景中很有价值:
- 市场分析:将内部财务数据与外部市场情绪和竞争对手表现进行比较
- 竞争情报:将您的产品表现与行业报告和竞争对手公告进行比较分析
- 合规验证:将内部政策与当前法规要求和行业标准进行交叉参考
- 战略规划:将业务决策基于专有数据和实时市场状况
- 客户研究:将内部客户数据与外部评论、社交情绪和市场趋势相结合