mcpField
G
groq-api

groq-api

github.com/diskd-ai開発0199 回インストール41 週間前に更新
リポジトリ

groq-api について

groq-apiは、GroqのLLM推論サービスを使ったアプリ開発向けのスキルで、PythonやTypeScript/JavaScriptの開発者を対象とします。チャット補完、音声・画像処理、構造化出力、ツール利用、バッチ処理を扱います。

主な機能

  1. 01PythonとTypeScript/JavaScript SDK
  2. 02ストリーミングチャット補完
  3. 03JSONと構造化出力
  4. 04画像理解とOCR
  5. 05音声の文字起こし・翻訳・合成
  6. 06バッチ処理とプロンプトキャッシュ

活用シーン

  1. 01アプリへのLLMチャットの追加
  2. 02画像からテキストやデータを抽出
  3. 03文字起こしや音声生成フローの構築
  4. 04APIリクエストの一括処理

MCP 対応

Responses APIを通じてサードパーティのMCPサーバーに接続し、ツールを利用する方法を説明しています。

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/diskd-ai/groq-api --skill groq-api

インストール後、Claude Code で/groq-apiを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

.gitignore
README.md
references/
sdk.md
audio.md
prompt-caching.md
structured-outputs.md
models.md
moderation.md
reasoning.md
tool-use.md
api-reference.md
vision.md

詳細

Groq API

Groq の超高速 LLM 推論(300~1000+ トークン/秒)を使用してアプリケーションを構築します。

クイックスタート

インストール
# Python
pip install groq

# TypeScript/JavaScript
npm install groq-sdk
環境のセットアップ
export GROQ_API_KEY=<your-api-key>
基本的なチャット補完

Python:

from groq import Groq

client = Groq()  # Uses GROQ_API_KEY env var

response = client.chat.completions.create(
    model="llama-3.3-70b-versatile",
    messages=[{"role": "user", "content": "Hello"}]
)
print(response.choices[0].message.content)

TypeScript:

import Groq from "groq-sdk";

const client = new Groq();

const response = await client.chat.completions.create({
    model: "llama-3.3-70b-versatile",
    messages: [{ role: "user", content: "Hello" }],
});
console.log(response.choices[0].message.content);

モデルの選択

ユースケースモデル備考
高速+低コストllama-3.1-8b-instantシンプルなタスクに最適
バランス重視llama-3.3-70b-versatile品質とコストのバランス
最高品質openai/gpt-oss-120b組み込みツール+推論
エージェント型groq/compoundウェブ検索+コード実行
推論openai/gpt-oss-20b高速な推論(low/med/high)
ビジョン/OCRllama-4-scout-17b-16e-instruct画像理解
音声 STTwhisper-large-v3-turbo文字起こし
TTSplayai-ttsテキスト読み上げ

モデルの一覧と料金については、references/models.md を参照してください。

よく使われるパターン

ストリーミング応答
stream = client.chat.completions.create(
    model="llama-3.3-70b-versatile",
    messages=[{"role": "user", "content": "Tell me a story"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")
システムメッセージ
response = client.chat.completions.create(
    model="llama-3.3-70b-versatile",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello"}
    ]
)
非同期クライアント(Python)
import asyncio
from groq import AsyncGroq

async def main():
    client = AsyncGroq()
    response = await client.chat.completions.create(
        model="llama-3.3-70b-versatile",
        messages=[{"role": "user", "content": "Hello"}]
    )
    return response.choices[0].message.content

print(asyncio.run(main()))
JSON モード
response = client.chat.completions.create(
    model="llama-3.3-70b-versatile",
    messages=[{"role": "user", "content": "List 3 colors as JSON array"}],
    response_format={"type": "json_object"}
)
構造化出力(JSON Schema)

出力がスキーマに一致するように強制します。2 つのモードを利用できます。

モード保証モデル
strict: trueスキーマに 100% 準拠openai/gpt-oss-20b、openai/gpt-oss-120b
strict: false可能な限り準拠サポートされているすべてのモデル

厳格モード(準拠を保証):

response = client.chat.completions.create(
    model="openai/gpt-oss-20b",
    messages=[{"role": "user", "content": "Extract: John is 30 years old"}],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "person",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "age": {"type": "integer"}
                },
                "required": ["name", "age"],
                "additionalProperties": False
            }
        }
    }
)

Pydantic を使用:

from pydantic import BaseModel

class Person(BaseModel):
    name: str
    age: int

response = client.chat.completions.create(
    model="openai/gpt-oss-20b",
    messages=[{"role": "user", "content": "Extract: John is 30"}],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "person",
            "strict": True,
            "schema": Person.model_json_schema()
        }
    }
)
person = Person.model_validate(json.loads(response.choices[0].message.content))

スキーマ要件、検証ライブラリ、例については、references/structured-outputs.md を参照してください。

音声

文字起こし(音声からテキストへ)
with open("audio.mp3", "rb") as f:
    transcription = client.audio.transcriptions.create(
        model="whisper-large-v3-turbo",
        file=f,
        language="en",  # Optional: ISO-639-1 code
        response_format="verbose_json",  # json, text, verbose_json
        timestamp_granularities=["word", "segment"]
    )
print(transcription.text)
翻訳(英語へ)
with open("french_audio.mp3", "rb") as f:
    translation = client.audio.translations.create(
        model="whisper-large-v3",
        file=f
    )
print(translation.text)  # English text
テキスト読み上げ
response = client.audio.speech.create(
    model="playai-tts",
    input="Hello, world!",
    voice="Fritz-PlayAI",
    response_format="wav",  # flac, mp3, mulaw, ogg, wav
    speed=1.0  # 0.5 to 5
)
response.write_to_file("output.wav")

ビジョン

Llama 4 マルチモーダルモデルで画像を処理します。1 回のリクエストにつき最大 5 枚の画像をサポートします。

モデル: meta-llama/llama-4-scout-17b-16e-instruct(高速)、meta-llama/llama-4-maverick-17b-128e-instruct(高品質)

URL から画像を取得
response = client.chat.completions.create(
    model="meta-llama/llama-4-scout-17b-16e-instruct",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "What's in this image?"},
            {"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}
        ]
    }]
)
ローカル画像(Base64)
import base64

def encode_image(path: str) -> str:
    with open(path, "rb") as f:
        return base64.b64encode(f.read()).decode("utf-8")

response = client.chat.completions.create(
    model="meta-llama/llama-4-scout-17b-16e-instruct",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "Describe this image"},
            {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{encode_image('photo.jpg')}"}}
        ]
    }]
)
OCR/データを JSON として抽出
response = client.chat.completions.create(
    model="meta-llama/llama-4-scout-17b-16e-instruct",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "Extract all text and data as JSON"},
            {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{base64_image}"}}
        ]
    }],
    response_format={"type": "json_object"}
)

複数画像、画像を使ったツールの使用、複数ターンの会話については、references/vision.md を参照してください。

ツールの使用

ツール呼び出しのパターンと例については、references/tool-use.md を参照してください。

簡単な例:

import json

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get weather for a location",
        "parameters": {
            "type": "object",
            "properties": {"location": {"type": "string"}},
            "required": ["location"]
        }
    }
}]

response = client.chat.completions.create(
    model="llama-3.3-70b-versatile",
    messages=[{"role": "user", "content": "Weather in Paris?"}],
    tools=tools
)

if response.choices[0].message.tool_calls:
    for tc in response.choices[0].message.tool_calls:
        args = json.loads(tc.function.arguments)
        # Execute function and continue conversation

組み込みツール(エージェント型)

組み込みのウェブ検索とコード実行には、groq/compound または openai/gpt-oss-120b を使用します。

response = client.chat.completions.create(
    model="groq/compound",
    messages=[{"role": "user", "content": "Search for latest Python news"}]
)
# Model automatically uses web search

MCP(リモートツール)

Responses API を使用して、Stripe、GitHub、ウェブスクレイピングなどのツールを提供するサードパーティの MCP サーバーに接続します。

import openai

client = openai.OpenAI(
    api_key=os.environ.get("GROQ_API_KEY"),
    base_url="https://api.groq.com/openai/v1"
)

response = client.responses.create(
    model="openai/gpt-oss-120b",
    input="What models are trending on Huggingface?",
    tools=[{
        "type": "mcp",
        "server_label": "Huggingface",
        "server_url": "https://huggingface.co/mcp"
    }]
)

MCP の設定とよく使われるサーバーについては、references/tool-use.md を参照してください。

推論モデル

複雑な問題について、モデルの思考方法を制御します。

モデル: openai/gpt-oss-20b、openai/gpt-oss-120b(low/medium/high)、qwen/qwen3-32b(none/default)

推論の強度を指定した GPT-OSS
response = client.chat.completions.create(
    model="openai/gpt-oss-20b",
    messages=[{"role": "user", "content": "How many r's in strawberry?"}],
    reasoning_effort="high",  # low, medium, high
    temperature=0.6,
    max_completion_tokens=1024
)

print(response.choices[0].message.content)
print("Reasoning:", response.choices[0].message.reasoning)
推論を解析した Qwen3
response = client.chat.completions.create(
    model="qwen/qwen3-32b",
    messages=[{"role": "user", "content": "Solve: x + 5 = 12"}],
    reasoning_format="parsed"  # raw, parsed, hidden
)

print("Answer:", response.choices[0].message.content)
print("Reasoning:", response.choices[0].message.reasoning)
推論を非表示にする(GPT-OSS)
response = client.chat.completions.create(
    model="openai/gpt-oss-20b",
    messages=[{"role": "user", "content": "What is 15% of 80?"}],
    include_reasoning=False  # Hide reasoning in response
)

ストリーミング、推論を使ったツールの使用、ベストプラクティスについては、references/reasoning.md を参照してください。

バッチ処理

大量の非同期処理(完了までの期間:24 時間~7 日)については、次を参照してください。

# 1. Create JSONL file with requests
# 2. Upload file
# 3. Create batch
batch = client.batches.create(
    input_file_id=file_id,
    endpoint="/v1/chat/completions",
    completion_window="24h"
)

# 4. Check status
batch = client.batches.retrieve(batch.id)
if batch.status == "completed":
    results = client.files.content(batch.output_file_id)

バッチ API の詳細については、references/api-reference.md を参照してください。

プロンプトキャッシュ

プロンプトのプレフィックスが繰り返される場合、レイテンシとコストを自動的に 50% 削減します。コードの変更は不要です。

サポートされているモデル: moonshotai/kimi-k2-instruct-0905、openai/gpt-oss-20b、openai/gpt-oss-120b、openai/gpt-oss-safeguard-20b

仕組み:

  • 静的コンテンツ(システムプロンプト、ツール、例)を先頭に配置します
  • 動的コンテンツ(ユーザーのクエリ)を末尾に配置します
  • キャッシュがプレフィックスを自動的に照合し、50% 割引を適用します
  • キャッシュは使用されない状態が 2 時間続くと期限切れになります

キャッシュの使用状況を追跡する:

response = client.chat.completions.create(
    model="moonshotai/kimi-k2-instruct-0905",
    messages=[{"role": "system", "content": large_system_prompt}, ...]
)

cached = response.usage.prompt_tokens_details.cached_tokens
print(f"Cached tokens: {cached}")  # 50% discount applied to these

最適化の方法と例については、references/prompt-caching.md を参照してください。

コンテンツモデレーション

セーフガードモデルを使用して、有害なコンテンツを検出し、フィルタリングします。

Llama Guard 4

一般的なコンテンツの安全性を分類します。safe または unsafe\nSX(カテゴリコード)を返します。

response = client.chat.completions.create(
    model="meta-llama/Llama-Guard-4-12B",
    messages=[{"role": "user", "content": user_input}]
)

if response.choices[0].message.content.startswith("unsafe"):
    # Block or handle unsafe content
    pass
GPT-OSS Safeguard 20B

カスタムポリシーを使用して、プロンプトインジェクションを検出します。構造化された JSON を返します。

response = client.chat.completions.create(
    model="openai/gpt-oss-safeguard-20b",
    messages=[
        {"role": "system", "content": injection_detection_policy},
        {"role": "user", "content": user_input}
    ]
)
# Returns: {"violation": 1, "category": "Direct Override", "rationale": "..."}

ポリシー、危害の分類体系、統合パターンの全容については、references/moderation.md を参照してください。

エラー処理

from groq import Groq, RateLimitError, APIConnectionError, APIStatusError

client = Groq()

try:
    response = client.chat.completions.create(
        model="llama-3.3-70b-versatile",
        messages=[{"role": "user", "content": "Hello"}]
    )
except RateLimitError:
    # Wait and retry with exponential backoff
    pass
except APIConnectionError:
    # Network issue
    pass
except APIStatusError as e:
    # API error (check e.status_code)
    pass

ファイル処理、メタデータフィールド、プロンプトのガイドラインなど、音声 API の完全なリファレンスについては、references/audio.md を参照してください。

リソース

コメント