SDKガイド
Ruby
ruby-openai gem で api14 を使う手順です。uri_base の設定と Rails の initializer 例から、チャット、ストリーミング、ツール呼び出し、構造化出力、画像入力、ゲートウェイのパラメーター、埋め込みまでを Ruby で示します。
ruby-openai gem を api14 で使います。uri_base を設定し、openai/gpt-5-mini などのモデル ID を使います。
インストール
gem install ruby-openai
export API14_API_KEY="sk-api14-..."
設定
ruby-openai は API バージョン(v1)を uri_base に付け足すため、ベースは https://api14.com/api となり、リクエストは https://api14.com/api/v1/... に送られます。
require "openai"
client = OpenAI::Client.new(
access_token: ENV.fetch("API14_API_KEY"),
uri_base: "https://api14.com/api",
request_timeout: 120
)
Rails アプリでは、イニシャライザーで gem を一度だけ設定し、引数なしでクライアントを作成します。
# config/initializers/openai.rb
OpenAI.configure do |config|
config.access_token = ENV.fetch("API14_API_KEY")
config.uri_base = "https://api14.com/api"
config.request_timeout = 120 # 秒。デフォルトは 120
end
client = OpenAI::Client.new
チャット
response = client.chat(
parameters: {
model: "openai/gpt-5-mini",
messages: [{ role: "user", content: "Explain vector databases in two sentences." }]
}
)
puts response.dig("choices", 0, "message", "content")
ストリーミング
stream に proc を渡します。チャンクごとに 1 回呼び出されます。
client.chat(
parameters: {
model: "anthropic/claude-sonnet-4.5",
messages: [{ role: "user", content: "Write a haiku about APIs." }],
stream: proc { |chunk, _bytesize| print chunk.dig("choices", 0, "delta", "content") }
}
)
ストリーミングを参照してください。
ツール呼び出し
require "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?" }]
loop do
response = client.chat(parameters: { model: "openai/gpt-5-mini", messages: messages, tools: tools })
message = response.dig("choices", 0, "message")
unless message["tool_calls"]
puts message["content"]
break
end
messages << message
message["tool_calls"].each do |call|
args = JSON.parse(call.dig("function", "arguments"))
messages << { role: "tool", tool_call_id: call["id"], content: get_weather(args["city"]).to_json } # 自分のメソッド
end
end
ツール呼び出しを参照してください。
構造化出力
response = client.chat(
parameters: {
model: "openai/gpt-5-mini",
messages: [{ role: "user", content: "Extract: Ada Lovelace, born 1815 in London." }],
response_format: {
type: "json_schema",
json_schema: {
name: "person",
strict: true,
schema: {
type: "object",
properties: { name: { type: "string" }, born: { type: "integer" }, city: { type: "string" } },
required: %w[name born city],
additionalProperties: false
}
}
}
}
)
person = JSON.parse(response.dig("choices", 0, "message", "content"))
構造化出力を参照してください。
画像入力
require "base64"
image = Base64.strict_encode64(File.binread("photo.png"))
client.chat(
parameters: {
model: "google/gemini-2.5-flash",
messages: [{
role: "user",
content: [
{ type: "text", text: "What is in this picture?" },
{ type: "image_url", image_url: { url: "data:image/png;base64,#{image}" } }
]
}]
}
)
画像とファイル入力を参照してください。
ゲートウェイのパラメーター
gem は parameters をそのまま転送するため、ゲートウェイのフィールドも直接使えます。
client.chat(
parameters: {
model: "openai/gpt-5-mini",
models: ["anthropic/claude-sonnet-4.5"], # フォールバック
provider: { sort: "throughput" },
reasoning: { effort: "low" },
messages: [{ role: "user", content: "Hi" }]
}
)
埋め込み
response = client.embeddings(
parameters: { model: "openai/text-embedding-3-small", input: ["The quick brown fox", "Lorem ipsum"] }
)
puts response.dig("data", 0, "embedding").length
エラー
HTTP エラーは Faraday::Error として発生します。レスポンスのハッシュには、ステータス、ヘッダー、OpenAI 形式のボディが含まれます。
begin
client.chat(parameters: { model: "openai/gpt-5-mini", messages: [{ role: "user", content: "Hi" }] })
rescue Faraday::Error => e
case e.response&.dig(:status)
when 402 then warn "Balance too low, add funds (insufficient_balance)"
when 429 then warn "Rate limited, retry after #{e.response[:headers]['retry-after']}s"
else raise
end
end
すべてのコードはエラーを参照してください。
バックオフ付きの再試行
ruby-openai はデフォルトでは再試行しません。小さなラッパーで rate_limited、5xx、タイムアウトを再試行し、daily_limit_reached と insufficient_balance は再試行しないようにします。
def with_retry(attempts: 5)
attempts.times do |i|
return yield
rescue Faraday::TimeoutError, Faraday::ConnectionFailed
raise if i == attempts - 1
sleep([2**i, 60].min + rand)
rescue Faraday::Error => e
status = e.response&.dig(:status).to_i
retryable = status >= 500 || (status == 429 && !e.response[:body].to_s.include?("daily_limit_reached"))
raise if !retryable || i == attempts - 1
wait = e.response.dig(:headers, "retry-after")&.to_i || 2**i
sleep([wait, 60].min + rand)
end
end
with_retry { client.chat(parameters: { model: "openai/gpt-5-mini", messages: [{ role: "user", content: "Hi" }] }) }
レート制限を参照してください。
すべての機能
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);