OpenAI SDK

OpenAI の Python または Node.js SDK から HopBase を呼び出します。

既存の OpenAI SDK アプリケーションは、Base URL、プランキー、モデル ID を変更するだけで利用できます。アプリケーションの現在のフレームワークやエラーハンドリングはそのまま使用できます。

項目
Base URLhttps://api.hop-base.com/v1
キーの環境変数HOPBASE_OPENAI_API_KEY
対応モデルGPT、Gemini、GLM チャット、その他 OpenAI 互換モデル
モデル ID使用するキーで GET /v1/models を呼んだ際に返される ID を使用

キーをソースコードに含めない

HOPBASE_OPENAI_API_KEY はデプロイ先のプラットフォーム、ローカルの .env ファイル、またはシステムの環境変数経由で注入してください。.env や実際のキーを Git にコミットしないでください。

インストールして最小構成のリクエストを送る

SDK をインストールします:

python -m pip install openai

リクエストを送信します:

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.hop-base.com/v1",
    api_key=os.environ["HOPBASE_OPENAI_API_KEY"],
)

resp = client.chat.completions.create(
    model="gpt-5.6-sol",
    messages=[{"role": "user", "content": "Hello"}],
)
print(resp.choices[0].message.content)

まずプロンプトを「ok とだけ返信してください」にして検証します。アプリケーションが実際にストリーミングを使う場合のみ stream: true を追加し、SSE イベントが逐次届くことを確認してください。

ストリーミング出力と使用量の取得

stream_options.include_usage を渡すと、最後のイベントは choices が空になり、usage フィールドにそのリクエストのトークン使用量が入ります。

stream = client.chat.completions.create(
    model="gpt-5.6-sol",
    messages=[{"role": "user", "content": "Describe yourself in three sentences"}],
    stream=True,
    stream_options={"include_usage": True},
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:  # Last event: choices is empty, only usage is set
        print()
        print(chunk.usage)

ツール呼び出し

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Look up the weather for a city",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]
messages = [{"role": "user", "content": "What's the weather like in Shanghai today?"}]

resp = client.chat.completions.create(model="gpt-5.6-sol", messages=messages, tools=tools)
msg = resp.choices[0].message
if msg.tool_calls:
    call = msg.tool_calls[0]
    print(call.function.name, call.function.arguments)
    # Run the tool, then feed the result back; tool_call_id must match the previous call.id
    messages += [msg, {"role": "tool", "tool_call_id": call.id, "content": "Sunny, 26°C"}]
    resp = client.chat.completions.create(model="gpt-5.6-sol", messages=messages, tools=tools)
print(resp.choices[0].message.content)

タイムアウトと再試行

openai-python はデフォルトで読み取りタイムアウトが 600 秒、自動再試行は 2 回です。長い出力にはストリーミングを使用してください。同時実行数の上限とタイムアウトについては同時実行数、タイムアウト、課金を参照してください。

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.hop-base.com/v1",
    api_key=os.environ["HOPBASE_OPENAI_API_KEY"],
    timeout=600,    # seconds; prefer streaming for long outputs
    max_retries=2,  # automatic retries for connection errors, 429, and 5xx
)

このページの内容