xai-x-search
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesexAI X (Twitter) Search
xAI X(Twitter)搜索
Real-time Twitter/X search using Grok's native X integration - a capability unique to xAI.
借助Grok原生的X集成实现Twitter/X实时搜索——这是xAI独有的功能。
Quick Start
快速开始
python
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("XAI_API_KEY"),
base_url="https://api.x.ai/v1"
)python
import os
from openai import OpenAI
client = OpenAI(
api_key=os.getenv("XAI_API_KEY"),
base_url="https://api.x.ai/v1"
)Simple X search
Simple X search
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": "Search X for what people are saying about Tesla stock today"
}]
)
print(response.choices[0].message.content)
undefinedresponse = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": "Search X for what people are saying about Tesla stock today"
}]
)
print(response.choices[0].message.content)
undefinedSearch Capabilities
搜索功能
1. Topic Search
1. 主题搜索
python
def search_x_topic(topic: str) -> str:
"""Search X for posts about a topic."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"Search X for recent posts about {topic}. Summarize the main discussions and sentiment."
}]
)
return response.choices[0].message.contentpython
def search_x_topic(topic: str) -> str:
"""Search X for posts about a topic."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"Search X for recent posts about {topic}. Summarize the main discussions and sentiment."
}]
)
return response.choices[0].message.content2. Ticker/Stock Search
2. 股票代码搜索
python
def search_stock_mentions(ticker: str) -> str:
"""Search X for stock ticker mentions."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""Search X for mentions of ${ticker} stock.
Find:
- Recent discussions
- Sentiment (bullish/bearish)
- Key influencer opinions
- Breaking news mentions
Return structured analysis."""
}]
)
return response.choices[0].message.contentpython
def search_stock_mentions(ticker: str) -> str:
"""Search X for stock ticker mentions."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""Search X for mentions of ${ticker} stock.
Find:
- Recent discussions
- Sentiment (bullish/bearish)
- Key influencer opinions
- Breaking news mentions
Return structured analysis."""
}]
)
return response.choices[0].message.content3. Account Monitoring
3. 账户监控
python
def monitor_account(handle: str) -> str:
"""Get recent posts from a specific X account."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"Search X for the most recent posts from @{handle}. Summarize their latest activity."
}]
)
return response.choices[0].message.contentpython
def monitor_account(handle: str) -> str:
"""Get recent posts from a specific X account."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"Search X for the most recent posts from @{handle}. Summarize their latest activity."
}]
)
return response.choices[0].message.content4. Trending Topics
4. 热门话题
python
def get_trending() -> str:
"""Get current trending topics on X."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": "What are the current trending topics on X? List the top 10 with brief descriptions."
}]
)
return response.choices[0].message.contentpython
def get_trending() -> str:
"""Get current trending topics on X."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": "What are the current trending topics on X? List the top 10 with brief descriptions."
}]
)
return response.choices[0].message.contentAgent Tools API (Advanced)
Agent Tools API(进阶用法)
For more control, use the Agent Tools API:
python
undefined如需更多控制,可使用Agent Tools API:
python
undefinedUsing Responses API with x_search tool
Using Responses API with x_search tool
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": "Search X for posts about Bitcoin from the last 24 hours"
}],
tools=[{
"type": "x_search",
"x_search": {
"enabled": True,
"date_range": {
"start": "2025-12-04",
"end": "2025-12-05"
}
}
}]
)
undefinedresponse = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": "Search X for posts about Bitcoin from the last 24 hours"
}],
tools=[{
"type": "x_search",
"x_search": {
"enabled": True,
"date_range": {
"start": "2025-12-04",
"end": "2025-12-05"
}
}
}]
)
undefinedFilter by Handles
按账户筛选
python
undefinedpython
undefinedSearch only specific accounts
Search only specific accounts
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": "What are these financial analysts saying about the market?"
}],
tools=[{
"type": "x_search",
"x_search": {
"enabled": True,
"allowed_x_handles": [
"jimcramer",
"elonmusk",
"chaikinadx",
"unusual_whales"
]
}
}]
)
undefinedresponse = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": "What are these financial analysts saying about the market?"
}],
tools=[{
"type": "x_search",
"x_search": {
"enabled": True,
"allowed_x_handles": [
"jimcramer",
"elonmusk",
"chaikinadx",
"unusual_whales"
]
}
}]
)
undefinedCommon Use Cases
常见使用场景
Financial News Monitoring
财经新闻监控
python
def monitor_financial_news() -> dict:
"""Monitor financial news on X."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": """Search X for breaking financial news in the last hour.
Focus on:
- Market-moving news
- Earnings announcements
- Fed/economic news
- Major analyst calls
Return as JSON:
{
"breaking_news": [...],
"market_sentiment": "bullish/bearish/neutral",
"key_events": [...]
}"""
}]
)
return response.choices[0].message.contentpython
def monitor_financial_news() -> dict:
"""Monitor financial news on X."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": """Search X for breaking financial news in the last hour.
Focus on:
- Market-moving news
- Earnings announcements
- Fed/economic news
- Major analyst calls
Return as JSON:
{
"breaking_news": [...],
"market_sentiment": "bullish/bearish/neutral",
"key_events": [...]
}"""
}]
)
return response.choices[0].message.contentEarnings Reaction Tracking
财报反应追踪
python
def track_earnings_reaction(ticker: str) -> str:
"""Track X reaction to earnings announcement."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""Search X for reaction to ${ticker} earnings.
Analyze:
- Overall sentiment
- Key concerns raised
- Positive highlights mentioned
- Notable influencer reactions
- Volume of discussion"""
}]
)
return response.choices[0].message.contentpython
def track_earnings_reaction(ticker: str) -> str:
"""Track X reaction to earnings announcement."""
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""Search X for reaction to ${ticker} earnings.
Analyze:
- Overall sentiment
- Key concerns raised
- Positive highlights mentioned
- Notable influencer reactions
- Volume of discussion"""
}]
)
return response.choices[0].message.contentCompetitor Analysis
竞品分析
python
def compare_sentiment(tickers: list) -> str:
"""Compare X sentiment across multiple stocks."""
ticker_str = ", ".join([f"${t}" for t in tickers])
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""Compare X sentiment for: {ticker_str}
For each, provide:
- Current sentiment score (-1 to +1)
- Key themes being discussed
- Notable mentions
Return as structured comparison."""
}]
)
return response.choices[0].message.contentpython
def compare_sentiment(tickers: list) -> str:
"""Compare X sentiment across multiple stocks."""
ticker_str = ", ".join([f"${t}" for t in tickers])
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{
"role": "user",
"content": f"""Compare X sentiment for: {ticker_str}
For each, provide:
- Current sentiment score (-1 to +1)
- Key themes being discussed
- Notable mentions
Return as structured comparison."""
}]
)
return response.choices[0].message.contentSearch Parameters
搜索参数
| Parameter | Description | Max |
|---|---|---|
| Only search these accounts | 10 |
| Exclude these accounts | 10 |
| Start date (ISO8601) | - |
| End date (ISO8601) | - |
| Analyze images/videos | - |
| 参数 | 描述 | 最大值 |
|---|---|---|
| 仅搜索指定账户 | 10 |
| 排除指定账户 | 10 |
| 开始日期(ISO8601格式) | - |
| 结束日期(ISO8601格式) | - |
| 分析图片/视频 | - |
Rate Limits & Costs
速率限制与成本
| Metric | Value |
|---|---|
| Cost per search | $0.005 ($5/1,000) |
| Max handles filter | 10 |
| Date range | Any |
| 指标 | 数值 |
|---|---|
| 每次搜索成本 | $0.005(即1000次搜索5美元) |
| 最大账户筛选数量 | 10 |
| 日期范围 | 无限制 |
Best Practices
最佳实践
1. Be Specific
1. 明确搜索需求
python
undefinedpython
undefinedBad - too vague
Bad - too vague
"Search X for stocks"
"Search X for stocks"
Good - specific query
Good - specific query
"Search X for posts about $AAPL stock price movement today from verified financial accounts"
undefined"Search X for posts about $AAPL stock price movement today from verified financial accounts"
undefined2. Request Structured Output
2. 请求结构化输出
python
undefinedpython
undefinedRequest JSON for easier parsing
Request JSON for easier parsing
content = """Search X for $NVDA sentiment. Return JSON:
{
"sentiment": "bullish/bearish/neutral",
"score": -1 to 1,
"key_posts": [...],
"influencer_opinions": [...]
}"""
undefinedcontent = """Search X for $NVDA sentiment. Return JSON:
{
"sentiment": "bullish/bearish/neutral",
"score": -1 to 1,
"key_posts": [...],
"influencer_opinions": [...]
}"""
undefined3. Use Handle Filters for Quality
3. 使用账户筛选提升内容质量
python
undefinedpython
undefinedFilter to trusted sources
Filter to trusted sources
financial_handles = [
"DeItaone", # Breaking news
"unusual_whales", # Options flow
"Fxhedgers", # Market news
"zaborsky" # Analysis
]
undefinedfinancial_handles = [
"DeItaone", # Breaking news
"unusual_whales", # Options flow
"Fxhedgers", # Market news
"zaborsky" # Analysis
]
undefined4. Combine with Other Data
4. 结合其他数据使用
python
undefinedpython
undefinedCombine X sentiment with price data
Combine X sentiment with price data
x_sentiment = search_stock_mentions("AAPL")
price_data = finnhub_client.get_quote("AAPL")
x_sentiment = search_stock_mentions("AAPL")
price_data = finnhub_client.get_quote("AAPL")
Analyze together
Analyze together
undefinedundefinedLimitations
局限性
- Sarcasm detection - May misinterpret sarcastic posts
- Bot content - Cannot always filter bot posts
- Historical depth - Best for recent data
- Rate limits - $5/1,000 searches
- 讽刺检测 - 可能会误解带有讽刺意味的帖子
- 机器人内容 - 无法完全过滤机器人发布的内容
- 历史数据深度 - 更适合处理近期数据
- 速率限制 - 1000次搜索5美元
Error Handling
错误处理
python
def safe_x_search(query: str) -> dict:
"""X search with error handling."""
try:
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{"role": "user", "content": query}],
timeout=30
)
return {
"success": True,
"data": response.choices[0].message.content
}
except Exception as e:
return {
"success": False,
"error": str(e)
}python
def safe_x_search(query: str) -> dict:
"""X search with error handling."""
try:
response = client.chat.completions.create(
model="grok-4-1-fast",
messages=[{"role": "user", "content": query}],
timeout=30
)
return {
"success": True,
"data": response.choices[0].message.content
}
except Exception as e:
return {
"success": False,
"error": str(e)
}Related Skills
相关技能
- - Sentiment analysis
xai-sentiment - - Stock-specific sentiment
xai-stock-sentiment - - Advanced tool usage
xai-agent-tools
- - 情感分析
xai-sentiment - - 股票专属情感分析
xai-stock-sentiment - - 进阶工具使用
xai-agent-tools