Grok 3 API の使い方:開発者向け完全ガイド (2026年版)
xAIのGrok 3 APIをアプリケーションにセットアップして統合する
Hyperealで構築を始めよう
Kling、Flux、Sora、Veoなどに単一のAPIでアクセス。無料クレジットで開始、数百万規模まで拡張可能。
クレジットカード不要 • 10万人以上の開発者 • エンタープライズ対応
Grok 3 API の使い方:2026年版 開発者向け完全ガイド
xAIの Grok 3 は、2026年時点で利用可能な最も有能な大規模言語モデルの一つです。強力な推論能力、広大なコンテキストウィンドウ、そしてコンテンツポリシーに対する独自のアプローチで知られています。Grok 3 API を使用することで、開発者はプログラムからこのモデルにアクセスし、アプリケーション、チャットボット、分析ツールなどを構築できます。
このガイドでは、 API key の取得から最初のリクエストの実行まで、Python、JavaScript、cURL のコード例を交えて解説します。
Grok 3 API とは?
Grok 3 API は、xAI が提供する RESTful API であり、OpenAI 互換の chat completions フォーマットに従っています。すでに OpenAI API を使用したことがある場合、リクエストとレスポンスの構造が同じであるため、すぐに使いこなすことができるでしょう。
| 機能 | 詳細 |
|---|---|
| プロバイダー | xAI |
| Base URL | https://api.x.ai/v1 |
| API フォーマット | OpenAI 互換 (chat completions) |
| 利用可能なモデル | grok-3, grok-3-mini, grok-3-fast |
| コンテキストウィンドウ | 131,072 tokens |
| 最大出力 | 32,768 tokens |
| マルチモーダル | テキスト + 画像入力 |
| ストリーミング | 対応 |
| Function Calling | 対応 |
ステップ 1: API Key を取得する
- console.x.ai の xAI Console にアクセスします。
- アカウントを作成するか、ログインします。
- "API Keys" セクションに移動します。
- "Create API Key" をクリックします。
- キーをすぐにコピーしてください(一度しか表示されません)。
API key の形式:
xai-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
安全に保管してください:
- バージョン管理システム(Git等)にコミットしない
- 環境変数を使用する
- 本番環境ではシークレットマネージャーを使用する
キーを環境変数として設定します。
# macOS/Linux: ~/.bashrc または ~/.zshrc に追加
export XAI_API_KEY="xai-your-key-here"
# Windows PowerShell
$env:XAI_API_KEY = "xai-your-key-here"
# または .env ファイルを使用(このファイルはコミットしないでください)
echo 'XAI_API_KEY=xai-your-key-here' >> .env
ステップ 2: 最初のリクエストを実行する
cURL を使用する場合
curl https://api.x.ai/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $XAI_API_KEY" \
-d '{
"model": "grok-3",
"messages": [
{"role": "system", "content": "You are a helpful programming assistant."},
{"role": "user", "content": "Explain the difference between a stack and a queue."}
],
"temperature": 0.7,
"max_tokens": 1024
}'
Python を使用する場合
OpenAI Python SDK をインストールします(xAI は OpenAI 互換のため動作します)。
pip install openai
from openai import OpenAI
import os
# xAI の base URL を指定してクライアントを初期化
client = OpenAI(
api_key=os.environ.get("XAI_API_KEY"),
base_url="https://api.x.ai/v1",
)
# chat completion リクエストの作成
response = client.chat.completions.create(
model="grok-3",
messages=[
{"role": "system", "content": "You are a helpful coding assistant."},
{"role": "user", "content": "Write a Python function to find the longest palindrome in a string."}
],
temperature=0,
max_tokens=2048,
)
print(response.choices[0].message.content)
JavaScript/TypeScript を使用する場合
npm install openai
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env.XAI_API_KEY,
baseURL: 'https://api.x.ai/v1',
});
async function main() {
const response = await client.chat.completions.create({
model: 'grok-3',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'Explain microservices vs monolithic architecture.' }
],
temperature: 0.7,
max_tokens: 2048,
});
console.log(response.choices[0].message.content);
}
main();
ステップ 3: 利用可能なモデルの理解
xAI は複数の Grok 3 バリアントを提供しています。
| モデル | 速度 | 品質 | コスト | 最適な用途 |
|---|---|---|---|---|
grok-3 |
中程度 | 最高 | 最高 | 複雑な推論、分析 |
grok-3-mini |
高速 | 良好 | 低い | 一般的なタスク、チャットボット |
grok-3-fast |
最速 | 良好 | 最安 | 高スループットなアプリケーション |
# 高速レスポンスのために fast モデルを使用する例
response = client.chat.completions.create(
model="grok-3-fast",
messages=[
{"role": "user", "content": "What is the time complexity of binary search?"}
],
)
ステップ 4: レスポンスのストリーミング
より良いユーザー体験のために、トークンが生成されるたびに表示するストリーミングを使用します。
# Python ストリーミングの例
stream = client.chat.completions.create(
model="grok-3",
messages=[
{"role": "user", "content": "Write a detailed guide to Docker networking."}
],
stream=True,
max_tokens=4096,
)
for chunk in stream:
if chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end="", flush=True)
print() # 最後に改行
// TypeScript ストリーミングの例
const stream = await client.chat.completions.create({
model: 'grok-3',
messages: [
{ role: 'user', content: 'Explain Kubernetes pods in detail.' }
],
stream: true,
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || '';
process.stdout.write(content);
}
console.log();
ステップ 5: Function Calling (ツール利用)
Grok 3 は Function Calling をサポートしており、外部ツールとのやり取りが可能です。
import json
tools = [
{
"type": "function",
"function": {
"name": "search_database",
"description": "Search the product database for items matching a query",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query"
},
"category": {
"type": "string",
"enum": ["electronics", "books", "clothing"],
"description": "Product category to filter by"
},
"max_results": {
"type": "integer",
"description": "Maximum number of results to return"
}
},
"required": ["query"]
}
}
}
]
response = client.chat.completions.create(
model="grok-3",
messages=[
{"role": "user", "content": "Find me the top 5 electronics under $50"}
],
tools=tools,
tool_choice="auto",
)
# モデルが関数呼び出しを希望しているか確認
message = response.choices[0].message
if message.tool_calls:
for tool_call in message.tool_calls:
function_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
print(f"Function: {function_name}")
print(f"Arguments: {arguments}")
# 関数を実行して結果を返す処理
# result = search_database(**arguments)
# ... 結果を元に会話を継続
ステップ 6: Vision (画像入力)
Grok 3 はテキストと一緒に画像を分析できます。
response = client.chat.completions.create(
model="grok-3",
messages=[
{
"role": "user",
"content": [
{
"type": "text",
"text": "What's happening in this image? Describe it in detail."
},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image.jpg"
}
}
]
}
],
max_tokens=1024,
)
print(response.choices[0].message.content)
base64 エンコードを使用してローカル画像を使用する場合:
import base64
def encode_image(image_path):
with open(image_path, "rb") as f:
return base64.standard_b64encode(f.read()).decode("utf-8")
base64_image = encode_image("screenshot.png")
response = client.chat.completions.create(
model="grok-3",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Describe what you see in this screenshot."},
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{base64_image}"
}
}
]
}
],
)
ステップ 7: Grok 3 API の料金
| モデル | 入力 (100万トークンあたり) | 出力 (100万トークンあたり) |
|---|---|---|
| grok-3 | $3.00 | $15.00 |
| grok-3-mini | $0.30 | $0.50 |
| grok-3-fast | $5.00 | $25.00 |
コストの見積もり:
# おおよそのコスト見積もり
def estimate_cost(input_tokens, output_tokens, model="grok-3"):
pricing = {
"grok-3": {"input": 3.00, "output": 15.00},
"grok-3-mini": {"input": 0.30, "output": 0.50},
"grok-3-fast": {"input": 5.00, "output": 25.00},
}
rates = pricing[model]
input_cost = (input_tokens / 1_000_000) * rates["input"]
output_cost = (output_tokens / 1_000_000) * rates["output"]
return input_cost + output_cost
# 例: 1000 入力トークン, 500 出力トークン
cost = estimate_cost(1000, 500, "grok-3")
print(f"Estimated cost: ${cost:.6f}") # $0.010500
エラーハンドリングのベストプラクティス
from openai import OpenAI, APIError, RateLimitError, AuthenticationError
import time
client = OpenAI(
api_key=os.environ.get("XAI_API_KEY"),
base_url="https://api.x.ai/v1",
)
def call_grok(messages, max_retries=3):
for attempt in range(max_retries):
try:
response = client.chat.completions.create(
model="grok-3",
messages=messages,
max_tokens=2048,
)
return response.choices[0].message.content
except AuthenticationError:
print("Invalid API key. Check your XAI_API_KEY.")
raise
except RateLimitError:
wait_time = 2 ** attempt
print(f"Rate limited. Waiting {wait_time}s...")
time.sleep(wait_time)
except APIError as e:
print(f"API error: {e}")
if attempt == max_retries - 1:
raise
time.sleep(1)
raise Exception("Max retries exceeded")
よくある問題と解決策
| 問題 | 原因 | 解決策 |
|---|---|---|
| 401 Unauthorized | API key が無効または未設定 | XAI_API_KEY が正しく設定されているか確認 |
| 429 Too Many Requests | レート制限に到達 | エクスポネンシャルバックオフを実装する |
| 400 Bad Request | リクエストボディの形式不正 | JSON とパラメータを検証する |
| 413 Payload Too Large | 入力がコンテキスト制限を超過 | 入力トークンを減らす (最大 131K) |
| Timeout | 長時間の生成またはネットワーク問題 | タイムアウト時間を設定するか、ストリーミングを使用する |
| Empty response | max_tokens が低すぎる | max_tokens パラメータの値を増やす |
まとめ
Grok 3 API は、2026年において AI アプリケーションを構築するための強力で開発者フレンドリーな選択肢です。 OpenAI 互換のフォーマットにより、最小限のコード変更で他のプロバイダーから移行でき、各種モデル (grok-3, grok-3-mini, grok-3-fast) によって品質、速度、コストの最適化を柔軟に行えます。
画像生成、動画作成、リップシンク、音声クローンなど、テキスト以外の AI 生成を必要とするプロジェクトについては、Hypereal AI が LLM と並んで数十種類の特化型 AI モデルへの統合 API アクセスを提供しています。単一のプラットフォームから、完結した AI パワーのワークフローを構築することが可能です。
