Cookieを使用しています. Cookieとブラウザストレージは、ログイン状態の維持と設定の保存に使われます。許可いただいた場合は、サイトの利用状況も計測します。はいつでも変更できます。詳しくはCookieポリシーをご覧ください。

Python

SDKガイド

Python

公式 openai Python パッケージで api14 を使う方法です。base_url と api_key の設定から、チャット、ストリーミング、ツール呼び出し、構造化出力、画像入力、画像生成、音声合成と文字起こし、再試行までを示します。

公式の openai Python パッケージを api14 で使います。base_url と api_key を設定し、model には任意のモデル ID(たとえば openai/gpt-5-mini)を指定します。

インストール

pip install openai
export API14_API_KEY="sk-api14-..."

設定

from openai import OpenAI
import os

client = OpenAI(
    base_url="https://api14.com/api/v1",
    api_key=os.environ["API14_API_KEY"],
)

非同期クライアントも利用できます。from openai import AsyncOpenAI は同じ引数を取ります。Web サーバーやバッチジョブなど、多くのリクエストを同時に実行する場合に使います。

import asyncio
from openai import AsyncOpenAI

aclient = AsyncOpenAI(base_url="https://api14.com/api/v1", api_key=os.environ["API14_API_KEY"])

async def ask(q):
    r = await aclient.chat.completions.create(model="openai/gpt-5-mini", messages=[{"role": "user", "content": q}])
    return r.choices[0].message.content

async def main():
    return await asyncio.gather(*(ask(q) for q in ["What is RAG?", "What is a token?"]))

answers = asyncio.run(main())

同時実行数は、プランの毎分リクエスト数の上限を下回るようにしてください。ガイド: バッチ処理を参照してください。

引数なしの OpenAI() は OPENAI_BASE_URL と OPENAI_API_KEY を読み取るため、環境変数だけで既存のアプリを api14 に向けられます。

export OPENAI_BASE_URL="https://api14.com/api/v1"
export OPENAI_API_KEY="sk-api14-..."

チャット

result = client.chat.completions.create(
    model="openai/gpt-5-mini",
    messages=[{"role": "user", "content": "Explain vector databases in two sentences."}],
)
print(result.choices[0].message.content)

ストリーミング

stream = client.chat.completions.create(
    model="anthropic/claude-sonnet-4.5",
    messages=[{"role": "user", "content": "Write a haiku about APIs."}],
    stream=True,
)
for chunk in stream:
    if chunk.choices:
        print(chunk.choices[0].delta.content or "", end="")

ストリーミングを参照してください。

ツール呼び出し

import json

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

while True:
    res = client.chat.completions.create(model="openai/gpt-5-mini", messages=messages, tools=tools)
    msg = res.choices[0].message
    if not msg.tool_calls:
        break
    messages.append(msg)
    for call in msg.tool_calls:
        args = json.loads(call.function.arguments)
        result = get_weather(**args)  # 自分の関数
        messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})

print(msg.content)

ツール呼び出しを参照してください。

構造化出力

client.chat.completions.parse は、Pydantic モデルを厳密な JSON Schema に変換し、解析済みのオブジェクトを返します。最近の openai のリリースが必要です。古い 1.x のバージョンでは client.beta.chat.completions.parse として提供されています。supported_parameters に structured_outputs または response_format が含まれるモデルを使ってください。

from pydantic import BaseModel

class Person(BaseModel):
    name: str
    born: int
    city: str

res = client.chat.completions.parse(
    model="openai/gpt-5-mini",
    messages=[{"role": "user", "content": "Extract: Ada Lovelace, born 1815 in London."}],
    response_format=Person,
)
person = res.choices[0].message.parsed  # Person(name='Ada Lovelace', born=1815, city='London')

構造化出力を参照してください。

画像入力

import base64

image = base64.b64encode(open("photo.png", "rb").read()).decode()

res = client.chat.completions.create(
    model="google/gemini-2.5-flash",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "What is in this picture?"},
            {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image}"}},
        ],
    }],
)

公開された https:// の URL も使えます。画像とファイル入力を参照してください。

画像

result = client.images.generate(
    model="openai/gpt-5.4-image-2",
    prompt="A minimalist product photo of a ceramic mug on a wooden table",
    n=1,
    extra_body={"aspect_ratio": "1:1"},
)
open("image.png", "wb").write(base64.b64decode(result.data[0].b64_json))

SDK が認識しないパラメーター(aspect_ratio、provider、models、reasoning)は extra_body に入れます。

音声合成と文字起こし

audio = client.audio.speech.create(
    model="openai/gpt-4o-mini-tts",
    input="Hello from api14!",
    voice="alloy",
)
audio.write_to_file("speech.mp3")

text = client.audio.transcriptions.create(
    model="openai/whisper-1",
    file=open("speech.mp3", "rb"),
)
print(text.text)

エラー

import openai

try:
    client.chat.completions.create(
        model="openai/gpt-5-mini",
        messages=[{"role": "user", "content": "Hi"}],
    )
except openai.APIStatusError as e:
    if e.status_code == 402:
        print("Balance too low, add funds:", e.code)  # insufficient_balance
    elif e.status_code == 429:
        print("Retry after", e.response.headers.get("retry-after"), "s:", e.code)  # rate_limited
    else:
        raise

エラーを参照してください。

タイムアウトと再試行

SDK は、接続エラー、408、409、429、5xx を、Retry-After に従いながら指数バックオフでデフォルトで 2 回再試行します。デフォルトのタイムアウトは 10 分です。どちらもクライアントで設定するか、with_options で呼び出しごとに設定できます。

import httpx

client = OpenAI(
    base_url="https://api14.com/api/v1",
    api_key=os.environ["API14_API_KEY"],
    timeout=httpx.Timeout(60.0, connect=5.0),
    max_retries=4,
)

client.with_options(timeout=300, max_retries=0).chat.completions.create(...)

daily_limit_reached や insufficient_balance は、再試行しても解決しません。再試行せず、停止してアラートを出してください。レート制限を参照してください。

すべての機能

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api14.com/api/v1",
  apiKey: process.env.API14_API_KEY,
});

const result = await client.chat.completions.create({
  "model": "openai/gpt-5-mini",
  "messages": [
    {
      "role": "user",
      "content": "Explain vector databases in two sentences."
    }
  ]
});
console.log(result.choices[0].message.content);