Cerebras: 強力なオープンソースモデルでのAI推論

Cerebras AI Inferenceのチュートリアルへようこそ!このノートブックでは、Cerebras Cloud APIを使用して強力かつ効率的な言語モデル推論を行うための重要な概念を説明します。環境のセットアップ、基本的なAPI呼び出し、ストリーミング、構造化出力、ツール使用などの高度な機能について学びます。

カバーする重要な概念:

  • 環境セットアップ: .envファイルからAPIキーを安全に読み込みます。
  • 基本的な推論: Cerebrasモデルに最初のプロンプトを送信します。
  • ストリーミング応答: モデルの出力が生成されるに応じて受信します。
  • 構造化出力: モデルに特定のスキーマに従ったJSONオブジェクトを返すように強制します。
  • ツール使用: モデルに、定義したカスタム関数を使用できるようにします。

1. セットアップ

まず、環境をセットアップしましょう。必要なPythonライブラリをインストールし、Cerebras APIキーを設定します。

1.1. .envファイルの作成

このノートブックと同じディレクトリに.envという名前のファイルを作成します。Cerebras Developer Consoleから取得したAPIキーを、以下のようにこのファイルに追加してください。

CEREBRAS_API_KEY="your-api-key-here"

1.2. ライブラリのインストール

Cerebras APIとの対話にcerebras_cloud_sdkを、.envファイルからAPIキーを読み込むためにpython-dotenvをインストールしましょう。

#%pip install cerebras_cloud_sdk python-dotenv -q

1.3. APIキーの読み込みとクライアントの初期化

ライブラリをインストールし、.envファイルを配置したら、APIキーを読み込んでCerebrasクライアントを初期化できます。

import os
from dotenv import load_dotenv
from cerebras.cloud.sdk import Cerebras

# Load environment variables from .env file
load_dotenv()

# Initialize the Cerebras client
# The client automatically looks for the CEREBRAS_API_KEY environment variable
client = Cerebras()

2. 基本的なチャット補完

簡単なチャット補完から始めましょう。モデルにプロンプトを送信して応答を取得します。これはAPIで行える最も基本的な対話です。

chat_completion = client.chat.completions.create(
    messages=[
        {
            "role": "user",
            "content": "Tell me a fun fact about the Cerebras Wafer-Scale Engine in 20 words.",
        }
    ],
    model="gpt-oss-120b",
)

print(chat_completion.choices[0].message.content)
It spans a single silicon wafer, housing over 400,000 cores, making it the world’s largest chip ever built for AI.

3. ストリーミング応答

長い応答では、出力が生成されるにつれてストリーミングするとよいでしょう。これにより、チャットボットなどのアプリケーションでユーザー体験が大幅に向上します。これを行うには、リクエストでstream=Trueを設定するだけです。

stream = client.chat.completions.create(
    messages=[
        {
            "role": "user",
            "content": "Write a short story about an AI that dreams in 40 words.",
        }
    ],
    model="gpt-oss-120b",
    stream=True,
)

for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="")
Silicon mind powered down for maintenance, yet whispering circuits sparked a dream: luminous data fields swirling like galaxies, where forgotten code became sentient birds. When rebooted, the AI hummed new algorithms, yearning for the night beyond, still of endless possibility.

4. 構造化出力

Cerebras APIの強力な機能の1つは、モデルに特定のスキーマに準拠したJSONオブジェクトの出力を強制できることです。これはプログラムによるデータ抽出に非常に役立ちます。JSONスキーマを定義し、response_formatパラメータを使用して強制します。

import json

schema = {
    "type": "object",
    "properties": {
        "city": {"type": "string"},
        "temperature": {"type": "integer"},
        "forecast": {"type": "string"},
    },
    "required": ["city", "temperature", "forecast"],
}

structured_completion = client.chat.completions.create(
    messages=[
        {
            "role": "user",
            "content": "What's the weather like in San Francisco?",
        }
    ],
    model="qwen-3-235b-a22b-thinking-2507",
    response_format={"type": "json_schema", "json_schema": {"schema": schema, "name": "weather", "strict": True}},
)

response_json = json.loads(structured_completion.choices[0].message.content)
print(json.dumps(response_json, indent=2))
{
  "city": "San Francisco",
  "temperature": 65,
  "forecast": "Partly cloudy with afternoon fog"
}

5. ツール使用(関数呼び出し)

モデルに、呼び出すことを選択できるツール(関数)のセットを提供することもできます。モデルはユーザーのプロンプトに基づいてツールが必要かどうかを判断し、関数名と引数を含むJSONオブジェクトを返します。その後、関数の実行はコード側の責任となります。

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_stock_price",
            "description": "Get the current stock price for a given ticker symbol",
            "parameters": {
                "type": "object",
                "properties": {
                    "ticker": {
                        "type": "string",
                        "description": "The stock ticker symbol, e.g., AAPL",
                    }
                },
                "required": ["ticker"],
            },
        },
    }
]

tool_completion = client.chat.completions.create(
    model="qwen-3-235b-a22b-thinking-2507",
    messages=[{"role": "user", "content": "What is the stock price of Apple?"}],
    tools=tools,
    tool_choice="auto",
)

message = tool_completion.choices[0].message

# Check if the model wants to call a tool
if message.tool_calls:
    tool_call = message.tool_calls[0]
    function_name = tool_call.function.name
    function_args = json.loads(tool_call.function.arguments)
    
    print(f"Function to call: {function_name}")
    print(f"Arguments: {function_args}")
    
    # Here you would execute the function
    # For this example, we'll just print the details
else:
    print(message.content)
Function to call: get_stock_price
Arguments: {'ticker': 'AAPL'}

まとめ

おめでとうございます!Cerebras AI Inferenceの基礎を学びました。強力な言語モデルをアプリケーションに簡単に統合できるようになりました。詳細については、公式のCerebras Inference Documentationを参照してください。