xai-auth

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

xAI Grok API Authentication

xAI Grok API 认证指南

Complete guide for setting up and managing xAI API authentication for Grok models with Twitter/X integration.
这是一份完整的指南,介绍如何为集成了Twitter/X的Grok模型设置和管理xAI API认证。

Quick Start

快速开始

1. Get API Key

1. 获取API密钥

  1. Go to console.x.ai
  2. Sign in with your X (Twitter) account
  3. Navigate to "API Keys" section
  4. Click "Create API Key"
  5. Copy and save the key (starts with
    xai-
    )
  1. 访问 console.x.ai
  2. 使用你的X(Twitter)账号登录
  3. 导航至“API Keys”板块
  4. 点击“Create API Key”
  5. 复制并保存密钥(以
    xai-
    开头)

2. Set Environment Variable

2. 设置环境变量

bash
undefined
bash
undefined

Add to .bashrc, .zshrc, or .env

添加到.bashrc、.zshrc或.env文件中

export XAI_API_KEY="xai-your-key-here"
undefined
export XAI_API_KEY="xai-your-key-here"
undefined

3. Test Connection

3. 测试连接

bash
curl https://api.x.ai/v1/models \
  -H "Authorization: Bearer $XAI_API_KEY"
bash
curl https://api.x.ai/v1/models \
  -H "Authorization: Bearer $XAI_API_KEY"

Authentication Methods

认证方式

Method 1: Environment Variable (Recommended)

方式1:环境变量(推荐)

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"
)

Method 2: Direct Key

方式2:直接配置密钥

python
from openai import OpenAI

client = OpenAI(
    api_key="xai-your-key-here",
    base_url="https://api.x.ai/v1"
)
python
from openai import OpenAI

client = OpenAI(
    api_key="xai-your-key-here",
    base_url="https://api.x.ai/v1"
)

Method 3: Using xai-sdk

方式3:使用xai-sdk

python
from xai_sdk import Client

client = Client(api_key=os.getenv("XAI_API_KEY"))
python
from xai_sdk import Client

client = Client(api_key=os.getenv("XAI_API_KEY"))

API Compatibility

API兼容性

xAI API is fully compatible with OpenAI SDK:
python
undefined
xAI API 完全兼容OpenAI SDK
python
undefined

Just change base_url - everything else works the same

只需修改base_url - 其余用法完全一致

from openai import OpenAI
client = OpenAI( api_key=os.getenv("XAI_API_KEY"), base_url="https://api.x.ai/v1" # Only difference )
response = client.chat.completions.create( model="grok-3-fast", # Use Grok models messages=[{"role": "user", "content": "Hello!"}] )
undefined
from openai import OpenAI
client = OpenAI( api_key=os.getenv("XAI_API_KEY"), base_url="https://api.x.ai/v1" # 唯一区别 )
response = client.chat.completions.create( model="grok-3-fast", # 使用Grok模型 messages=[{"role": "user", "content": "Hello!"}] )
undefined

Free Credits

免费额度

$150/Month Free Credits

每月150美元免费额度

  1. Go to console.x.ai
  2. Navigate to Settings → Data Sharing
  3. Enable data sharing opt-in
  4. Receive $150/month in API credits
  1. 访问 console.x.ai
  2. 导航至“设置”→“数据共享”
  3. 启用数据共享选项
  4. 即可获得每月150美元的API额度

Credit Usage

额度计费标准

ActionCost
Grok 4.1 Fast (input)$0.20/1M tokens
Grok 4.1 Fast (output)$0.50/1M tokens
X Search / Web Search$5/1,000 calls
Code Execution$5/1,000 calls
操作费用
Grok 4.1 Fast(输入)0.20美元/百万tokens
Grok 4.1 Fast(输出)0.50美元/百万tokens
X搜索/网页搜索5美元/1000次调用
代码执行5美元/1000次调用

Configuration File

配置文件

Create
.env.xai
:
bash
undefined
创建
.env.xai
文件:
bash
undefined

xAI API Configuration

xAI API 配置

XAI_API_KEY=xai-your-key-here XAI_BASE_URL=https://api.x.ai/v1 XAI_DEFAULT_MODEL=grok-3-fast
undefined
XAI_API_KEY=xai-your-key-here XAI_BASE_URL=https://api.x.ai/v1 XAI_DEFAULT_MODEL=grok-3-fast
undefined

Error Handling

错误处理

Common Errors

常见错误

ErrorCauseSolution
no credits
No credits on accountAdd credits or enable free tier
invalid_api_key
Wrong or expired keyGenerate new key at console.x.ai
rate_limit_exceeded
Too many requestsImplement backoff, reduce frequency
model_not_found
Invalid model nameCheck available models
错误原因解决方案
no credits
账户无可用额度充值或启用免费层级
invalid_api_key
密钥错误或已过期在console.x.ai生成新密钥
rate_limit_exceeded
请求过于频繁实现退避机制,降低请求频率
model_not_found
模型名称无效检查可用模型列表

Python Error Handling

Python错误处理示例

python
from openai import OpenAI, APIError, RateLimitError

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

try:
    response = client.chat.completions.create(
        model="grok-3-fast",
        messages=[{"role": "user", "content": "Hello"}]
    )
except RateLimitError:
    print("Rate limit hit, waiting...")
    time.sleep(60)
except APIError as e:
    print(f"API error: {e}")
python
from openai import OpenAI, APIError, RateLimitError

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

try:
    response = client.chat.completions.create(
        model="grok-3-fast",
        messages=[{"role": "user", "content": "Hello"}]
    )
except RateLimitError:
    print("触发速率限制,等待中...")
    time.sleep(60)
except APIError as e:
    print(f"API错误: {e}")

Security Best Practices

安全最佳实践

  1. Never commit API keys to git
  2. Use environment variables instead of hardcoding
  3. Rotate keys regularly via console.x.ai
  4. Use separate keys for dev/prod environments
  5. Add to .gitignore:
    .env
    .env.*
    **/secrets.*
  1. 切勿将API密钥提交至git仓库
  2. 使用环境变量而非硬编码密钥
  3. 定期通过console.x.ai轮换密钥
  4. 为开发/生产环境使用不同密钥
  5. 将以下内容添加到.gitignore:
    .env
    .env.*
    **/secrets.*

Rate Limits

速率限制

ModelRequests/MinTokens/Min
Grok 4.1 Fast60100,000
Grok 43050,000
Grok 3 Mini100200,000
模型每分钟请求数每分钟tokens数
Grok 4.1 Fast60100,000
Grok 43050,000
Grok 3 Mini100200,000

Endpoints

接口端点

EndpointDescription
https://api.x.ai/v1/chat/completions
Chat completions
https://api.x.ai/v1/models
List available models
https://api.x.ai/v1/responses
Agent Tools API
端点描述
https://api.x.ai/v1/chat/completions
对话补全
https://api.x.ai/v1/models
列出可用模型
https://api.x.ai/v1/responses
Agent工具API

Related Skills

相关技能

  • xai-models
    - Model selection guide
  • xai-x-search
    - Twitter/X search
  • xai-sentiment
    - Sentiment analysis
  • xai-models
    - 模型选择指南
  • xai-x-search
    - Twitter/X搜索
  • xai-sentiment
    - 情感分析

References

参考资料